频繁的方向更改为Textview提供空指针异常

时间:2014-07-11 11:35:54

标签: android textview

我的问题是,如果我经常进行方向更改,TextView会提供 java.lang.NullPointerException 。我粘贴了下面的代码。我错过了什么吗?

@Override
public void onSaveInstanceState(Bundle outState) {

    if (title.getText().toString() != null) {      //Getting Null Exception here
        Log.i("onSaveInstanceState", "  "+title.getText().toString());
        outState.putString("title", title.getText().toString());
    }
}

-

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    view=inflater.inflate(R.layout.add, null);
    title =(TextView) view.findViewById(R.id.title);

    if (savedInstanceState.getString("title") != null) {
        Log.i("on create", " "+savedInstanceState.getString("title"));
        title.setText(savedInstanceState.getString("title"));
    }
}

1 个答案:

答案 0 :(得分:0)

试试这种方式

@Override
public void onSaveInstanceState(Bundle outState) {

    if (title.getText() != null) {      //Getting Null Exception here
        Log.i("onSaveInstanceState", "  "+title.getText().toString());
        outState.putString("title", title.getText().toString());
    }
}

您正在比较评估“null”的结果,这样会给您一个NullPointerException。

<强>更新

请参阅此SO帖子,其中接受的答案指出您需要再次搜索onSaveInstanceState方法中的TextView小部件。

  

how to save state with onSaveInstanceState and onRestoreInstanceState while orientation change