当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Unable Create any SharedPrefrences

问题描述:

I usually use this code for creating sharedPrefs file :

SharedPrefrences SP = getSharedPrefrences("MYPREF",0);

SP.getString("Username","x");

But now if I see this directory :

"/data/data/packageName/"

There is no shared_prefs directory.

Another thing : if I use Editor its work properly.

Please help me ..

网友答案:

First of all you have to SET the data with an Editor

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Pepito");
editor.apply();

Then you can read it as follows :

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "Here's the default value");

If you've set the value after make that getString() your String value will be "Pepito", otherwise you'll get "Here's the default value"

网友答案:

First you need to store some data in shared preferences using apply()/commit() method so that you retrieve data from there.

    SharedPrefrences SP = getSharedPrefrences("MYPREF",0);
    SP.edit().putString("Username","SOME NAME").apply();
    System.out.println("Username is : "+SP.getString("Username","x"));
分享给朋友:
您可能感兴趣的文章:
随机阅读: