读取ContentProvider内的数据
本文地址:http://blog.csdn.net/caroline_wendy
本文的合集已经编著成书,高级Android开发强化实战,欢迎各位读友的建议和指导。
在京东即可购买:https://item.jd.com/12385680.html
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90kaNlXVU1UMJRVT3V1MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TN2gTOzITM5EDMzYDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
读取ContentProvider的数据,需要使用ContentResolver,解析其中的内容,反馈给游标(Cursor); 游标(Cursor)默认指向-1,需要移动cursor.moveToNext(),query需要解析URI,返回列值使用字符串; URI和字符串:
public static final String AUTHORITY = "me.cxxxyx.healthtool.provider";
public static final class StepCounter implements BaseColumns
{
public static final String TABLE_NAME = "stepcounter";
public static final String STEP = "step";
public final static Uri STEP_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/step");
}
解析器(Resolver)具体使用:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ContentResolver cr; //内容解析器
TextView mTextView; //显示界面
mTextView = (TextView) findViewById(R.id.steps);
//通过contentResolver进行查找
cr = this.getContentResolver();
Cursor cursor = cr.query(ContentData.StepCounter.STEP_CONTENT_URI, null, null, null, null);
String str = "";
while (cursor.moveToNext()) {
str = cursor.getString(cursor.getColumnIndex(ContentData.StepCounter.STEP));
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
mTextView.setText(str);
cursor.close(); //查找后关闭游标
}