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


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:

    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(;

        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:

public void onCreate(Bundle savedInstanceState){

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    editor = sharedPreferences.edit();


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

textView = getActivity().findViewById(;

Try this :

textView = root.findViewById(;

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