Android之ContentProvite组件的使用

    科技2022-07-10  187

    ContentProvite组件的使用

    实例:

    activiy: public class MainActivity extends AppCompatActivity { private ListView MainActivity_listview; private List<User> listdata=new ArrayList<>(); List<Map<String, Object>> listmap=new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); getAllContacts2(); for (User user1:listdata){ Map<String,Object> map=new HashMap<>(); map.put("id",user1.get_id()); map.put("name",user1.getName()); map.put("phone",user1.getPhone()); listmap.add(map); } SimpleAdapter simpleAdapter=new SimpleAdapter(this,listmap,R.layout.listview_layout,new String[]{"name","phone"},new int[]{R.id.text1, R.id.text2}); MainActivity_listview.setAdapter(simpleAdapter); // test(); } //使用新版本完成查询 public void getAllContacts2(){ Uri uri=ContactsContract.Data.CONTENT_URI; //所有的数据一般存在data1 //查询data1,mimetype_id,raw_contact_id Cursor cursor=getContentResolver().query(uri,null,null,null,"display_name"); int index_contact_id=cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID); int index_data1=cursor.getColumnIndex(ContactsContract.Data.DATA1); int index_mimetype=cursor.getColumnIndex(ContactsContract.Data.MIMETYPE); Log.i("data1",index_contact_id+""); Log.i("data2",index_data1+""); Log.i("data3",index_mimetype+""); cursor.moveToFirst(); String id=cursor.getString(index_contact_id); int tempid=Integer.parseInt(id); User user=new User(); user.set_id(tempid); do{ id=cursor.getString(index_contact_id); if (Integer.parseInt(id)!=tempid){ listdata.add(user); user=new User(); tempid=Integer.parseInt(id); user.set_id(tempid); } String data1=cursor.getString(index_data1); String mimetype=cursor.getString(index_mimetype); //名称,字段名我是直接从数据库的mimetypes表复制的 if (mimetype.equals("vnd.android.cursor.item/name")){ user.setName(data1); } //电话 if (mimetype.equals("vnd.android.cursor.item/phone_v2")){ user.setPhone(data1); } }while(cursor.moveToNext()); listdata.add(user); } //使用老版本所公开的Uri完成查询 public void getAllContacts(){ ContentResolver cr=getContentResolver(); Uri uri=ContactsContract.Contacts.CONTENT_URI; Uri Phoneuri=ContactsContract.CommonDataKinds.Phone.CONTENT_URI; Cursor cursor=cr.query(uri,null,null,null,null); while (cursor.moveToNext()){ User user=new User(); String contact_id=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); user.set_id(Integer.parseInt(contact_id)); user.setName(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))); Cursor Phonecursor=cr.query(Phoneuri,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",new String[]{contact_id},null); while (Phonecursor.moveToNext()){ user.setPhone(Phonecursor.getString(Phonecursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))); } listdata.add(user); } } //测试 public void test(){ //1、ContentResolver // ContentResolver cr=getContentResolver(); // //ContentResolver公开接口 insert, update, delete, query // Uri uri= ContactsContract.Contacts.CONTENT_URI;//联系人名称 // Cursor cursor=cr.query(uri,new String[]{ContactsContract.Contacts.DISPLAY_NAME},null,null,null); // while (cursor.moveToNext()){ // String name=cursor.getString(0); // Log.i("PhoneName:",name); // } // ContentResolver cr1=getContentResolver(); // Uri uri1=ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // Cursor cursor=cr1.query(uri1,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},null,null,null); // while (cursor.moveToNext()){ // String number=cursor.getString(0); // Log.i("Phone:",number); // } ContentResolver cr=getContentResolver(); Uri uri=ContactsContract.Data.CONTENT_URI;//2.X以上版本可用 Cursor cursor=cr.query(uri,new String[]{ContactsContract.Data.DATA1},null,null,null); while (cursor.moveToNext()){ String data1=cursor.getString(0); Log.i("data1",data1); } } private void initView() { MainActivity_listview = (ListView) findViewById(R.id.MainActivity_listview); } } layout <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/MainActivity_listview" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </androidx.constraintlayout.widget.ConstraintLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Name" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/text2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Phone" android:textAppearance="?android:attr/textAppearanceLarge" /> </LinearLayout>

    自定义ContentProvider

    自定义ContentProviderUriMatcher

    编写一个类,必须继承自ContentProvider类

    实现ContentProvider类中所有的抽象方法; onCerate(),getType(),query(),insert(),update(),delete()等方法 在清单文件中声明注册ContentProvider

    1、自定义创建数据库的类

    package com.example.myapplication.util; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /* * 自定义一个创建数据库的帮助类 * */ public class DBHelper extends SQLiteOpenHelper { public static final int VERSION=1; public DBHelper(Context context) { //创建数据库 super(context,"Student.db",null,VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { //创建数据库中的表 String sql="create table Student(_id integer primary key autoincrement,name,age,score)"; sqLiteDatabase.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { //修改数据库 } }

    2、创建自定义Provider类

    package com.example.myapplication.util; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class MyProvider extends ContentProvider { private DBHelper dbHelper; @Override public boolean onCreate() { dbHelper=new DBHelper(getContext()); return false; } /* *strings:查询的列 * s:行条件 * strings1:条件中参数的值 * s1:排序(排序字段) * * */ @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) { return dbHelper.getReadableDatabase().query("Student",strings,s,strings1,null,null,s1); } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) { SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase(); long rowId = sqLiteDatabase.insert("Student", null, contentValues); //追加一个id;就是在url后面加资源标识如:content://heying.provider.contentprovider/rowId sqLiteDatabase.close(); return ContentUris.withAppendedId(uri,rowId); } @Override public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) { return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) { return 0; } }

    3、在AndroidManifest.xml中注册自定义的Provider

    <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <!-- 允许程序访问联系人通讯录信息--> <uses-permission android:name="android.permission.READ_CONTACTS"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--注册provider; authorities:相当于url我们自定定义的字符串; name:自定义Provider的位置; exported:为真就是允许别人访问--> <provider android:authorities="heying.provider.contentprovider" android:name="com.example.myapplication.util.MyProvider" android:exported="true"/> </application> </manifest>

    使用

    一)、本包MainActivity 的使用

    package com.example.myapplication; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.myapplication.bean.User; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private ListView MainActivity_listview; private List<User> listdata = new ArrayList<>(); List<Map<String, Object>> listmap = new ArrayList<>(); private EditText textname; private EditText textage; private EditText textcj; private Button butadd; protected ContentResolver cr; private Uri contenurl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); cr=getContentResolver(); contenurl= Uri.parse("content://heying.provider.contentprovider"); query(); } private void initView() { MainActivity_listview = (ListView) findViewById(R.id.MainActivity_listview); textname = (EditText) findViewById(R.id.textname); textname.setOnClickListener(this); textage = (EditText) findViewById(R.id.textage); textage.setOnClickListener(this); textcj = (EditText) findViewById(R.id.textcj); textcj.setOnClickListener(this); butadd = (Button) findViewById(R.id.butadd); butadd.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.butadd: insert(); break; } } private void query(){ Cursor cursor=cr.query(contenurl,null,null,null,null); SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.listview_layout,cursor,new String[]{"name","age","score"}, new int[]{R.id.text1,R.id.text2,R.id.text3}); MainActivity_listview.setAdapter(adapter); } private void insert() { ContentValues values=new ContentValues(); values.put("name",textname.getText().toString().trim()); values.put("age",textage.getText().toString().trim()); values.put("score",textcj.getText().toString().trim()); cr.insert(contenurl, values); Toast.makeText(this,"数据插入成功....",Toast.LENGTH_LONG).show(); query(); } }

    二)、其他应用程序的使用

    注:只要知道其他包的共享的uri就可以拿到响应共享的数据。

    package com.example.myapplication2; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private ListView main_listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); query(); } private void query() { Uri uri=Uri.parse("content://heying.provider.contentprovider"); Cursor cursor=getContentResolver().query(uri,null,null,null,null); SimpleCursorAdapter simpleCursorAdapter=new SimpleCursorAdapter(this,R.layout.listview_layout,cursor,new String[]{"name","age","score"}, new int[]{R.id.text1,R.id.text2,R.id.text3}); main_listview.setAdapter(simpleCursorAdapter); } private void initView() { main_listview = (ListView) findViewById(R.id.main_listview); } }

    UriMatcher的使用(管理多个表的共享分区)

    在自定义的ContentProvider为表设置资源标识:

    使用matcher.match(uri);方法区分:

    使用

    Processed: 0.014, SQL: 8