开发者

Android app crashes because of Shared preferrence

in the first activity of my app, at sta开发者_Python百科rt i am checking whether the SharedPreferrence contains some value or not. If it is to be null, it open the first activity, if not i want to open the second activity of my app.

Following is part of my code.

SharedPreferences prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );
public void onCreate(Bundle savedInstanceState)
{       
   super.onCreate(savedInstanceState);  
   setContentView(R.layout.login);
  if(prefs.getString("idValue", "")==null)
    {
        userinfo();
    }
    else
    {
        Intent myIntent = new Intent(getBaseContext(), Add.class);
    startActivityForResult(myIntent, 0);
    }
}

When i checked in logcat it shows error at the following line

But my app gets crashed when the first activity gets opened

 SharedPreferences prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );

Following is the my logcat details....

AndroidRuntime(5747): Uncaught handler: thread main exiting due to uncaught exception
AndroidRuntime(5747): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gs.cc.sp/com.gs.cc.sp.UserInfo}: java.lang.NullPointerException
AndroidRuntime(5747): Caused by: java.lang.NullPointerException
AndroidRuntime(5747):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
AndroidRuntime(5747):     at com.gs.cc.sp.UserInfo.<init>(UserInfo.java:62)
AndroidRuntime(5747):     at java.lang.Class.newInstanceImpl(Native Method)
AndroidRuntime(5747):     at java.lang.Class.newInstance(Class.java:1479)
AndroidRuntime(5747):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
AndroidRuntime(5747):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)

Please friends tell me where i am going wrong


You are accessing the current instance this of your class before initiating ,Thats why you are getting nullpointer exception.

SharedPreferences prefs = null;
public void onCreate(Bundle savedInstanceState)
{       
   super.onCreate(savedInstanceState);  
   setContentView(R.layout.login);
prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );
  if(prefs.getString("idValue", "")==null)
    {
        userinfo();
    }
    else
    {
        Intent myIntent = new Intent(getBaseContext(), Add.class);
    startActivityForResult(myIntent, 0);
    }
}


You don't say, but I'm going to assume that you initialise some user info in your call to userinfo().

What you need to know about prefs.getString is that the it will never return null. The second argument you provide defines the value it will return if the preference does not exist - so in your example you should probably use:

if ( prefs.getString ( "idValue", "" ).equals ( "" ) )
{
    userinfo();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜