Adam
Adam

Reputation: 11

How to save and get SharedPreferences in different activities?

I've been having issues understanding how to save and read SharedPreferences. I'm trying to save four separate SharedPreferences but as I couldn't figure out how to do it, I decided to try with a simple String.

In this code I'm trying to create and save a string in SharedPreferences

        Button enrollNewStudent = (Button) findViewById(R.id.enrollStudentButton) ;

    enrollNewStudent.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            SharedPreferences prefs = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE);
            SharedPreferences.Editor editor = getSharedPreferences(getString(R.string.testing), MODE_PRIVATE).edit();
            editor.putString("name", "Dave");
            editor.commit();
            startActivity(new Intent(MainActivity.this, AddNewStudent.class));
        }
    });

And in this next part I'm trying to read the SharedPreferences and have a TextView set to it in a second activity.

        Context context = this;
    SharedPreferences sharedPref = getSharedPreferences(getString(R.string.testing),MODE_PRIVATE);
    String toPutInTextView = sharedPref.getString(getString(R.string.testing), null);

    TextView textView = findViewById(R.id.exampleTextView);
    textView.setText(toPutInTextView);

When I run this app and click the button to switch to the second activity the TextView on the second activity is blank.

Does anybody see a problem with this? I've been trying to piece together what I need to do from the android developers website and from other questions here but I just cannot get this working. This is for a university project.

Upvotes: 0

Views: 39

Answers (1)

Jacob Kaddoura
Jacob Kaddoura

Reputation: 175

The problem is: sharedPref.getString(getString(R.string.testing), null) is pulling using the string getString(R.string.testing) as the key. However, the key you used when you called "putString()" was "name". So you need to use "name" as your key for your getString() call.

Try:

String toPutInTextView = sharedPref.getString("name", "<default_value>");

Upvotes: 1

Related Questions