Android学习笔记-ContentProvider操作

时间:2021-11-04 09:26:17

---恢复内容开始---

之前写了一个用SQlite来实现增删改查的应用,今天又新学了一个用ContentProvider来操作的增删改查

首先ContentProvider是用来共享数据的,那么咱们先来建立一个数据源,之后用其他程序获得共享的ContentProvider,来实现CRUD

Android学习笔记-ContentProvider操作  数据源结构,一共三个Java文件

SQLDatabaseHelper.java

 1 package com.example.sqlcz;
 2 
 3 import android.content.Context;
 4 import android.database.sqlite.SQLiteDatabase;
 5 import android.database.sqlite.SQLiteOpenHelper;
 6 import android.util.Log;
 7 
 8 /**
 9  * Created by Administrator on 2016/9/22.
10  */
11 public class SQLDatabaseHelper extends SQLiteOpenHelper {
12     private static SQLDatabaseHelper sqlDatabaseHelper;
13     private static final String DB_NAME = "wxhl.db";
14     public static final String TABLE_NAME = "t_person";
15 
16     private static final int VERSION = 1;
17     private final String TAG = "--main--";
18 
19     private SQLDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
20         super(context, name, factory, version);
21     }
22 
23     public static synchronized SQLDatabaseHelper getInstance(Context context) {
24         if (sqlDatabaseHelper == null) {
25             sqlDatabaseHelper = new SQLDatabaseHelper(context, DB_NAME, null, VERSION);
26 
27         }
28         return sqlDatabaseHelper;
29     }
30     //创建数据表
31     @Override
32     public void onCreate(SQLiteDatabase db) {
33         String sql = "create table if not exists t_person"+
34                 "(_id integer primary key autoincrement," +
35                 "name text not null,age int default 18, sex text)";
36         db.execSQL(sql);
37 
38         Log.e(TAG, "onCreate: 执行---");
39     }
40 
41     @Override
42     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
43 
44     }
45 }

SQL文件主要是用来建立数据库,已经数据表,

MyContentProvider.java 核心代码

  1 package com.example.sqlcz;
  2 
  3 import android.content.ContentProvider;
  4 import android.content.ContentUris;
  5 import android.content.ContentValues;
  6 import android.content.UriMatcher;
  7 import android.database.Cursor;
  8 import android.database.sqlite.SQLiteDatabase;
  9 import android.net.Uri;
 10 import android.util.Log;
 11 
 12 /**
 13  * Created by Administrator on 2016/9/22.
 14  */
 15 public class MyContentProvider extends ContentProvider {
 16 
 17     private static final String TAG = "--main--";
 18     private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
 19     private static final int SINGLE = 1;//单条数据
 20     private static final int MULTIPLE = 2;//全部数据
 21 
 22     private SQLDatabaseHelper sqlDatabaseHelper;
 23     private SQLiteDatabase db;
 24 
 25     static {
 26         uriMatcher.addURI("com.wuxianedu.provider", "t_person", MULTIPLE);
 27         uriMatcher.addURI("com.wuxianedu.provider","t_person" + "/#", SINGLE);
 28     }
 29 
 30 
 31 
 32     @Override
 33     public boolean onCreate() {
 34         //获取数据库实例
 35         sqlDatabaseHelper = SQLDatabaseHelper.getInstance(getContext());
 36         db = sqlDatabaseHelper.getWritableDatabase();
 37         return false;
 38     }
 39     //新增数据
 40     @Override
 41     public Uri insert(Uri uri, ContentValues values) {
 42         switch (uriMatcher.match(uri)) {
 43             case MULTIPLE:
 44                 long id = db.insert("t_person", null, values);
 45                 Uri newUri = ContentUris.withAppendedId(uri, id);
 46 //                db.close();
 47                 return newUri;
 48         }
 49 //        db.close();
 50         throw new IllegalArgumentException("无效的 Uri :" + uri);
 51     }
 52     //删除数据
 53     @Override
 54     public int delete(Uri uri, String selection, String[] selectionArgs) {
 55 //        SQLiteDatabase db = sqlDatabaseHelper.getWritableDatabase();
 56         int count = 0;
 57         switch (uriMatcher.match(uri)) {
 58             case SINGLE:
 59 //                long id = ContentUris.parseId(uri);
 60 //                count = db.delete(SQLDatabaseHelper.TABLE_NAME, "id = ?", new String[]{String.valueOf(id)});
 61                 count = db.delete("t_person", selection, selectionArgs);
 62 //                db.close();
 63                 return count;
 64             case MULTIPLE:
 65                 count = db.delete("t_person", null, null);
 66 //                db.close();
 67                 return count;
 68         }
 69 //        db.close();
 70         throw new IllegalArgumentException("无效的 Uri :" + uri);
 71     }
 72     //查询数据
 73     @Override
 74     public Cursor query(Uri uri, String[] projection, String selection,
 75                         String[] selectionArgs, String sortOrder) {
 76 //        SQLiteDatabase db = sqlDatabaseHelper.getWritableDatabase();
 77         Log.e(TAG, "query: ------");
 78         Cursor cursor = null;
 79         switch (uriMatcher.match(uri)) {
 80             case SINGLE:
 81 //                long id = ContentUris.parseId(uri);
 82 //                cursor = db.query(SQLDatabaseHelper.TABLE_NAME, null, "id = ?", new String[]{String.valueOf(id)}, null, null, null);
 83                 cursor = db.query("t_person", null, selection, selectionArgs, null, null, sortOrder);
 84 //                db.close();
 85                 return cursor;
 86             case MULTIPLE:
 87                 cursor = db.query("t_person", null, null, null, null, null, sortOrder);
 88 //                db.close();
 89                 return cursor;
 90         }
 91 //        db.close();
 92         throw new IllegalArgumentException("无效的 Uri :" + uri);
 93     }
 94     //修改数据
 95     @Override
 96     public int update(Uri uri, ContentValues values, String selection,
 97                       String[] selectionArgs) {
 98 //        SQLiteDatabase db = sqlDatabaseHelper.getWritableDatabase();
 99 
100         int count = 0;
101         switch (uriMatcher.match(uri)) {
102             case SINGLE:
103 //                long id = ContentUris.parseId(uri);
104 //                count = db.update(SQLDatabaseHelper.TABLE_NAME, values, "id = ?", new String[]{String.valueOf(id)});
105                 count = db.update("t_person", values, selection, selectionArgs);
106 //                db.close();
107                 return count;
108             case MULTIPLE:
109                 count = db.update("t_person", values, null, null);
110 //                db.close();
111                 return count;
112         }
113 //        db.close();
114         throw new IllegalArgumentException("无效的 Uri :" + uri);
115     }
116 
117     @Override
118     public String getType(Uri uri) {
119         // TODO: Implement this to handle requests for the MIME type of the data
120         // at the given URI.
121         switch (uriMatcher.match(uri)) {
122             case SINGLE:
123                 return "vnd.android.cursor.item/" + "t_person";
124             case MULTIPLE:
125                 return "vnd.android.cursor.dir/" + "t_person";
126         }
127         throw new IllegalArgumentException("无效的 Uri :" + uri);
128     }
129 }
下面是共享数据的应用结构
Android学习笔记-ContentProvider操作
 

Bean文件

 1 package com.example.zuoye;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * Created by Administrator on 2016/9/22.
 7  */
 8 public class JavaBean implements Serializable {
 9     private static final long serialVersionUID = -5689121879237580927L;
10     private int id;
11     private String name;
12     private int age;
13     private String sex;
14 
15     public int getId() {
16         return id;
17     }
18     public void setId(int id) {
19         this.id = id;
20     }
21     public String getName() {
22         return name;
23     }
24     public void setName(String name) {
25         this.name = name;
26     }
27     public int getAge() {
28         return age;
29     }
30     public void setAge(int age) {
31         this.age = age;
32     }
33     public String getSex() {
34         return sex;
35     }
36     public void setSex(String sex) {
37         this.sex = sex;
38     }
39 
40     @Override
41     public String toString() {
42         return "Wechat [name=" + name + ", area=" + sex + ", weCode=" + id + "]";
43     }
44 }

MainActivity.java

 1 package com.example.zuoye;
 2 
 3 import android.content.ContentResolver;
 4 import android.content.Intent;
 5 import android.database.Cursor;
 6 import android.net.Uri;
 7 import android.support.v7.app.AppCompatActivity;
 8 import android.os.Bundle;
 9 import android.util.Log;
10 import android.view.Menu;
11 import android.view.MenuItem;
12 import android.widget.ListView;
13 
14 import java.util.ArrayList;
15 import java.util.List;
16 
17 public class MainActivity extends AppCompatActivity {
18     private MainAdapter mainAdapter;//构建数据源
19     private List<JavaBean> list;
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         ListView listview = (ListView) findViewById(R.id.liebiao);
25         list = quyy();
26         mainAdapter = new MainAdapter(this,list);
27         listview.setAdapter(mainAdapter);
28     }
29     //查询ContentProvider共享的数据
30     public List<JavaBean> quyy(){
31         List<JavaBean> list = new ArrayList<JavaBean>();
32         ContentResolver resolver = getContentResolver();
33         String str = "content://com.wuxianedu.provider/t_person";
34         Uri uri = Uri.parse(str);
35         Cursor cursor = resolver.query(uri,null,null,null,null);
36         while (cursor.moveToNext()){
37             JavaBean java = new JavaBean();
38             int id = cursor.getInt(cursor.getColumnIndex("_id"));
39             int age = cursor.getInt(cursor.getColumnIndex("age"));
40             String name = cursor.getString(cursor.getColumnIndex("name"));
41             String sex = cursor.getString(cursor.getColumnIndex("sex"));
42             Log.e("我是ID",id+"");
43             java.setId(id);
44             java.setName(name);
45             java.setAge(age);
46             java.setSex(sex);
47             list.add(java);
48             Log.e("main---",""+id+"--------------"+age+name+sex);
49         }
50 
51 /*        if(cursor !=null){
52             cursor.close();
53             cursor = null;
54         }*/
55         return list;
56     }
57 
58     @Override //菜单的点击事件
59     public boolean onCreateOptionsMenu(Menu menu) {
60         getMenuInflater().inflate(R.menu.menu,menu);
61         menu.findItem(R.id.add).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
62             @Override
63             public boolean onMenuItemClick(MenuItem item) {
64                 //点击添加跳转
65                 Intent intent=new Intent(MainActivity.this,UpdateActivity.class);
66                 startActivityForResult(intent,5);
67                 return false;
68             }
69         });
70         return super.onCreateOptionsMenu(menu);
71 
72     }
73     //利用生命周期
74     @Override
75     protected void onResume() {
76         super.onResume();
77         //重新获取list数据
78         list = quyy();
79         //给list赋值 更新
80         mainAdapter.setList(list);
81     }
82 }

下面是Adapter的代码

  1 package com.example.zuoye;
  2 
  3 import android.content.ContentResolver;
  4 import android.content.ContentUris;
  5 import android.content.Context;
  6 import android.content.DialogInterface;
  7 import android.content.Intent;
  8 import android.net.Uri;
  9 import android.support.v7.app.AlertDialog;
 10 import android.util.Log;
 11 import android.view.LayoutInflater;
 12 import android.view.View;
 13 import android.view.ViewGroup;
 14 import android.widget.BaseAdapter;
 15 import android.widget.Button;
 16 import android.widget.TextView;
 17 import android.widget.Toast;
 18 
 19 import java.util.List;
 20 
 21 /**
 22  * Created by Administrator on 2016/9/22.
 23  */
 24 public class MainAdapter extends BaseAdapter {
 25     private Context context;
 26     private List<JavaBean> list;//接收数据的LIST
 27     private ContentResolver resolver;
 28 
 29     //适配器
 30     public MainAdapter(Context context, List<JavaBean> list){
 31         this.context = context;
 32         this.list = list;
 33     }
 34     //更新集合用
 35     public void setList(List<JavaBean> list) {
 36         this.list = list;
 37         notifyDataSetChanged();
 38     }
 39 
 40     @Override
 41     public int getCount() {
 42         return list.size();
 43     }
 44 
 45     @Override
 46     public Object getItem(int position) {
 47         return list.get(position);
 48     }
 49 
 50     @Override
 51     public long getItemId(int position) {
 52         return position;
 53     }
 54 
 55     @Override
 56     public View getView(final int position, View convertView, ViewGroup parent) {
 57         resolver =context.getContentResolver();
 58         final HUi hui;
 59         if(convertView == null){
 60             hui = new HUi();
 61             convertView = LayoutInflater.from(context).inflate(R.layout.item_lie, null);
 62             hui.name = (TextView) convertView.findViewById(R.id.tv_name);
 63             hui.age = (TextView) convertView.findViewById(R.id.tv_age);
 64             hui.sex = (TextView) convertView.findViewById(R.id.tv_sex);
 65             hui.update = (Button) convertView.findViewById(R.id.but_name);
 66             hui.delete = (Button) convertView.findViewById(R.id.but_delete);
 67             //修改按钮
 68             hui.update.setOnClickListener(new View.OnClickListener() {
 69                 @Override
 70                 public void onClick(View v) {
 71                     Intent intent = new Intent(context,UpdateActivity.class);
 72                     int ooon = (int) hui.update.getTag();
 73                     Log.e("main---","------Adapterget出来的Id--------"+ooon);
 74                     JavaBean javabean = list.get(ooon);
 75                     intent.putExtra("name",javabean);
 76                     context.startActivity(intent);
 77                 }
 78             });
 79             convertView.setTag(hui);
 80         }else{
 81             hui = (HUi) convertView.getTag();
 82         }
 83         final JavaBean java = list.get(position);
 84         // hui.update.setTag(position);
 85         hui.name.setText(java.getName());
 86         hui.age.setText(String.valueOf(java.getAge()));
 87         hui.sex.setText(java.getSex());
 88         hui.delete.setTag(position);
 89         hui.update.setTag(position);
 90         //构建删除对话框
 91         hui.delete.setOnClickListener(new View.OnClickListener() {
 92             @Override
 93             public void onClick(View v) {
 94                 AlertDialog.Builder builder = new  AlertDialog.Builder(context);
 95                 builder.setMessage("确定删除吗?");
 96                 builder.setPositiveButton("取消",null);
 97                 builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
 98                     @Override
 99                     public void onClick(DialogInterface dialog, int which) {
100                         //获取下标
101                         int on = (int) hui.delete.getTag()+1;
102                         String str = "content://com.wuxianedu.provider/t_person/"+java.getId();
103                         Uri uri = Uri.parse(str);
104                         long id = ContentUris.parseId(uri);
105                         int index = resolver.delete(uri,"_id = ? ",new String[]{String.valueOf(id)});
106                         list.remove(position);
107                         notifyDataSetChanged();
108                         Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show();
109                     }
110                 }).show();
111 
112             }
113         });
114         return convertView;
115     }
116     //优化ListView
117     class HUi {
118         TextView name,age,sex;
119         Button update,delete;
120     }
121 }

  添加数据和修改数据代码

 1 package com.example.zuoye;
 2 
 3 import android.content.ContentResolver;
 4 import android.content.ContentUris;
 5 import android.content.ContentValues;
 6 import android.content.Intent;
 7 import android.net.Uri;
 8 import android.support.v7.app.AppCompatActivity;
 9 import android.os.Bundle;
10 import android.util.Log;
11 import android.view.View;
12 import android.widget.Button;
13 import android.widget.EditText;
14 import android.widget.Toast;
15 
16 public class UpdateActivity extends AppCompatActivity implements View.OnClickListener {
17 
18     private EditText ed_name,ed_sex,ed_age;
19     private JavaBean com;
20     private Button xiugai,shanchu;
21     private ContentResolver resolver;
22 
23     @Override
24     protected void onCreate(Bundle savedInstanceState) {
25         super.onCreate(savedInstanceState);
26         setContentView(R.layout.activity_update);
27         ed_name= (EditText) findViewById(R.id.ed_name);
28         ed_age = (EditText) findViewById(R.id.ed_age);
29         ed_sex = (EditText) findViewById(R.id.ed_sex);
30         xiugai = (Button) findViewById(R.id.but_tianjia);
31         shanchu = (Button) findViewById(R.id.but_queding);
32         Intent on = getIntent();
33         com = (JavaBean) on.getSerializableExtra("name");
34         //这里是取值,是否为空,如果为空就是从添加用户过来的,如果不为空就是从增加数据过来的
35         if(com == null){
36             shanchu.setVisibility(View.GONE);
37         }else{
38             xiugai.setVisibility(View.GONE);
39             ed_name.setText(com.getName()+"");
40             ed_age.setText(String.valueOf(com.getAge())+"");
41             ed_sex.setText(com.getSex()+"");
42         }
43         xiugai.setOnClickListener(this);
44         shanchu.setOnClickListener(this);
45 
46     }
47     private void SqlInsert(){
48         ContentValues contentValues = new ContentValues();
49         contentValues.put("name",ed_name.getText().toString());
50         contentValues.put("age",ed_age.getText().toString());
51         contentValues.put("sex",ed_sex.getText().toString());
52        /* db.insert(contentValues);*/
53         resolver = getContentResolver();
54         String str = "content://com.wuxianedu.provider/t_person";
55         Uri uri = Uri.parse(str);
56         // long id = ContentUris.parseId(uri);
57         Uri rUri = resolver.insert(uri,contentValues);
58         Toast.makeText(UpdateActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
59     }
60     //修改数据
61     private void SqlUpdate(){
62         resolver = getContentResolver();
63         String str = "content://com.wuxianedu.provider/t_person/"+(com.getId());
64         Log.e("main--get出来的ID-",""+com.getId());
65         //转换URI
66         Uri uri = Uri.parse(str);
67         long id = ContentUris.parseId(uri);
68         Log.e("main--uri出来的ID-",""+id+"");
69         ContentValues values = new ContentValues();
70         values.put("name",ed_name.getText().toString());
71         values.put("age",ed_age.getText().toString());
72         values.put("sex",ed_sex.getText().toString());
73         int index =  resolver.update(uri,values,"_id = ?",new String[]{String.valueOf(id)});;
74         Toast.makeText(UpdateActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
75     }
76     //判断
77     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
78         if(requestCode != 5){
79 
80         }
81     }
82 
83     @Override
84     public void onClick(View v) {
85         switch (v.getId()){
86             case R.id.but_queding:
87                 SqlUpdate();
88                 break;
89             case R.id.but_tianjia:
90                 SqlInsert();
91                 break;
92         }
93     }
94 }

对了,还需要注册,在AndroidManfest.xml中进行注册,代码如下

<provider
android:name=".MyContentProvider"
android:authorities="com.wuxianedu.provider"
android:enabled="true"
android:exported="true">
</provider>
注:注册时在第一个应用里面注册,第二个不用

下面把布局代码贴一下,
第二个应用activity_main.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6 //这里面只有一个ListView,
 7     tools:context="com.example.zuoye.MainActivity">
 8 
 9     <ListView android:id="@+id/liebiao"
10         android:layout_width="wrap_content"
11         android:layout_height="wrap_content"
12         android:text="Hello World!" />
13 </RelativeLayout>

Adapter的布局文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="horizontal" android:layout_width="match_parent"
 4     android:layout_height="match_parent">
 5     <LinearLayout   android:layout_width="0dp"
 6         android:layout_height="wrap_content"
 7         android:layout_weight="5">
 8         <TextView android:id="@+id/tv_name"
 9             android:layout_width="0dp" android:layout_gravity="center_vertical"
10             android:layout_height="wrap_content"
11             android:text="aaa" android:layout_weight="1"
12             android:gravity="center"/>
13 
14         <TextView android:id="@+id/tv_age"
15             android:layout_width="wrap_content"
16             android:layout_height="wrap_content" android:layout_gravity="center_vertical"
17             android:text="aaa" android:layout_weight="1"
18             android:gravity="center"/>
19         <TextView android:id="@+id/tv_sex"
20             android:layout_width="wrap_content"
21             android:layout_height="wrap_content" android:layout_gravity="center_vertical"
22             android:text="aaa" android:layout_weight="1"
23             android:gravity="center"/>
24     </LinearLayout>
25     <Button android:id="@+id/but_name"
26         android:layout_width="0dp"
27         android:layout_height="40dp"
28         android:layout_marginTop="2dp"
29         android:text="修改" android:layout_weight="1"
30         android:gravity="center"  android:background="#3F51B5"
31         android:textColor="#FFFFFF"  android:padding="10dp"
32         android:layout_marginRight="10dp"/>
33 
34     <Button android:id="@+id/but_delete"
35         android:layout_width="0dp"
36         android:layout_height="40dp"
37         android:layout_marginTop="2dp"
38         android:text="删除" android:layout_weight="1"
39         android:gravity="center" android:background="#3F51B5"
40 
41         android:textColor="#FFFFFF" android:layout_marginRight="10dp"/>
42 </LinearLayout>

修改和添加用户的界面

 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.zuoye.UpdateActivity">
    <EditText android:id="@+id/ed_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入姓名"/>

    <EditText android:id="@+id/ed_age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入年龄"
        android:layout_below="@+id/ed_name"/>

    <EditText android:id="@+id/ed_sex"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入性别"
        android:layout_below="@+id/ed_age"/>

    <Button android:id="@+id/but_queding"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="修改用户"
        android:layout_below="@+id/ed_sex"/>

    <Button android:id="@+id/but_tianjia"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="添加用户"
        android:layout_below="@+id/ed_sex"/>
</RelativeLayout>
 

好了,到这里就全部完成了,最后时限效果是这样的

 

Android学习笔记-ContentProvider操作Android学习笔记-ContentProvider操作

 

---恢复内容结束---