我已经尝试了所有形式的错误检查,以便捕获并处理错误检查,但没有任何作用,它一直在崩溃。
Cursor cursor = null;
try{
cursor = mydb.getAllRows();
}finally{
if(cursor == null)
{
// I want to exit here and do nothing.
// Crashes here.
}
else{if(cursor.moveToFirst()){
do{
String id= cursor.getString(0);
String text = cursor.getString(1);
String cooktime = cursor.getString(2);
String difficulty = cursor.getString(3);
String making = cursor.getString(4);
}while(cursor.moveToNext());
}
cursor.close();
}
}
我知道mydb中没有任何内容,所以如何对此问题进行错误检查,以免崩溃。
错误记录
12-03 14:54:21.259: E/AndroidRuntime(16766): FATAL EXCEPTION: main
12-03 14:54:21.259: E/AndroidRuntime(16766): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exasmple.test/com.exasmple.test.List_of_recipes}: java.lang.NullPointerException
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.ActivityThread.access$900(ActivityThread.java:148)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.os.Handler.dispatchMessage(Handler.java:99)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.os.Looper.loop(Looper.java:137)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.ActivityThread.main(ActivityThread.java:5457)
12-03 14:54:21.259: E/AndroidRuntime(16766): at java.lang.reflect.Method.invokeNative(Native Method)
12-03 14:54:21.259: E/AndroidRuntime(16766): at java.lang.reflect.Method.invoke(Method.java:525)
12-03 14:54:21.259: E/AndroidRuntime(16766): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:854)
12-03 14:54:21.259: E/AndroidRuntime(16766): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670)
12-03 14:54:21.259: E/AndroidRuntime(16766): at dalvik.system.NativeStart.main(Native Method)
12-03 14:54:21.259: E/AndroidRuntime(16766): Caused by: java.lang.NullPointerException
12-03 14:54:21.259: E/AndroidRuntime(16766): at com.exasmple.test.List_of_recipes.onCreate(List_of_recipes.java:114)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.Activity.performCreate(Activity.java:5234)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-03 14:54:21.259: E/AndroidRuntime(16766): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
12-03 14:54:21.259: E/AndroidRuntime(16766): ... 11 more
编辑: 感谢大家的帮助,我使用了Nathan建议的try catch方法。
try{
Cursor cursor = mydb.getAllRows();
// Do everything here
}catch (NullPointerException e){
// if caught then I do nothing and move on.
}
这阻止了我的问题,而不是尝试{},最后是{}。在.getAllRows()类调用中也发现了这个问题。