0

私は 2 つのクラスを持っています。最初のクラスは onclick にあります。

Intent myIntent = new Intent(getApplicationContext(), PlayGame.class);
        myIntent.putExtra("gameWord", Word.getRandomWord().toUpperCase());
        startActivity(myIntent);
        finish();

次に、受信クラスの onCreate 内に ;

    Bundle extras = getIntent().getExtras();

    String secretWord = extras.getString("gameWord");

Android アプリケーションを実行しようとすると、「startActivity(myIntent);」でエラーが発生します。何か案は?

これが私のlogCatです。

Shutting down VM
FATAL EXCEPTION: main
Process: com.example.hunglikeanandroid, PID: 3431
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hunglikeanandroid/com.example.hunglikeanandroid.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at com.example.hunglikeanandroid.MainActivity.<init>(MainActivity.java:35)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1572)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
4

3 に答える 3

2

getApplicationContext() を使用する代わりに、現在のアクティビティである MainActivity.this を使用します

Intent myIntent = new Intent(MainActivity.this, PlayGame.class);
 myIntent.putExtra("gameWord", Word.getRandomWord().toUpperCase());
 startActivity(myIntent);
于 2015-03-18T01:35:47.607 に答える
1

ライン1:

Intent myIntent = new Intent(FirstActivity.this, PlayGame.class);
于 2015-03-18T01:08:06.023 に答える
1

ApplicationContext は Activity Context とは異なります。getActivity()代わりにget を使用する必要がありgetApplicationContextます。</p>

于 2015-03-18T02:21:25.243 に答える