2017-10-09 91 views
0

我使用SQLiteDatabase和我有一個奇怪的問題 - 當我嘗試SELECT * FROM表它給了我這樣的:的Android工作室SQL找不到表

no such table: test_table (code 1): , while compiling: SELECT * FROM test_table 

但是當我插入到同一個表,沒有發送Exception。 這是我的代碼:

,但未通過表中的所有數據採集方法:

public List<Test> GetAllTests() 
{ 
    List<Test> tests =new ArrayList<Test>(); 

    SQLiteDatabase db = this.getReadableDatabase(); 

    String sql = "SELECT * FROM " + TEST_TABLE; 

    Cursor cursor = db.rawQuery(sql,null); 
    if(cursor.moveToFirst()) 
    { 
     do 
     { 
      Test test = new Test(); 
      test.setId(cursor.getInt(cursor.getColumnIndex(KEY_ID))); 
      test.setSubjectID(cursor.getInt(cursor.getColumnIndex(KEY_SUBJECT_ID))); 

      String dateString = cursor.getString(cursor.getColumnIndex(KEY_TEST_DATE)); 
      DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); 
      Date date = null; 
      try { 
       date = format.parse(dateString); 
      } catch (ParseException e) { 
       e.printStackTrace(); 
      } 
      test.setDate(date); 
      test.setGrade(cursor.getDouble(cursor.getColumnIndex(KEY_TEST_GRADE))); 

      tests.add(test); 
     }while(cursor.moveToNext()); 
    } 
    return tests; 
} 

是將數據插入到同一個表的方法(無例外):

public long InsertTest(Test test) 
{ 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues values = new ContentValues(); 
    values.put(KEY_SUBJECT_ID,test.getSubjectID()); 
    values.put(KEY_TEST_DATE,test.getDate().toString()); 
    return db.insert(TEST_TABLE,null,values); 
} 

的代碼插入並獲取數據:

Test test = new Test(testSubjectID.getSelectedItemPosition(),date); 
AddTestToList(test); 
try { 
    dbManager.InsertTest(test); 
    List<Test> tests = dbManager.GetAllTests(); 
    for (Test test:tests) 
    { 
     AddTestToList(test); 
    } 
}catch (Exception e){Log.d("MSG_ERROR",e.toString());} 
+3

卸載應用程序,並重新安裝 –

+0

問題解決了:) –

+0

卸載並安裝回去? –

回答

2

FYI

  • App uninstall不是好辦法。如果你的APP在PLAYSTORE那麼?

你應該使用onUpgrade爲避免DATA LOSS

數據庫需要升級時調用。實施 應該使用此方法刪除表,添加表或執行任何其他需要升級到新的模式版本的 。

怎麼樣?

@Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     Log.e(TAG, "Updating table from " + oldVersion + " to " + newVersion); 


     if (oldVersion < 3){ // Here I SET 3. You should use your DB version . When-ever **`adding table`** please increase DB version . 
      db.execSQL(ALTER_USER_TABLE_1); 
      db.execSQL(ALTER_USER_TABLE_2); 
     } 

    } 

ALTER TABLE

private static final String ALTER_USER_TABLE_1 = "ALTER TABLE test_table ADD FIELD_NAME TEXT"; 
private static final String ALTER_USER_TABLE_2 = "ALTER TABLE test_table ADD FIELD_NAME2 TEXT"; 
0

有一箇舊版本的d您的設備上沒有test_table表的數據庫。

解決方法:卸載你的應用程序,並重新安裝