0

My Problem is, TextView is giving java.lang.NullPointerException if I do Orientation changes frequently. I pasted my code below. Am I missing something?

@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"));
    }
}
Yous
  • 728
  • 6
  • 22
kavie
  • 2,154
  • 4
  • 28
  • 53

1 Answers1

0

Try this way

@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());
    }
}

You're comparing the result of evaluating something that's null, that way it will give you a NullPointerException.

UPDATE

Reffer to this SO Post where the accepted answer points out that you need to search again for the TextView widget in onSaveInstanceState method.

how to save state with onSaveInstanceState and onRestoreInstanceState while orientation change

Community
  • 1
  • 1
reixa
  • 6,903
  • 6
  • 49
  • 68