2016-07-06 123 views
0

我试图弄清楚为什么在应用程序重新启动后无法访问我的SharedPreference文件。SharedPreference在应用程序重新启动后不可用

在在OnCreate我的应用程序类我定义我SharedPreference一次:

pref = getSharedPreferences(Util.PREF_FILE_NAME, Context.MODE_PRIVATE); 
editor = pref.edit(); 

然后在我的活动的onResume我打电话:

String userName = MyApp.getApplication().pref.getString(Util.USER_NAME, ""); 

但在这一点上的用户名是重启后总是空的。

-To保存我值:

MyApp.getApplication().editor.putString(Util.USER_NAME,"name").commit(); 

-For MyApp.getApplication()我在我的应用类中定义:

public MyApp() { 
    instance = this; 
} 
public static MyApp getApplication() { 
    if (instance == null) { 
     instance = new MyApp(); 
    } 
    return instance; 
} 

从我的设备I运行终端的应用程序和用'cat'命令我可以看到我的sharedPreference XML文件的内容。即使当我杀了我的应用程序,我可以看到sharedPreference文件仍然存在与我的正确值内。 但是,当我重新启动我的应用程序这个值不能被读取。那里发生了什么?

我已经注意到与Android棒棒糖的平板电脑我没有问题,但与Android Kitkat平板我有这个问题。

+0

您必须提交编辑。 'edit.commit();' –

+0

@ZahidulIslam这就是我对MyApp.getApplication()。editor.putString(Util.USER_NAME,“name”)。commit(); ? – AlexDG

+2

有没有机会Util.PREF_FILE_NAME更改应用午餐的价值? – X3Btel

回答

0

用于修改SharedPreferences对象中的值的接口。在编辑器中,你做的所有更改是成批的,而不是复制回原SharedPreferences直到调用commit()或应用()

,所以不要忘了你的editor.commit()

+0

他在更改后有.commit() – X3Btel

0

最好的,我使用方式:

Util.class

public static void saveIntToUserDefaults(Context c, String Key, int value) { 

    SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedpreferences.edit(); 
    editor.putInt(Key, value); 
    editor.commit(); 
    Log.e("Saved:", "" + Key + "-" + value); 
} 

public static String getFromUserDefaults(Context c, String Key) { 

    SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE); 

    return sharedpreferences.getString(Key, ""); 
} 

public static void clearUserDefaults(Context c) { 

    SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedpreferences.edit(); 
    editor.clear(); 
    editor.commit(); 
} 

我随时随地拨打电话&其工作精湛