【问题标题】:Populating ListView with ArrayAdapter force closes使用 ArrayAdapter 强制关闭 ListView
【发布时间】:2012-10-30 22:19:37
【问题描述】:

我正在尝试使用以下代码使用预定义的字符串数组填充 ListView:

String[] schedule_names = getResources().getStringArray(R.array.test_schedules);

// Populate the ListView using the array of schedule names
ArrayList<String> als = new ArrayList<String>(Arrays.asList(schedule_names));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.id.listView, als);

adapter.add("Test");

ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);

但除非我注释掉 listView.setAdapter(adapter);,否则它会强制关闭(这显然意味着根本没有填充 ListView)。看来原因是NullPointerException

这是为什么?

【问题讨论】:

  • 错误日志会很有帮助

标签: android listview crash android-2.2-froyo


【解决方案1】:

这行错了……

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.id.listView, als);

...构造函数的第二个参数不应该是你的ListView,它应该是一个带有TextView的布局。

尝试将R.id.listView 替换为android.R.layout.simple_list_item_1

【讨论】:

  • 这解决了问题,谢谢! simple_list_item_1 是什么?
  • 没关系,事实证明这在stackoverflow.com/questions/3663745/… 中有解释,所以我将从这里链接以供将来参考。
  • 很高兴为您提供帮助。是的,这是一个很好的链接来解释预定义的 android.R.layout 资源。
猜你喜欢
  • 2014-11-19
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-17
  • 2013-08-26
相关资源
最近更新 更多