2016-05-12 112 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 

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