游标如何在Android中工作 [英] How does Cursor work in android
问题描述
我很难在程序中准确显示光标功能。我有点理解,但是有人能详细解释它的功能吗?
I'm having a hard time exactly visualizing 'Cursor' functionality in my program. I kind of get the jist of it, but can anyone explain it's functionality in detail?
通过光标,我的意思是 Cursor
界面。
我不能简单地理解它在任何事物中的作用。
By Cursor, I mean the Cursor
interface.
I can't simply understand the role it plays with anything.
http://developer.android.com/reference/android/database/Cursor.html
推荐答案
在SQLite数据库上的查询返回了Cursor对象。
它将返回查询返回的所有行。
A Cursor object is returned from a query on a SQLite database. It will return all rows that the query returns.
假设您有一个名为 names
的表您的数据库数据库配置如下:
Say you have a table called names
in your database database configured as such:
_id _name
1 Space Ghost
2 Zorak
3 Moltar
4 Brak
如果要从此表中获取所有数据并使用它,您将执行
这样的操作:
If you want to get all data from this table and use it, you would do something like this:
public HashMap<Integer, String> getNames(){
HashMap<Integer, String> data = new HashMap<Integer, String>();
try{
SQLiteOpenHelper helper = new MyOpenDbHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();
String selectQuery = "SELECT * FROM names";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToFirst()){ //make sure you got results, and move to first row
do{
int mID = cursor.getInt(0); //column 0 for the current row
String mName = cursor.getString(1); //column 1 for the current row
data.put(mID, mName);
} while (cursor.moveToNext()); //move to next row in the query result
}
} catch (Exception ex) {
Log.e("MyApp", ex.getMessage());
} finally
{
if (cursor != null) {
cursor.close();
}
if (db != null) {
db.close();
}
}
return data;
}
通常,您将创建自己的类来扩展SQLiteOpenHelper,例如:
Usually you will create your own class to extend SQLiteOpenHelper, as such:
public class MyOpenDbHelper extends SQLiteOpenHelper {
//........
}
这篇关于游标如何在Android中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!