如何克隆或冻结Android数据库游标 [英] How to clone or freeze an Android database cursor

查看:174
本文介绍了如何克隆或冻结Android数据库游标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的光标适配器,我想把光标的每一行都返回到应用程序(通过一个注册的回调函数工作)。



我知道我可以从游标读取每个字段,并手动进行,但我只想传递一个冻结克隆的光标回来。 (读取适配器中的字段将需要我做这个类的几个专门的版本。)



理想情况下,我想传回与Cursor相同的接口,但不能遍历结果集。



查询返回少于20行,因此空间不是问题。

  Cursor c = ...; //包含许多行
if c.moveToFirst()){
String [] columns = c.getColumnNames();
while(!c.isAfterLast()){
MatrixCursor newCursor = new MatrixCursor(columns,1);
MatrixCursor.RowBuilder b = newCursor.newRow();
for(String col:columns){
//如果所有列都是字符串类型。但是如果他们是
//不同,那么请看下面的注释
b.add(c.getString(c.getColumnIndex(col)));
}
//使用newCursor调用您的监听器
}
}


b $ b

如果列的数据类型不是字符串,该怎么办?



对于API> = 11:只需调用<$ c $在中为循环使用 getType()方法并使用 switch 语句调用适当的get方法。



对于API< 11:运行类似于 PRAGMA table_info(my_table_name)的另一个查询, a 映射列名和类型,并在for循环中使用它。以下是阅读此游标的方法 http://stackoverflow.com/a/9354401/1112882


I have a custom cursor adapter, and I would like to pass each 'row' of the cursor back to the application (via a registered callback which is working).

I know I could read each of the fields from the cursor and do it manually, but I would simply like to pass a 'frozen clone' of the cursor back. (Reading the fields in the adapter would require me to make several specialised versions of this class.)

Ideally I would like to pass back something with the same interface as Cursor, but which couldn't traverse the result set.

The queries return fewer than 20 rows, so space is not an issue.

解决方案

I guess you have a cursor with 20 rows and now you want to invoke a method 20 times with a cursor that contains only one row. Here is how you can do this:

Cursor c = ...;// contains many rows
if(c.moveToFirst()){
    String[] columns = c.getColumnNames();
    while(!c.isAfterLast()){ 
        MatrixCursor newCursor = new MatrixCursor(columns , 1);
        MatrixCursor.RowBuilder b = newCursor.newRow();
        for(String col: columns){
             // in case all columns are of string type. But if they are 
             // different then see my comment below 
             b.add(c.getString(c.getColumnIndex(col)));
        }
     // invoke your listener here with newCursor
    }
}

What if data type of columns is not String?

For API>=11: Just call getType() method in for loop and use switch statement to invoke appropriate get method.

For API<11: Run another query similar to this PRAGMA table_info(my_table_name) and then just fill a Map of column name and type and use it in for loop. Here is how you can read this cursor http://stackoverflow.com/a/9354401/1112882

这篇关于如何克隆或冻结Android数据库游标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆