查询返回null指针异常

时间:2012-08-23 18:36:34

标签: android database sqlite

您好我的查询有问题。我想我错过了什么,但我不知道是什么,所以我需要你的帮助

返回java.lang.NullPointerException

 import android.annotation.TargetApi;
    import android.app.Activity;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.util.Log;

    @TargetApi(16)
    public class logged extends Activity{
        public TextView msg;
        private SQLiteDatabase myDB = null;
        public void onCreate(Bundle savedInstanceState){
             super.onCreate(savedInstanceState);
             setContentView(R.layout.logged);
             msg = (TextView) findViewById(R.id.msg);
             myDB.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READONLY);

             try{
//here is the problem. Both kind of queries return the same error
                 //Cursor cur = myDB.query("user_login", new String[] {"username"}, null, null, null, null, null);
                 Cursor cur = myDB.rawQuery("SELECT username FROM user_login", null);
                 msg.setText("Hello");
             }catch (Exception e1){
                 Log.e("DATABAZA","hola "+e1);
                 msg.setText("No Hello you creep");
             }

        }


    }

我的数据库OnCreate是

public void onCreate(SQLiteDatabase db) {
        String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + KEY_UID + " INTEGER PRIMARY KEY,"
                + KEY_NAME + " TEXT,"
                + KEY_LAST + " TEXT,"
                + KEY_EMAIL + " TEXT UNIQUE,"
                + KEY_USERNAME + " TEXT UNIQUE" + ")";

        db.execSQL(CREATE_LOGIN_TABLE);


    }

提前致谢

1 个答案:

答案 0 :(得分:3)

<强>重写

private SQLiteDatabase myDB = null;

mDB为null,您需要在引用它之前对其进行初始化。

尝试使用扩展的SQLiteOpenHelper类:

Database openHelper = new Database(this);
myDB = openHelper.getWritableDatabase(); // or getReadableDatabase();

并删除:

myDB.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READONLY);

现在mDB.query()应该有效!