我有一个名为 TermTable 的sqlite表,列 id , term 和 type :
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 的数据源对象为值行插入了一些:
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(???);
}
}
有什么建议吗?
答案 0 :(得分:2)
所以, 首先,更改以下功能:
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
}
}
}
如果您想创建所有记录,请创建一个方法:
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
}
}
}