2011-06-07 58 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(); 
} 
相關問題