我阅读this教程并使用其中的代码在我的游戏中实现ScoreLoop服务。并提交得分正常,但显示其他Android活动或简单的Toast消息与NullPointer错误崩溃。
崩溃排队:
Intent intent = new Intent(mContext, EntryScreenActivity.class);
并在:
Toast.makeText(mContext, "Refreshing scores", Toast.LENGTH_SHORT).show();
在调试模式下,我看到mContext不为空
错误在哪里以及如何解决?
LogCat:
08-22 17:54:27.329: E/AndroidRuntime(15468): java.lang.NullPointerException 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.content.ContextWrapper.getResources(ContextWrapper.java:81) 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.widget.Toast.<init>(Toast.java:92) 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.widget.Toast.makeText(Toast.java:233) 08-22 17:54:27.329: E/AndroidRuntime(15468): at com.masterofcode.android.slingshot.ActionResolverAndroid$3.run(ActionResolverAndroid.java:46) 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.os.Handler.handleCallback(Handler.java:605) 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.os.Handler.dispatchMessage(Handler.java:92) 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.os.Looper.loop(Looper.java:137) 08-22 17:54:27.329: E/AndroidRuntime(15468): at android.app.ActivityThread.main(ActivityThread.java:4424) 08-22 17:54:27.329: E/AndroidRuntime(15468): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 17:54:27.329: E/AndroidRuntime(15468): at java.lang.reflect.Method.invoke(Method.java:511) 08-22 17:54:27.329: E/AndroidRuntime(15468): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 08-22 17:54:27.329: E/AndroidRuntime(15468): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 08-22 17:54:27.329: E/AndroidRuntime(15468): at dalvik.system.NativeStart.main(Native Method)
========================================================================
public class ActionResolverAndroid implements ActionResolver {
Handler uiThread;
BumbleAndroid mContext; //Your class here which extends AndroidApplication
ScoreloopHandler handler;
public ActionResolverAndroid(BumbleAndroid mContext) {
uiThread = new Handler(); //This binds the handler to the "main" thread, see documentation of handler
this.mContext = mContext;
handler = new ScoreloopHandler(mContext);
}
}
通过这种方式我获得了mContext
答案 0 :(得分:1)
这个问题:Null at android.content.ContextWrapper.getResources(ContextWrapper.java:80)暗示当在错误的上下文中调用时,getResources将返回null(看起来你需要当前Activity的上下文来制作Toast)。
这是另一个具有类似含义的问题:Difference between Activity Context and Application Context
很高兴能找到更具体的文档,但我还没找到......
答案 1 :(得分:0)
问题在于错误的mContext。
正确的代码是:
public class MyGameAndroidActivity extends AndroidApplication implements
ActionResolver {
public void showScoreloop() {
Intent intent = new Intent(this, EntryScreenActivity.class);
this.startActivity(intent);
}
}