Mayank Thakur Mayank Thakur - 3 years ago 90
Java Question

shared preferenced across mutiple activities

I have a project where I need to use a shared preference. I'm just trying the shared preference at the moment, so instead of passing a string value through an intent, I'm passing it through a shared preference. in my first activity I have this:

SharedPreferences prefs = this.getSharedPreferences("com.example.mayankthakur.personalprojecttrial2", Context.MODE_PRIVATE);
Intent nameSave = getIntent();
name = nameSave.getStringExtra("name")
prefs.edit().putString(name, "name").apply();


in my second activity

SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
name = preferences.getString("name", name);
example.setText(name);


for now, i just have a textview in the second activity where I would like to show the value of string name. the app doesn't crash, but there is one bug. instead of showing the value of string name, the textview just shows "name" without the quotes. I looked this up and turns out I need a string key for the get string method and the put string. so I would like to know what a string key is (so I don't have this problem later) and how I can fix this issue in my code.

any help is greatly appreciated

Answer Source

there are two changes here..

prefs.edit().putString("name", name).apply();

instead of writing name in getstring you have to pass default value,so change your code like this,

   SharedPreferences preferences = getSharedPreferences("prefs", 
  Context.MODE_PRIVATE);

        example.setText(preferences.getString("name",null);

this will solve your problem

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download