简体   繁体   中英

Writing data in SharedPrefer - Application stops responding

I am using the following code to store data in shared pref. However when ever this code is called , the virtual device tells me that the application stopped responding. Any suggestions why this is happening ?

SharedPreferences spref =       this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = spref.edit();
editor.putString("td", "SharedPref"); //name-value pair
editor.commit();

Edit: Now I am using the following

SharedPreferences spref = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE); SharedPreferences.Editor editor = spref.edit(); editor.putString("td", "SharedPref"); editor.commit();

But I am still Getting "The application has stopped unexpectedly..Please Try Again"

Looks like there was some problem with the virtual device. After recreating it my app started working fine.

尝试这个

SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(Context);

You are initializing the wrong initialization

final SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);

This will work.

In my apps i prefer using my own location names. Declare

public static final String PREFS_NAME = "MyPrefsFile";

then in the code

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  //0 might be bad naming, can just use MODE_PRIVATE or something instead depending on what you need to do :)
SharedPreferences.Editor editor = settings.edit();
editor.putInt("key", "value");
editor.commit();

shouldn't be any problems with this if the info you're saving is correct

EDIT

you also need to update your manifest with the following:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM