getWritableDatabase()-Nullpoiter Exception(android)

时间:2012-12-02 22:45:08

标签: android nullpointerexception getwritabledatabase

每当我解雇数据库时,我的应用程序崩溃了。我这几天一直在研究这个问题。 (我这里只输入databaseAdapter.java文件的重要代码片段。我在getWritableDatabase()NullPointerException收到错误。

  private SQLiteDatabase db;
  static final boolean assertionsDisabled = false;
  private DBHelper dbHelper;
  // private Context context;


  public DatabaseAdapter(Context context) {
  dbHelper = new DBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
  }


  private static class DBHelper extends SQLiteOpenHelper {
  public DBHelper(Context context, String name, CursorFactory factory, int version) {
    super(context, name, factory, version);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {

    try {
        db.execSQL(CREATE_TABLE_ENTRIES);
        //db = DBHelper.getWritableDatabase();

    } catch (SQLException e) {
    e.printStackTrace();
}
}

    @Override   
    public void onUpgrade(SQLiteDatabase db, int i, int j)
    {

        Log.w("mytag", (new StringBuilder("Upgrading from version ")).append(i).append(" to ").append(j).append(", which will destroy all old data").toString());
        db.execSQL("DROP TABLE IF EXISTS CREATE TABLE IF NOT EXISTS entries (_id INTEGER PRIMARY KEY AUTOINCREMENT, input_type INTEGER NOT NULL, activity_type INTEGER NOT NULL, date_time DATETIME NOT NULL, duration INTEGER NOT NULL, distance FLOAT, avg_pace INTEGER, avg_speed INTEGER,calories INTEGER, climb INTEGER, avg_heartrate INTEGER, comment TEXT, privacy INTEGER, gps_data BLOB );");
        onCreate(db);
    }

    }

     public DatabaseAdapter open()
     throws SQLException
      {
     db = dbHelper.getWritableDatabase();
 return this;
     } 

/////////////////////////////////////////////// //////////////////////

编辑1:我从ActivityManualInput.java代码调用databaseAdapter.java ////////////////////////这是ActivityManualInput.java中的代码片段,其中调用了databaseAdapter

          public class ActivityManualInput extends ListActivity {

          //  Some code here
      private Context mContext;

          // Some code here          

         protected void onCreate(Bundle savedInstanceState) {
    //TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.xml.manualinput);   

             // Some code here  

         Button btn = ((Button) findViewById(R.id.btnSave));

     View.OnClickListener myListener; 

    myListener= new View.OnClickListener(){
        @Override
    public void onClick(View v)
    {

  //  mDateTime = new GregorianCalendar(mYear, mMonth, mDay, mHour, mMinute);       
            mDateTime = new GregorianCalendar(2, 3, 1, 4,5);

    db = new DatabaseAdapter(mContext);
    db.open();
    // long id = db.insertEntry(mInputType, mActivityType, mDateTime, mDuration, mDistance, mCalories, mComment);
    long id = db.insertEntry(3, 3, mDateTime, 4, 5, 5, "ant");
    db.close();
    Toast.makeText(getApplicationContext(), "Entry #" + id + "Saved!", Toast.LENGTH_SHORT)
    .show();
    finish();
    }   
    };

    btn.setOnClickListener(myListener);

/////////日志文件...... /////////////////////

      12-03 06:03:00.318: W/dalvikvm(270): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
       12-03 06:03:00.318: E/AndroidRuntime(270): Uncaught handler: thread main exiting due to uncaught exception
       12-03 06:03:00.398: E/AndroidRuntime(270): java.lang.NullPointerException
       12-03 06:03:00.398: E/AndroidRuntime(270):   at        android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at com.android.saud.lab3.DatabaseAdapter.open(DatabaseAdapter.java:147) 
       12-03 06:03:00.398: E/AndroidRuntime(270):   at com.android.saud.lab3.ActivityManualInput$1.onClick(ActivityManualInput.java:85)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.View.performClick(View.java:2364)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.View.onTouchEvent(View.java:4179)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.widget.TextView.onTouchEvent(TextView.java:6541)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.View.dispatchTouchEvent(View.java:3709)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
       12-03 06:03:00.398: E/AndroidRuntime(270):   at android.os.Handler.dispatchMessage(Handler.java:99)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at android.os.Looper.loop(Looper.java:123)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at android.app.ActivityThread.main(ActivityThread.java:4363)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at java.lang.reflect.Method.invokeNative(Native Method)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at java.lang.reflect.Method.invoke(Method.java:521)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
        12-03 06:03:00.398: E/AndroidRuntime(270):  at dalvik.system.NativeStart.main(Native Method)
        12-03 06:03:00.418: I/dalvikvm(270): threadid=7: reacting to signal 3
        12-03 06:03:00.418: E/dalvikvm(270): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
        12-03 06:08:00.478: I/Process(270): Sending signal. PID: 270 SIG: 9

编辑#2:上述错误已经解决。现在我得到的应用程序不会崩溃。但是数据不存储在数据库中。错误在返回db.insert中(TABLE_NAME_ENTRIES,null,contentvalues); databaseadapter.java文件的行

     public long insertEntry(int i, int j, GregorianCalendar gregoriancalendar, long l, double d, 
    int k, String s)
      {
     ContentValues contentvalues = new ContentValues();
     contentvalues.put(KEY_INPUT_TYPE, Integer.valueOf(i));
     contentvalues.put(KEY_ACTIVITY_TYPE, Integer.valueOf(j));
     contentvalues.put(KEY_DATE_TIME, Long.valueOf(gregoriancalendar.getTimeInMillis() / 1000L));
      contentvalues.put(KEY_DURATION, Long.valueOf(l));
     contentvalues.put(KEY_DISTANCE, Double.valueOf(d));
     contentvalues.put(KEY_CALORIES, Integer.valueOf(k));
     contentvalues.put(KEY_COMMENT, s);
     return db.insert(TABLE_NAME_ENTRIES, null, contentvalues);   // Logcat is howing                
     error here
      }

这是logcat

     12-03 08:51:10.608: E/Database(327): Error inserting input_type=3 calories=5 distance=5.0 duration=4 comment=ant date_time=-62096464100 activity_type=3
     12-03 08:51:10.608: E/Database(327): android.database.sqlite.SQLiteException: no such table: entries: , while compiling: INSERT INTO entries(input_type, calories, distance, duration, comment, date_time, activity_type) VALUES(?, ?, ?, ?, ?, ?, ?);
     12-03 08:51:10.608: E/Database(327):   at android.database.sqlite.SQLiteProgram.native_compile(Native Method)
     12-03 08:51:10.608: E/Database(327):   at android.database.sqlite.SQLiteProgram.compile(SQLiteProgram.java:110)

2 个答案:

答案 0 :(得分:2)

原始错误

您尚未发布LogCat错误,但这是一个典型错误。我猜您正在尝试将DataAdapter创建为字段变量,如注释中所述。

public class MainActivity extends Activity {
    // Do not do this! 
    //   This will case a NullPointerException later when your call getWritableDatabase()...
    //DatabaseAdapter dba = new DatabaseAdapter(this);

    // Do this instead:
    DatabaseAdapter dba;

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

        dba = new DatabaseAdapter(this); // Right way!

this引用的上下文在注释掉的代码中无效。您必须等到Context有效。您获得的第一个机会是onCreate()


<强>加成
在这种情况下,您使用的是new DatabaseAdapter(mContext);但忘记初始化mContext所以它是null ...

新的LogCat显示表条目不存在,原因是您不能将这些SQL命令链接在一起:

db.execSQL("DROP TABLE IF EXISTS CREATE TABLE IF NOT EXISTS entries ...

这是语法错误,因此从未构建表entries。这些必须是单独的命令:

db.execSQL("DROP TABLE IF EXISTS entries");
db.execSQL("CREATE TABLE IF NOT EXISTS entries ...

不要忘记增加DATABASE_VERSION,以便在onUpgrade()中创建表格。

希望这已经解决了您当前的问题。如果遇到更多例外情况,请随意提出新问题。 祝你好运!:)

答案 1 :(得分:0)

您的数据库中的表名为entries吗?