NullPointerException正在ArrayList.add(String)上抛出

时间:2015-08-27 17:02:03

标签: java android arraylist nullpointerexception

我正在尝试将字符串添加到之前从内部存储文件中拉出的ArrayList。但是,此行会抛出NullPointerException。

ArrayList<String> names = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    createLayout();
    next.setOnClickListener(new View.OnClickListener() {
    @SuppressWarnings("unchecked")
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    String tripName = tripNameET.getText().toString(); //tripNameET is the EditText that provides the String to be put in the ArrayList
...
    FileInputStream fis1 = null;
    ObjectInputStream ois1 = null;
    try {
       fis1 = openFileInput("names");
       ois1 = new ObjectInputStream(fis1);
       names = (ArrayList<String>) ois1.readObject();
       ois1.close();
       fis1.close();
    } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    } catch (ClassNotFoundException e) {
       e.printStackTrace();
    }
    names.add(tripName); //NPE is Thrown Here
...
  }
}

2 个答案:

答案 0 :(得分:0)

tripName为空,这就是当您尝试添加列表时获取NPE的原因。 只需在添加到列表之前添加一个简单的检查。

     if(tripName!=null){
        names.add(tripName);
      }

答案 1 :(得分:0)

有可能将名称从readObject()反序列化为null。

请参阅this question