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

时间:2018-07-08 16:56:04

标签: android

我似乎找不到代码中哪里出了错。无法继续进行MatchStats.class。在应用程序logcat中,此行是错误所属的字符串String selectedMatch = listItems.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);

        }
    });
}

}

matchstats活动

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);

}

}

2 个答案:

答案 0 :(得分:0)

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);

    }
});

答案 1 :(得分:0)

在您的代码中,您没有将任何捆绑软件传递给该意图。因此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 detailIntent = new Intent(view.getContext(), MatchStats.class);
detailIntent.putExtra("match", "some value");
startActivity(detailIntent);

您可以从MatchStats活动中访问此文件,如下所示:

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