尝试从SQLite数据库获取数据时出现NullPointerException / CursorOutOfBoundsException

时间:2014-03-16 22:07:41

标签: java android sqlite nullpointerexception android-sqlite

[edit] logcat添加

根据标题。当我尝试从数据库中恢复数据并且没有任何内容时,我曾预料会发生这种情况,所以我试图避免它。

目前我有一个带有三个参数的User类(String,String,int)。我在扩展SQLiteOpenHelper的类中也有以下方法:

public User retrieveUserInfo() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_USER, null);


        String name = null;
        String surname = null;
        String age = null;

        if (cursor == null) {
            Log.d("NULL", "CURSOR IS NULL");
            user = new User("Please connect to server", " ", 0);

        }

        if (cursor.moveToFirst()) { 

            Log.d("NOT NULL", "CURSOR IS NOT NULL");

            do {
                name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
                surname = cursor.getString(cursor
                        .getColumnIndex(COLUMN_SURNAME));
                age = cursor.getString(cursor.getColumnIndex(COLUMN_AGE));
            } while (cursor.moveToNext());
            Log.d("NAME", name);
            int age_p = Integer.parseInt(age);
            user = new User(name, surname, age_p);

        }



        return user;
    }

然后,我从另一个活动中调用此方法:

DatabaseTask dt = new DatabaseTask(this);
        User user = dt.retrieveUserInfo();
        String name = user.getName();
        String surname = user.getSurname();

        TextView textName = (TextView) findViewById(R.id.textView1);
        TextView textSurname = (TextView) findViewById(R.id.textView2);

        textName.setText(name);
        textSurname.setText(surname);

所以,目前我正试图通过在游标为空时发送带有一些占位符字段的User实例来避免崩溃(此方法中的" user"字段是公共静态成员类型为User的变量,在类的前面定义),当游标不为null时返回存储在数据库中的普通数据。但它仍然无法正常工作:只要我卸载应用程序并重新安装它,应用程序就会崩溃。现在,如果我在数据库中插入一些东西然后重新安装应用程序而不先删除它(更新它并保留旧数据库,我猜)应用程序不会崩溃。

我检查光标的原因是否为空的任何想法都不起作用?

[edit] logcat如下:

> 03-17 02:48:35.036: E/AndroidRuntime(1225): FATAL EXCEPTION: main
> 03-17 02:48:35.036: E/AndroidRuntime(1225): Process:
> com.example.jsonbourne, PID: 1225 03-17 02:48:35.036:
> E/AndroidRuntime(1225): java.lang.RuntimeException: Unable to start
> activity
> ComponentInfo{com.example.jsonbourne/com.example.jsonbourne.MainActivity}:
> java.lang.NullPointerException 03-17 02:48:35.036:
> E/AndroidRuntime(1225):   at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> android.app.ActivityThread.access$800(ActivityThread.java:135) 03-17
> 02:48:35.036: E/AndroidRuntime(1225):     at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> android.os.Handler.dispatchMessage(Handler.java:102) 03-17
> 02:48:35.036: E/AndroidRuntime(1225):     at
> android.os.Looper.loop(Looper.java:136) 03-17 02:48:35.036:
> E/AndroidRuntime(1225):   at
> android.app.ActivityThread.main(ActivityThread.java:5017) 03-17
> 02:48:35.036: E/AndroidRuntime(1225):     at
> java.lang.reflect.Method.invokeNative(Native Method) 03-17
> 02:48:35.036: E/AndroidRuntime(1225):     at
> java.lang.reflect.Method.invoke(Method.java:515) 03-17 02:48:35.036:
> E/AndroidRuntime(1225):   at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 03-17
> 02:48:35.036: E/AndroidRuntime(1225):     at
> dalvik.system.NativeStart.main(Native Method) 03-17 02:48:35.036:
> E/AndroidRuntime(1225): Caused by: java.lang.NullPointerException
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> com.example.jsonbourne.MainActivity.onCreate(MainActivity.java:31)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> android.app.Activity.performCreate(Activity.java:5231) 03-17
> 02:48:35.036: E/AndroidRuntime(1225):     at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
> 03-17 02:48:35.036: E/AndroidRuntime(1225):   ... 11 more

[edit 2] MainActivity和activity_mail.xml如下:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //GetJson gj = new GetJson(this);
        //gj.getData();

        DatabaseTask dt = new DatabaseTask(this);

        User user = dt.retrieveUserInfo(); // **<------- LINE 31**



        String name = user.getName();
        String surname = user.getSurname();

        TextView textName = (TextView) findViewById(R.id.textView1);
        TextView textSurname = (TextView) findViewById(R.id.textView2);

        textName.setText(name);
        textSurname.setText(surname); 

        Button buttonconnect = (Button) findViewById(R.id.button_connect);

activity_mail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_connect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="188dp"
        android:background="#F0FF00"
        android:text="@string/pressconnect" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button_connect"
        android:layout_alignParentTop="true"
        android:layout_marginTop="100dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignRight="@+id/button_connect"
        android:layout_marginRight="17dp"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="22dp"
        android:text="Welcome,"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:2)

尝试:

    if (cursor == null) {
        Log.d("NULL", "CURSOR IS NULL");
        user = new User("Please connect to server", " ", 0);

    } else if (cursor.moveToFirst()) { 
        Log.d("NOT NULL", "CURSOR IS NOT NULL");
        //...
    }

而不是:

    if (cursor == null) {
        Log.d("NULL", "CURSOR IS NULL");
        user = new User("Please connect to server", " ", 0);

    }

    if (cursor.moveToFirst()) { 

您似乎忘记了else声明

答案 1 :(得分:2)

有问题的代码

DatabaseTask dt = new DatabaseTask(this);

User user = dt.retrieveUserInfo(); // **<------- LINE 31**

String name = user.getName();

无法真正产生堆栈跟踪,所以让我们通过调用getName() null上的user来假设NPE真的出现在下一行。这可以通过修复retrieveUserInfo()来修复,例如:

Cursor cursor = ...;

if (cursor.moveToFirst()) {
  // create user from cursor data
} else {
  // create default user
}
return user;

评论中提到的cursor null检查不是必需的。

此外,您的查询从表中提取所有行,但仅使用最后一行中的数据。稍后您可能需要考虑优化,即仅获取您实际使用的数据。