开发者

Android: string value is not getting in Shared Preference

I have created a shared prefe开发者_JS百科rence for a boolean value and for a string value. The boolean value is gotten in another activity. But for the string I am only getting default value.

Home.class

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor spe = prefs.edit();

    spe.putBoolean("flag", true); 
    spe.putString("user", "hello");
    spe.commit(); 

welcome.class

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean flag= prefs.getBoolean("flag", false); 
    String user=prefs.getString("user","Nothing");  

      TextView tv = new TextView(this);
      tv.setText("Flag : "+flag+(" User : "+user);

For 'user', only 'Nothing' is displaying. Where should I correct my code?


Try using:

SharedPreferences settings = getSharedPreferences(appName,0);
settings.getBoolean("flag", true);  
settings.getString("user", "hello"); 

And to put:

SharedPreferences settings = getSharedPreferences(appName,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag",true);
editor.putString("user","hello");
editor.commit();

This is what I use in my application, and it shares booleans/ints/strings accrossed many many Classes

Note: appName doesn't have to be the app name, like in the official tutorial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜