我正在向列表中添加一個映射,然後刷新陣列適配器。這在早期工作完美,但現在我使用了來自兩種不同方法的addItem()方法,它引發了一個NullPointer。我希望我的代碼將清理我所說的話:數組適配器NotifyDataSetChanged()NullPointerException Android
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()時,它已停止工作。我也檢查並確保我從我的意圖中獲取的任何字符串都不爲空。
非常感謝您的回覆!我不能接受答案(它不會讓我再等3分鐘),但我認爲它解決了它(我遇到了另一個(無關的)錯誤)。 – Kgrover
@Kgrover - 您歡迎。 – MByD