我收到以下消息崩溃:
04-17 11:18:19.855: W/dalvikvm(368): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-17 11:18:19.925: E/AndroidRuntime(368): FATAL EXCEPTION: main
04-17 11:18:19.925: E/AndroidRuntime(368): java.lang.IllegalStateException: Could not execute method of the activity
04-17 11:18:19.925: E/AndroidRuntime(368): at android.view.View$1.onClick(View.java:2072)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.view.View.performClick(View.java:2408)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.view.View$PerformClick.run(View.java:8816)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.os.Handler.handleCallback(Handler.java:587)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.os.Handler.dispatchMessage(Handler.java:92)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.os.Looper.loop(Looper.java:123)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-17 11:18:19.925: E/AndroidRuntime(368): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 11:18:19.925: E/AndroidRuntime(368): at java.lang.reflect.Method.invoke(Method.java:521)
04-17 11:18:19.925: E/AndroidRuntime(368): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-17 11:18:19.925: E/AndroidRuntime(368): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-17 11:18:19.925: E/AndroidRuntime(368): at dalvik.system.NativeStart.main(Native Method)
04-17 11:18:19.925: E/AndroidRuntime(368): Caused by: java.lang.reflect.InvocationTargetException
04-17 11:18:19.925: E/AndroidRuntime(368): at com.UturpatShuPepper.LogCat.TheLogCatActivity.onGo(TheLogCatActivity.java:41)
04-17 11:18:19.925: E/AndroidRuntime(368): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 11:18:19.925: E/AndroidRuntime(368): at java.lang.reflect.Method.invoke(Method.java:521)
04-17 11:18:19.925: E/AndroidRuntime(368): at android.view.View$1.onClick(View.java:2067)
04-17 11:18:19.925: E/AndroidRuntime(368): ... 11 more
04-17 11:18:19.925: E/AndroidRuntime(368): Caused by: java.lang.ClassCastException: android.app.Application
04-17 11:18:19.925: E/AndroidRuntime(368): ... 15 more
我跟着调试器,看到崩溃发生在下面的代码中,在标记的行中:
// Go button pressed
public void onGo(View v) {
final EditText et = (EditText) findViewById(R.id.filters);
String filter = "food\\s+[ABC]";
if(!ValidateText(et, "^\\s*(" + filter + "(\\s+)" + filter + ")?$", "Bad filters")) {
return;
}
--->GlobalApp app = (GlobalApp) getApplication(); <--- CRASHES HERE
for(int i = 0; i < 100; i++) {
app.addMessage("message number " + i);
}
根据日志,它是由 ClassCastException 引起的。
我将 GlobalApp 类定义如下:
public class GlobalApp extends Application {
private final ArrayList<String> messages = new ArrayList<String>();
public ArrayList<String> getMessages(){
return messages;
}
public void addMessage(String msg){
messages.add(msg);
}
}
为什么选错了?正确的方法是什么?