我将映射添加到列表,然后刷新阵列适配器。这在以前很完美,但是现在我使用来自两个不同方法的addItem()方法,它将抛出NullPointer。我希望我的代码能弄清我在说什么:
SimpleAdapter adapter;
List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();
ListView listthings;
int[] to;
String[] from;
String painLevelString, timeOfPainString, textTreatmentString,
painLocation, row1, row2, name;
OnCreate(){
if(getIntent().getStringExtra("newPainLevel")!= null){
createNewEditedEntry();
}
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout,
from, to);
listthings.setAdapter(adapter);
}
private void createNewEditedEntry() {
String newPainLevel = this.getIntent().getStringExtra("newPainLevel");
String newPainTime =this.getIntent().getStringExtra("newPainTime");
String newTreatment =this.getIntent().getStringExtra("newTreatment");
painLevelString = newPainLevel;
timeOfPainString = newPainTime;
textTreatmentString = newTreatment;
row1 = "sample1";
row2 = "sample2";
addItem();
//painItems.remove(getIntent().getStringExtra("position"));
//adapter.notifyDataSetChanged();
}
@Override
// on the activityresult,get the string extra, then add the item to the list
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
row1 = data.getStringExtra("com.painLogger.row1");
row2 = data.getStringExtra("com.painLogger.row2");
painLevelString = data.getStringExtra("com.painLogger.painLevel");
painLocation = data.getStringExtra("painLocation");
timeOfPainString = data.getStringExtra("com.painLogger.painTime");
textTreatmentString = data
.getStringExtra("com.painLogger.treatment");
addItem();
}
}
// to add the item, put it in the map, and add the map into the list
private void addItem() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("row_1", row1);
map.put("row_2", row2);
map.put("row_3", painLevelString);
map.put("row_4", painLocation);
map.put("row_5", timeOfPainString);
map.put("row_6",textTreatmentString);
painItems.add(map);
adapter.notifyDataSetChanged(); //Null Pointer **HERE**
}
需要明确的是,永远不会同时调用createNewEditedEntry()和onActivityResult()且不会发生冲突。他们是两个完全不同的事件。它仅与OnActivityResult一起使用,但是现在当我使用CreateNewEditedEntry()时,它已停止工作。我还检查并确保从意图中获取的所有字符串都不为空。
最佳答案
在adapter
中调用createNewEditedEntry
之前,需要初始化onCreate
:
OnCreate(){
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout, from, to);
if(getIntent().getStringExtra("newPainLevel")!= null){
createNewEditedEntry();
}
// ...
}
否则,
adapter
在从那里调用的addItem
中将为空(createNewEditedEntry
的最后一行)。