开发者

Shared Preference issue in Android App

in my app i have three activities named as Home, SignIn and Add Page.

In my home Screen i have declared the Shared preference as follows

   Idprefs = PreferenceManager.getDefaultSharedPreferences(this);
   int UserId = Idprefs.getInt("useridValue", 0);

If UserId ==0 i goes to SignIn Activity or else to AddPage

In my SignIn Activity the user has to enter the name and password, from the server i get back an id in an xml file, which i am parsing and storing it the shared preference.

To use this value in other activities i have declared it as follows

public static SharedPreferences Idprefs;

in my oncreate method i have this

Idprefs = PreferenceManager.getDefaultSharedPreferences(this);

fro开发者_StackOverflowm my parsed values i am storing in Shared preference

SharedPreferences.Editor editor = Idprefs.edit();
editor.putInt("useridValue", userid);
editor.commit();

In my third Activity i have the following

int User = SignIn.Idprefs.getInt("useridValue",0);

here i am using the User value for other purposes.

Now the problem is all the above said functions work proper for the first time when the app i launched ie it will go as

HomeScreen--> SignIn --> AddPage

But when the app closed and opened for the second time the flow is as follows

HomeScreen --> AddPage

Now the app is getting crashed and i logcat it refers to the following line in AddPage Activity

 int User = SignIn.Idprefs.getInt("useridValue",0);

Second time SignIn page is not called so that it gets crashed. How can i get the stored value in other activities, pleas help me


You access the preferences through a class that was not instantiated (SignIn):

int User = SignIn.Idprefs.getInt("useridValue",0);

And therefore it's probably NULL.

It's a bad practice to access class members (especially when context is involved) this way. Just instantiate them each time in your current activity.


Are you accessing shared preferences after the super.onCreate() call in your activity? Otherwise, this will throw errors and cause the application to malfunction.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜