Android mobile application foundation tutorial [sharing data with content providers]

	//获取相应操作的Uri,Uri.parse()方法是将字符串转化成Uri对象。
	Uri uri = Uri.parse("content://cn.itcast.mycontentprovider/person"); 
	//获取ContentResolver对象
    ContentResolver resolver = context.getContentResolver();
    //通过ContentResolver对象查询数据
    Cursor cursor = resolver.query(Uri uri, String[] projection, String selection,
                                     String[] selectionArgs, String sortOrder);
    while (cursor.moveToNext()) {
        String address = cursor.getString(0); 
        long date = cursor.getLong(1);
        int type = cursor.getInt(2);
   }
    cursor.close();

 //创建内容观察者
 private class MyObserver extends ContentObserver{
        public MyObserver(Handler handler) {
            super(handler);
        }
        //当观察到Uri代表的数据发生变化时调用方法,程序会回调onChange()方法
        //并在该方法中处理相关逻辑
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
          }
    }

  ContentResolver resolver = getContentResolver();
    Uri uri = Uri.parse("content://aaa.bbb.ccc");
    //注册内容观察者
    resolver.registerContentObserver(uri, true, new MyObserver(new Handler()));

 @Override
protected void onDestroy() {
     super.onDestroy();
     //取消注册内容观察者
     getContentResolver().unregisterContentObserver(new MyObserver(       
     											new Handler()));
}

This chapter explains the relevant knowledge of content providers in detail. First, it briefly introduces content providers, then explains how to create content providers and how to use content providers to access the data exposed by other programs, and finally explains the content observer to observe the changes of data through the content observer. The ContentProvider mentioned in this chapter is one of the four major components of Android. It will often be used when subsequent programs need to share data. Therefore, beginners are required to master the contents of this chapter.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>