0

我有两个课程,第一个在我的 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

ApplicationContext 与 Activity Context 不同,应该使用 getgetActivity()而不是getApplicationContext。</p>

于 2015-03-18T02:21:25.243 回答
1

第 1 行:

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