2012-05-26 107 views
2

我想從我的數據庫中獲取信息並將其放入字符串中以在屏幕上進行打印。我想我可以使用下面的代碼來做到這一點,但它給出了一些關於遊標的信息,而不是遊標內的信息。從SQLite數據庫獲取數據到字符串Android

datasource = new DataBaseHelper(this); 
datasource.open(); 
Cursor c = datasource.getAllGoals(); 
startManagingCursor(c); 
String g = c.toString(); 
goal.setText(g); 
datasource.close(); 
+0

怎樣的信息?你能更具體化嗎? 'String g = c.toString()''你只能得到''cursor''的字符串表示。爲了從光標獲取信息,你應該使用'getters'和方法來允許你通過數據傳遞。 – Sajmon

回答

1

遊標可以被認爲是指向一些底層數據的指針。在光標對象上運行c.toString()將打印默認Cursor類的字符串表示的實現(符號字符@和對象的哈希代碼的無符號十六進制表示),這不是您想要的。

要檢索底層數據庫數據,您需要調用c.getString(columnIndex)source)或您需要的特定列索引的任何列數據類型。

下面是一個例子modified from source

說你已經創建了一個表

private static final String DATABASE_CREATE = 
      "create table comments (" 
      + "_id integer primary key autoincrement, " 
      + "comment text not null);"; 

和你getAllGoals函數返回一個指向數據約_idcomment光標。現在您只想顯示有關comment列的詳細信息。所以你必須運行c.getString(1)。假設你的getAllGoals函數返回一個只指向關於comment列的數據的遊標。現在你必須運行c.getString(0)

我建議您下載所提供示例中的源代碼,並瞭解如何從遊標中檢索數據。

編輯:

public List<Comment> getAllComments() { 
     List<Comment> comments = new ArrayList<Comment>(); 

     Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, 
       allColumns, null, null, null, null, null); 

     cursor.moveToFirst(); 
     while (!cursor.isAfterLast()) {//retrieve data from multiple rows 
      Comment comment = cursorToComment(cursor); 
      comments.add(comment); 
      cursor.moveToNext(); 
     } 
     // Make sure to close the cursor 
     cursor.close(); 
     return comments; 
    } 

    private Comment cursorToComment(Cursor cursor) { 
     Comment comment = new Comment(); 
     comment.setId(cursor.getLong(0)); 
     comment.setComment(cursor.getString(1)); 
     return comment; 
    } 

source

+0

列索引指的是什麼。我需要改變還是隻是需要> –

+0

檢查我的更新答案。 –

+0

所以如果我正在從數據庫中獲取幾位信息,我會針對每一點信息運行幾次這些信息? –

0
openDataBase(); 
Cursor c = myDataBase.rawQuery("SELECT * FROM tb_aa_City where City_Name = '"+cityname+"'", null); 
if (c.getCount() > 0) { 
    c.moveToFirst(); 
    seqid = c.getString(4); 
    System.out.println("In DB..getSequenceID..."+seqid); 
    } 
    c.close(); 
    myDataBase.close(); 
    SQLiteDatabase.releaseMemory(); 
+0

如何我得到的c.getString(int);指向正確的信息 –

+0

c.getString(Colomn number)//給數據庫列號 –

相關問題