打开数据库时Android SQLite空指针异常

时间:2012-11-29 05:43:58

标签: android sqlite

我无法在adroid上执行我的SQLite应用程序。出于测试目的,我尽可能简单。将数据添加到数据库中的查询,当用户单击“查看计划”按钮时,数据库中的所有数据都应显示为TOAST消息。 “MySQLitehelper.java”文件包含所有与数据库相关的代码,“SelectOptions.java”包含具有“查看计划”按钮的代码。所有正确的导入都已添加,因此我在这里省略了它们。

在跟踪LogCat时,我看到当你调用MySQLitehelper类的helper.open()方法时有一个空指针异常。我尝试打印语句来跟踪它,并发现该程序关闭了以下几行:

  public MySQLitehelper open() throws SQLException
 {
    System.out.println("Inside open function");
     db = dbhelper.getReadableDatabase();  // even tried helper.getWritableDatabase()
    return this;
 }

并在行

时停止
 db = dbhelper.getReadableDatabase(); 
遇到了

。 这是我的代码:

/ * --------------MySQLitehelper.java代码----------------- * /

public class MySQLitehelper {

//public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "GWid";
  public static final String COLUMN_DATE = "date";
  public static final String COLUMN_LOCATION = "location";
  public static final String COLUMN_TIME = "time";

  public static final String TABLE_NAME = "UPDTable";

  private static final String DATABASE_NAME = "UPDdb";
  private static final int DATABASE_VERSION = 1;

  private final Context context;


  // Database creation sql statement
  private static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
                                " (" +COLUMN_ID+ " VARCHAR," + COLUMN_DATE + "VARCHAR," +
                                COLUMN_LOCATION+" VARCHAR," +COLUMN_TIME +" VARCHAR);";

  private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME +
                                                " Values ('47688507','DEC-07-2012','MARVIN 203','20:00');";


  DatabaseHelper dbhelper;
  SQLiteDatabase db;

 public MySQLitehelper(Context ctx)
  {
      this.context = ctx;
  }

 private static class DatabaseHelper extends SQLiteOpenHelper {

     public DatabaseHelper(Context context)
     {
         super(context,DATABASE_NAME, null,DATABASE_VERSION);
     }

 @Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(DATABASE_CREATE);            //execute create table
    db.execSQL(DATABASE_INSERT);            //execute insert query

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    Log.w(MySQLitehelper.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}


// open the DB
 public MySQLitehelper open() throws SQLException
 {
    System.out.println("Inside open function");
     db = dbhelper.getReadableDatabase();
    return this;
 }

 public void close()
 {
     dbhelper.close();
 }


public Cursor getAllrows()      //function to get all rows in the DB. Testing initially.
{
    //SQLiteDatabase db=this.getReadableDatabase();
    Cursor cur=db.query(TABLE_NAME,new String []{COLUMN_ID, COLUMN_DATE,
            COLUMN_LOCATION,COLUMN_TIME},null,null,null,null, null);

     return cur;
}

  }

/ ------------- SelectOptions.java class ------------------ /

    public class SelectOptions extends Activity {

Button btnView, btnDrop, btnLocation;

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


    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    btnView = (Button)findViewById(R.id.btnViewShift);
    btnDrop = (Button)findViewById(R.id.btnDropShift);
    btnLocation = (Button)findViewById(R.id.btnViewLocation);


    final MySQLitehelper helper = new MySQLitehelper(this);


    btnView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            helper.open();
            Cursor c = helper.getAllrows();
              if (c.moveToFirst()) {
             do {

                 System.out.println("In Do while");
                 DisplayRecord(c); 

             } while (c.moveToNext());
          }
            helper.close(); 
            System.out.println("Out of Do");



        }  
    });


}

public void DisplayRecord(Cursor c)
{
    System.out.println("In side toast display function");
    Toast.makeText(this, "id: "+c.getString(0)+"\n"+
            "Date: "+c.getString(1)+"\n"+
            "Location: "+c.getString(2)+"\n"+
            "Time: "+c.getString(3), Toast.LENGTH_LONG).show();
}


    }

logcat的

11-29 06:18:01.393: I/System.out(8162): Inside open function
11-29 06:18:01.453: E/SQLiteLog(8162): (1) no such column: date
11-29 06:18:01.453: D/AndroidRuntime(8162): Shutting down VM
11-29 06:18:01.463: W/dalvikvm(8162): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
11-29 06:18:01.503: E/AndroidRuntime(8162): FATAL EXCEPTION: main
11-29 06:18:01.503: E/AndroidRuntime(8162): android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT GWid, date, location, time FROM UPDTable
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
11-29 06:18:01.503: E/AndroidRuntime(8162):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)

3 个答案:

答案 0 :(得分:1)

您没有初始化dbhelper实例

将此语句写入MySQLitehelper()构造函数

dbhelper = new DatabaseHelper(ctx);

完整代码

public MySQLitehelper(Context ctx)
{
      this.context = ctx;
    dbhelper = new DatabaseHelper(ctx);
}

<强>被修改

您的插入查询错误,最后一个值20:00应为'20:00'

private static final String DATABASE_INSERT = "INSERT INTO " +TABLE_NAME +
                                                " Values ('47688507','DEC-07-2012','MARVIN 203','20:00');";

答案 1 :(得分:1)

你得到了NULLPointer异常,因为你没有在MySQLitehelper构造函数中实例化 dbHelper 对象。

答案 2 :(得分:0)

以下行中存在语法错误。 20:00参数的格式无效。应为字符串“20:00”或有效整数或浮点数--20.0

 enter code here`private static final String DATABASE_INSERT = "INSERT INTO " +
      TABLE_NAME +    " Values ('47688507','DEC-07-2012','MARVIN 203',20:00);";