2

アプリの最初のアクティビティで、開始時に SharedPreferrence に何らかの値が含まれているかどうかを確認しています。null にする場合は最初のアクティビティを開きます。そうでない場合は、アプリの 2 番目のアクティビティを開きます。

以下は私のコードの一部です。

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)

友達に私が間違っているところを教えてください

4

2 に答える 2

6

開始する前にクラスの現在のインスタンスにアクセスしているため、thisnullpointer 例外が発生しています。

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);
    }
}
于 2011-06-07T10:09:31.773 に答える
0

あなたは言いませんが、への呼び出しでいくつかのユーザー情報を初期化すると仮定しますuserinfo()

あなたが知る必要prefs.getStringがあるのは、それが二度と戻らないということnullです. 指定する2番目の引数は、設定が存在しない場合に返される値を定義します-したがって、あなたの例ではおそらく次を使用する必要があります:

if ( prefs.getString ( "idValue", "" ).equals ( "" ) )
{
    userinfo();
}
于 2011-06-07T10:17:53.133 に答える