数组适配器NotifyDataSetChanged()NullPointerException Android

时间:2011-08-01 05:48:26

标签: java android android-listview android-adapter

我将地图添加到列表中,然后刷新数组适配器。这在早期工作得很好,但是现在我从两个不同的方法使用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()时,它已停止工作。我也检查并确保我从我的意图中获取的字符串都不为空。

2 个答案:

答案 0 :(得分:4)

adapter中致电createNewEditedEntry之前,您需要初始化onCreate

OnCreate(){
     adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout, from, to);
      if(getIntent().getStringExtra("newPainLevel")!= null){
        createNewEditedEntry();    
      }
// ...
}

否则,adapter在从那里调用的addItem中将为空(createNewEditedEntry的最后一行)。

答案 1 :(得分:0)

您还应该知道,当您在子活动中时,如果您的活动被Android销毁,您对addItem的调用可能会失败。阅读我对this question的回答,了解资源不足时会发生什么。