[英]Android how to get values from columns in a sqlite database
, and : 我有一個名為TermTable的sqlite表,列 , 和 :
static final String TermTable = "Terms";
static final String ID = "id";
static final String Term = "term";
static final String Type = "type";
此外,我有一個實現數據庫的Datasource類,並具有以下方法來放入和獲取表中的數據:
public long insertTermList(String term, String type) {
ContentValues initialValues = new ContentValues();
initialValues.put(WordsDB.Term, term);
initialValues.put(WordsDB.Type, type);
return db.insert(WordsDB.TermTable, null, initialValues);
}
public Cursor getTermValues(int index) {
String from[] = { "Term", "Type" };
String where = WordsDB.ID + "=" + index;
Cursor cursor = db.query(true, WordsDB.TermTable, from, where, null, null, null, null, null);
return cursor;
}
在另一個類中,我調用了insertTermList,並使用名為ds的Datasource對象為值行插入了一些:
private void setData()
{
ds.insertTermList("abbey", "noun");
ds.insertTermList("abide", "verb");
ds.insertTermList("abound", "verb");
ds.insertTermList("absurd", "adjective");
}
現在我想根據我給它的id從列中獲取值,並將每行的每個列值附加到名為text的文本視圖中。 我怎樣才能做到這一點?
private void getData() {
Cursor c = ???
if(c != null)
{
c.moveToFirst();
text.append(???);
}
}
有什么建議么?
所以,首先,改變你的以下功能:
public Cursor getTermValues(int index) {
String from[] = { "Term", "Type" };
String where = WordsDB.ID + "=" + index;
Cursor cursor = db.query(true, WordsDB.TermTable, from, where, null, null, null, null, null);
return cursor;
}
至
public Cursor getTermValues(int index) {
String from[] = { "Term", "Type" };
String where = WordsDB.ID + "=?";
String[] whereArgs = new String[]{index+""};
Cursor cursor = db.query(WordsDB.TermTable, from, where, whereArgs, null, null, null, null);
return cursor;
}
然后,
private void getData(int id) {
Cursor c = getTermValues(id);
if(c != null)
{
while(c.moveToNext){
String term = c.getString(c.getColumnIndex("term")));
String type = c.getString(c.getColumnIndex("type")));
// use these strings as you want
}
}
}
如果你想ge所有記錄然后創建一個方法:
public void getAllRecords() {
Cursor cursor = db.query(WordsDB.TermTable, null, null, null, null, null, null, null);
if(c != null)
{
while(c.moveToNext){
String term = c.getString(c.getColumnIndex("term")));
String type = c.getString(c.getColumnIndex("type")));
// use these strings as you want
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.