2

每当我启动数据库时,我的应用程序就会崩溃。我已经为此工作了几天。(我在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 中的代码片段数据库适配器被称为

          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:上述错误已解决。现在我得到的应用程序不会崩溃。但数据并不存储在数据库中。错误在 return 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)
4

2 回答 2

2

原始错误

您尚未发布 LogCat 错误,但这是一个典型错误。我猜您正在尝试将 DatabaseAdapter 创建为不正确的字段变量,如评论中所述。

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在注释掉的代码中无效。您必须等到上下文有效。你得到的第一个机会是在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().

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

于 2012-12-02T22:56:54.530 回答
0

您的数据库中的表是否被调用entries

于 2012-12-03T03:51:46.443 回答