1

How to I read SharedPreferences value from another activity?

I have got setting.calss when i choose which activity start first it works great...

how to i read Preferences from other activities?

    final SharedPreferences settings = getPreferences(MODE_PRIVATE);
    int choice = settings.getInt("language", -1);

Open Dialog 3 activities:

    String[] activities = { "Activity 1", "Activity 2", "Activity 3" };

OnClick:

            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putInt("language", which);
                editor.commit();
                launchActivity(which);
            }
            }).show();
    } else {
        // start the activity and close this activity
        launchActivity(choice);
    }
}
user1710911
  • 629
  • 3
  • 7
  • 14

1 Answers1

6

On code behind;

SharedPreferences prefs = this.getSharedPreferences("title",Context.MODE_PRIVATE);
String LanSettining = prefs.getString("language", null);

You can also use following code:

Set:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit(); 
                        editor.putString("language", language);
                        editor.commit();

Read:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String language = settings.getString("language", "");
Sandeep
  • 2,693
  • 21
  • 27
  • the error said: The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (new DialogInterface.OnClickListener(){}) – user1710911 Nov 19 '13 at 10:39
  • You need to give the context of you activity and not of dialog. Just write there: ActivityName.this in place of context. – Sandeep Nov 19 '13 at 10:41
  • I have appreciate _Sandy_ your help but it always start MainActivity not the activity i have choose.. I have already store a Preference only i need read it from MainActivity. – user1710911 Nov 19 '13 at 10:57
  • Then you must be doing some small mistake. Try to print the value of shared preferences and see whether it's getting stored. – Sandeep Nov 19 '13 at 10:58
  • Yes, because when i opened setting.class an activity3 was chosen redirect to Activity3 – user1710911 Nov 19 '13 at 11:07