skip to Main Content

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

2

Answers


  1. try using TinyDB it makes using sharedprefrences a lot easier
    TinyDB github documentation

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search