讀取ContentProvider内的資料
本文位址:http://blog.csdn.net/caroline_wendy
本文的合集已經編著成書,進階Android開發強化實戰,歡迎各位讀友的建議和指導。
在京東即可購買:https://item.jd.com/12385680.html
讀取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(); //查找後關閉遊标
}