为什么每当我单击列表视图转到下一个活动时,应用活动都会崩溃



我似乎找不到我在代码中出错的地方。 无法继续比赛统计.class。 在应用程序日志猫中,此行是错误所属的位置 字符串选择匹配 = 列表项目.get(position(.toString((;

以下是"主要"活动

public class Matches extends AppCompatActivity {
private String selectedLeague;
private ListView listOfMatches;
private ArrayList<String> listCL = new ArrayList<String>();
final ArrayList<String> listItems = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matches);
Intent in = getIntent();
Bundle b = in.getExtras();
selectedLeague = b.getString("league");
listOfMatches = (ListView) findViewById(R.id.listOfMatches);
String[] CLMatches = new String[] { "Liverpool VS Real Madrid" };
for(int i = 0; i < CLMatches.length; i++){
listCL.add(CLMatches [i]);
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, listCL);
listOfMatches.setAdapter(adapter);
listOfMatches.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedMatch = listItems.get(position).toString();
Intent detailIntent = new Intent(view.getContext(), MatchStats.class);
}
});
}

}

比赛统计活动

public class MatchStats extends AppCompatActivity {
TextView choice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_stats);
Intent in = getIntent();
Bundle b = in.getExtras();
String selectedMatch = b.getString("match");
choice = (TextView) findViewById(R.id.textView);
choice.setText("You have selected the match " + selectedMatch);
}

}

listItems是空的,这就是你崩溃的原因。您将listCL传递给适配器,然后通过listItems请求项目,当然它会崩溃。

尝试像这样更改OnItemClickListener

listOfMatches.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedMatch = listCL.get(position).toString();
Intent detailIntent = new Intent(view.getContext(), MatchStats.class);
}
});

在代码中,您不会将任何捆绑包传递给意图。因此getExtras()将返回"null"。 您可以像这样传递捆绑包:

Intent detailIntent = new Intent(view.getContext(), MatchStats.class);
Bundle b = new Bundle();
b.putString("match", "value");
detailIntent.putExtras(b);
startActivity(detailIntent);

并像您一样访问它。

另一种方法:

若要传递字符串,请在调用detailsIntent之前,将字符串放入 Intent 中。

Intent detailIntent = new Intent(view.getContext(), MatchStats.class);
detailIntent.putExtra("match", "some value");
startActivity(detailIntent);

您可以从MatchStats这样的活动中访问它:

String selectedMatch = getIntent().getStringExtra("match"); // 'some value'

最新更新