2016-05-12 83 views
0

嘿,我目前有兩個函數打印整個數據庫作爲一個字符串和另一個應該只獲取數據時,在數據庫的「TODO」列滿足條件,這些如下面所述。選擇在哪裏與SQLite和Android

 public String databaseToString() { 
    String dbString = ""; 
    SQLiteDatabase db = getWritableDatabase(); 
    String query = "SELECT * FROM " + TABLE_LIST + " WHERE 1"; 

    //Cursor points to a location in your results 
    Cursor c = db.rawQuery(query, null); 
    //Move to the first row in your results 
    c.moveToFirst(); 

    //Position after the last row means the end of the results 
    while (!c.isAfterLast()) { 
     if (c.getString(c.getColumnIndex("ToDo")) != null) { 
      dbString += c.getString(c.getColumnIndex("ToDo")); 
      dbString += " "; 
      dbString += c.getString(c.getColumnIndex("accFor")); 
      dbString += "\n"; 
     } 
     c.moveToNext(); 
    } 
    db.close(); 
    return dbString; 
} 

這是用於將整個數據庫轉換爲要打印的字符串的工作函數的代碼。下面是應該得到數據庫中的所有值,其中TODO等於字符串的大學,我已經進一步調用在mydatabasemanager應用程序,包含了這兩種功能

public String UniversityToString() { 
    String dbString = ""; 
    SQLiteDatabase db = getWritableDatabase(); 
    String query = ("SELECT " + COLUMN_TODO + COLUMN_FOR + " FROM " + TABLE_LIST + " WHERE "+ COLUMN_FOR + "=\"" + University + "\";"); 

    //Cursor points to a location in your results 
    Cursor c = db.rawQuery(query, null); 
    //Move to the first row in your results 
    c.moveToFirst(); 

    //Position after the last row means the end of the results 
    while (!c.isAfterLast()) { 
     if (c.getString(c.getColumnIndex("ToDo")) != null) { 
      dbString += c.getString(c.getColumnIndex("ToDo")); 
      dbString += " "; 
      dbString += c.getString(c.getColumnIndex("accFor")); 
      dbString += "\n"; 
     } 
     c.moveToNext(); 
    } 

    db.close(); 
    return dbString; 
} 

這個代碼在這裏會導致沒有工作職能我的應用程序崩潰時打開調用它的活動,我只是想知道如何解決這個問題,以正確選擇我需要的數據。

+0

將錯誤與堆棧跟蹤附加在一起 –

+0

字符串串聯很容易出錯。你可以看看這個問題,以更清晰的方式查詢數據庫。 http://stackoverflow.com/questions/5276099/how-to-format-the-where-clause-and-in-a-sqlite-query –

+0

@ cricket_007 致命例外:main java.lang.RuntimeException:Unable開始活動ComponentInfo {com.kai.todolist/com.kai.todolist.Main3Activity}:android.database.sqlite.SQLiteException:no such column:University(code 1):,while compiling:SELECT ToDo,accFor FROM List WHERE accFor =大學 –

回答

0

查詢中至少應該有兩列之間的內容。

COLUMN_TODO + ", " COLUMN_FOR 

您也不需要添加;在查詢字符串的末尾