由于共享偏好,Android应用程序崩溃

Siv*_*a K 2 android switching sharedpreferences android-activity

在我的应用程序的第一个活动中,在开始时我正在检查SharedPreferrence是否包含某些值.如果它为null,则打开第一个活动,如果不是,我想打开我的应用程序的第二个活动.

以下是我的代码的一部分.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

当我检查logcat时,它显示以下行的错误

但是当第一个活动打开时我的应用程序崩溃了

 SharedPreferences prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );
Run Code Online (Sandbox Code Playgroud)

以下是我的logcat详细信息....

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)
Run Code Online (Sandbox Code Playgroud)

请朋友告诉我哪里出错了

Tan*_*dal 6

this在启动之前正在访问类的当前实例,这就是为什么您将获得nullpointer异常.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)