Setting TextView with string variable (storing shared preferences) crashes app

Issue

I am attempting to store and retrieve data between fragments using SharedPreferences. I am trying to display the stored data in a TextView but can only manage to display it in a Toast. When the line "textView.setText(string);" is executed, the app crashes. "string" is a String variable storing the data.

I have read several threads on this topic but have not been able to figure out my issue yet. If anyone has any ideas as to what I’m doing wrong here, please let me know!

Retrieving SharedPreferences:

@Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.file, container, false);

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String string = sharedPreferences.getString("key","");
        TextView textView;
        textView = getActivity().findViewById(R.id.textView);

        textView.setText(string);    //<------------ Error occurs here
           //Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

//Toast.makeText(getActivity().getApplicationContext(),key,Toast.LENGTH_SHORT).show();  <---- Used for troubleshooting, displays value as intended

return root;
}

Setting SharedPreferences:

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    editor = sharedPreferences.edit();
    editor.putString(getString(R.string.checkbox),"True");
    editor.apply();
    editor.putString("key","Hellooooo");
    editor.apply();
}

Solution

Don’t do this. TextView is on a null object reference.

textView = getActivity().findViewById(R.id.textView);

Try this :

textView = root.findViewById(R.id.textView);

Answered By – Charles Raj I

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published