2011-06-07 59 views
2

,在开始时我正在检查SharedPreferrence是否包含某个值。如果它是空的,它会打开第一个活动,如果没有,我想打开我的应用程序的第二个活动。Android应用程序崩溃,因为我的应用程序的第一个活动中共享偏好

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

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); 
    } 
} 

,当我在logcat的检查的话显示错误在以下行

但是,当第一个活动被打开

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

以下是我的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) 

请朋友告诉我我要去哪里错

+0

BTW:如果(prefs.getString(“idValue”,“”)== null)将永远不会为真,因为如果没有“idValue”,则会设置默认值(“”),该值不为空。 – Stuck 2011-06-07 10:16:07

回答

6

您正在访问您的类的当前实例this之前启动,这就是为什么你得到空指针异常。

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); 
    } 
} 
0

你不会说,但我会假设你在userinfo()的调用中初始化了一些用户信息。

你需要知道的关于prefs.getString的是它永远不会返回null。您提供的第二个参数定义,如果偏好不存在,将返回值 - 因此,在你的榜样,你应该使用:

if (prefs.getString ("idValue", "").equals ("")) 
{ 
    userinfo(); 
} 
相关问题