我正在尝试将列表中的选定项目传递给新活动。
我宣布了一个ArrayAdapter
ArrayAdapter madapter
OnCreate之前;在OnResume中,我收集数据;并将其分配给mAdapter
//variable mAdapter
//new ArrayAdapter string
madapter = new ArrayAdapter<String>(
SearchingMidwife.this,
android.R.layout.simple_list_item_checked,
locations);
//set List to display mAdapter
然后我有了这个,当点击listItem时,应该允许将所选项目转换为变量,并将其传递给新活动
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//in checked, in listview get Item positions for checked items
SparseBooleanArray checked = l.getCheckedItemPositions();
//assign selected items to new String ArrayList
ArrayList<String> selectedItems = new ArrayList<String>();
//determine size of items checked (number)
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
position = checked.keyAt(i);
// Add location if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
//add selected items to madapter
selectedItems.add(madapter.getItem(position));
}
//create string output array, store new string array with selected items
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(getApplicationContext(),
MidwifeResultList.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
我有一个结果活动,旨在收集所选项目并显示它:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_midwife_result_list);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("SelectedItems");
ListView lv = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
当我运行程序时,我可以看到listItem结果,但是当我选择一个程序停止时,就会出现这个错误:
无法启动活动ComponentInfo {android.bignerdranch.com.mobilemidwife / android.bignerdranch.com.mobilemidwife.MidwifeResultList}:java.lang.NullPointerException:storage == null
指向这行代码:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resultArr);
代码似乎是正确的......为什么resultArr上会出现空值?
答案 0 :(得分:0)
b.putStringArray("selectedItems", outputStrArr);
...
String[] resultArr = b.getStringArray("SelectedItems");
你有一个拼写错误,在一个地方写“selectedItems”,在另一个地方你写“SelectedItems”。请注意,第一个字母大写在一个而不是另一个。您应该将它们更改为相同。