Android学习笔记-ContentProvider操作

胸怀万里世界, 放眼无限未来。这篇文章主要讲述Android学习笔记-ContentProvider操作相关的知识,希望能为你提供帮助。
---恢复内容开始---
之前写了一个用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 { 12private static SQLDatabaseHelper sqlDatabaseHelper; 13private static final String DB_NAME = "wxhl.db"; 14public static final String TABLE_NAME = "t_person"; 15 16private static final int VERSION = 1; 17private final String TAG = "--main--"; 18 19private SQLDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { 20super(context, name, factory, version); 21} 22 23public static synchronized SQLDatabaseHelper getInstance(Context context) { 24if (sqlDatabaseHelper == null) { 25sqlDatabaseHelper = new SQLDatabaseHelper(context, DB_NAME, null, VERSION); 26 27} 28return sqlDatabaseHelper; 29} 30//创建数据表 31@Override 32public void onCreate(SQLiteDatabase db) { 33String 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)"; 36db.execSQL(sql); 37 38Log.e(TAG, "onCreate: 执行---"); 39} 40 41@Override 42public 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 17private static final String TAG = "--main--"; 18private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 19private static final int SINGLE = 1; //单条数据 20private static final int MULTIPLE = 2; //全部数据 21 22private SQLDatabaseHelper sqlDatabaseHelper; 23private SQLiteDatabase db; 24 25static { 26uriMatcher.addURI("com.wuxianedu.provider", "t_person", MULTIPLE); 27uriMatcher.addURI("com.wuxianedu.provider","t_person" + "/#", SINGLE); 28} 29 30 31 32@Override 33public boolean onCreate() { 34//获取数据库实例 35sqlDatabaseHelper = SQLDatabaseHelper.getInstance(getContext()); 36db = sqlDatabaseHelper.getWritableDatabase(); 37return false; 38} 39//新增数据 40@Override 41public Uri insert(Uri uri, ContentValues values) { 42switch (uriMatcher.match(uri)) { 43case MULTIPLE: 44long id = db.insert("t_person", null, values); 45Uri newUri = ContentUris.withAppendedId(uri, id); 46 //db.close(); 47return newUri; 48} 49 //db.close(); 50throw new IllegalArgumentException("无效的 Uri :" + uri); 51} 52//删除数据 53@Override 54public int delete(Uri uri, String selection, String[] selectionArgs) { 55 //SQLiteDatabase db = sqlDatabaseHelper.getWritableDatabase(); 56int count = 0; 57switch (uriMatcher.match(uri)) { 58case SINGLE: 59 //long id = ContentUris.parseId(uri); 60 //count = db.delete(SQLDatabaseHelper.TABLE_NAME, "id = ?", new String[]{String.valueOf(id)}); 61count = db.delete("t_person", selection, selectionArgs); 62 //db.close(); 63return count; 64case MULTIPLE: 65count = db.delete("t_person", null, null); 66 //db.close(); 67return count; 68} 69 //db.close(); 70throw new IllegalArgumentException("无效的 Uri :" + uri); 71} 72//查询数据 73@Override 74public Cursor query(Uri uri, String[] projection, String selection, 75String[] selectionArgs, String sortOrder) { 76 //SQLiteDatabase db = sqlDatabaseHelper.getWritableDatabase(); 77Log.e(TAG, "query: ------"); 78Cursor cursor = null; 79switch (uriMatcher.match(uri)) { 80case SINGLE: 81 //long id = ContentUris.parseId(uri); 82 //cursor = db.query(SQLDatabaseHelper.TABLE_NAME, null, "id = ?", new String[]{String.valueOf(id)}, null, null, null); 83cursor = db.query("t_person", null, selection, selectionArgs, null, null, sortOrder); 84 //db.close(); 85return cursor; 86case MULTIPLE: 87cursor = db.query("t_person", null, null, null, null, null, sortOrder); 88 //db.close(); 89return cursor; 90} 91 //db.close(); 92throw new IllegalArgumentException("无效的 Uri :" + uri); 93} 94//修改数据 95@Override 96public int update(Uri uri, ContentValues values, String selection, 97String[] selectionArgs) { 98 //SQLiteDatabase db = sqlDatabaseHelper.getWritableDatabase(); 99 100int count = 0; 101switch (uriMatcher.match(uri)) { 102case SINGLE: 103 //long id = ContentUris.parseId(uri); 104 //count = db.update(SQLDatabaseHelper.TABLE_NAME, values, "id = ?", new String[]{String.valueOf(id)}); 105count = db.update("t_person", values, selection, selectionArgs); 106 //db.close(); 107return count; 108case MULTIPLE: 109count = db.update("t_person", values, null, null); 110 //db.close(); 111return count; 112} 113 //db.close(); 114throw new IllegalArgumentException("无效的 Uri :" + uri); 115} 116 117@Override 118public String getType(Uri uri) { 119// TODO: Implement this to handle requests for the MIME type of the data 120// at the given URI. 121switch (uriMatcher.match(uri)) { 122case SINGLE: 123return "vnd.android.cursor.item/" + "t_person"; 124case MULTIPLE: 125return "vnd.android.cursor.dir/" + "t_person"; 126} 127throw new IllegalArgumentException("无效的 Uri :" + uri); 128} 129 }

下面是共享数据的应用结构
Android学习笔记-ContentProvider操作

文章图片


 

【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 { 9private static final long serialVersionUID = -5689121879237580927L; 10private int id; 11private String name; 12private int age; 13private String sex; 14 15public int getId() { 16return id; 17} 18public void setId(int id) { 19this.id = id; 20} 21public String getName() { 22return name; 23} 24public void setName(String name) { 25this.name = name; 26} 27public int getAge() { 28return age; 29} 30public void setAge(int age) { 31this.age = age; 32} 33public String getSex() { 34return sex; 35} 36public void setSex(String sex) { 37this.sex = sex; 38} 39 40@Override 41public String toString() { 42return "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 { 18private MainAdapter mainAdapter; //构建数据源 19private List< JavaBean> list; 20@Override 21protected void onCreate(Bundle savedInstanceState) { 22super.onCreate(savedInstanceState); 23setContentView(R.layout.activity_main); 24ListView listview = (ListView) findViewById(R.id.liebiao); 25list = quyy(); 26mainAdapter = new MainAdapter(this,list); 27listview.setAdapter(mainAdapter); 28} 29//查询ContentProvider共享的数据 30public List< JavaBean> quyy(){ 31List< JavaBean> list = new ArrayList< JavaBean> (); 32ContentResolver resolver = getContentResolver(); 33String str = "content://com.wuxianedu.provider/t_person"; 34Uri uri = Uri.parse(str); 35Cursor cursor = resolver.query(uri,null,null,null,null); 36while (cursor.moveToNext()){ 37JavaBean java = new JavaBean(); 38int id = cursor.getInt(cursor.getColumnIndex("_id")); 39int age = cursor.getInt(cursor.getColumnIndex("age")); 40String name = cursor.getString(cursor.getColumnIndex("name")); 41String sex = cursor.getString(cursor.getColumnIndex("sex")); 42Log.e("我是ID",id+""); 43java.setId(id); 44java.setName(name); 45java.setAge(age); 46java.setSex(sex); 47list.add(java); 48Log.e("main---",""+id+"--------------"+age+name+sex); 49} 50 51 /*if(cursor !=null){ 52cursor.close(); 53cursor = null; 54}*/ 55return list; 56} 57 58@Override //菜单的点击事件 59public boolean onCreateOptionsMenu(Menu menu) { 60getMenuInflater().inflate(R.menu.menu,menu); 61menu.findItem(R.id.add).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { 62@Override 63public boolean onMenuItemClick(MenuItem item) { 64//点击添加跳转 65Intent intent=new Intent(MainActivity.this,UpdateActivity.class); 66startActivityForResult(intent,5); 67return false; 68} 69}); 70return super.onCreateOptionsMenu(menu); 71 72} 73//利用生命周期 74@Override 75protected void onResume() { 76super.onResume(); 77//重新获取list数据 78list = quyy(); 79//给list赋值 更新 80mainAdapter.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 { 25private Context context; 26private List< JavaBean> list; //接收数据的LIST 27private ContentResolver resolver; 28 29//适配器 30public MainAdapter(Context context, List< JavaBean> list){ 31this.context = context; 32this.list = list; 33} 34//更新集合用 35public void setList(List< JavaBean> list) { 36this.list = list; 37notifyDataSetChanged(); 38} 39 40@Override 41public int getCount() { 42return list.size(); 43} 44 45@Override 46public Object getItem(int position) { 47return list.get(position); 48} 49 50@Override 51public long getItemId(int position) { 52return position; 53} 54 55@Override 56public View getView(final int position, View convertView, ViewGroup parent) { 57resolver =context.getContentResolver(); 58final HUi hui; 59if(convertView == null){ 60hui = new HUi(); 61convertView = LayoutInflater.from(context).inflate(R.layout.item_lie, null); 62hui.name = (TextView) convertView.findViewById(R.id.tv_name); 63hui.age = (TextView) convertView.findViewById(R.id.tv_age); 64hui.sex = (TextView) convertView.findViewById(R.id.tv_sex); 65hui.update = (Button) convertView.findViewById(R.id.but_name); 66hui.delete = (Button) convertView.findViewById(R.id.but_delete); 67//修改按钮 68hui.update.setOnClickListener(new View.OnClickListener() { 69@Override 70public void onClick(View v) { 71Intent intent = new Intent(context,UpdateActivity.class); 72int ooon = (int) hui.update.getTag(); 73Log.e("main---","------Adapterget出来的Id--------"+ooon); 74JavaBean javabean = list.get(ooon); 75intent.putExtra("name",javabean); 76context.startActivity(intent); 77} 78}); 79convertView.setTag(hui); 80}else{ 81hui = (HUi) convertView.getTag(); 82} 83final JavaBean java = list.get(position); 84// hui.update.setTag(position); 85hui.name.setText(java.getName()); 86hui.age.setText(String.valueOf(java.getAge())); 87hui.sex.setText(java.getSex()); 88hui.delete.setTag(position); 89hui.update.setTag(position); 90//构建删除对话框 91hui.delete.setOnClickListener(new View.OnClickListener() { 92@Override 93public void onClick(View v) { 94AlertDialog.Builder builder = newAlertDialog.Builder(context); 95builder.setMessage("确定删除吗?"); 96builder.setPositiveButton("取消",null); 97builder.setNegativeButton("确定", new DialogInterface.OnClickListener() { 98@Override 99public void onClick(DialogInterface dialog, int which) { 100//获取下标 101int on = (int) hui.delete.getTag()+1; 102String str = "content://com.wuxianedu.provider/t_person/"+java.getId(); 103Uri uri = Uri.parse(str); 104long id = ContentUris.parseId(uri); 105int index = resolver.delete(uri,"_id = ? ",new String[]{String.valueOf(id)}); 106list.remove(position); 107notifyDataSetChanged(); 108Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show(); 109} 110}).show(); 111 112} 113}); 114return convertView; 115} 116//优化ListView 117class HUi { 118TextView name,age,sex; 119Button 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 18private EditText ed_name,ed_sex,ed_age; 19private JavaBean com; 20private Button xiugai,shanchu; 21private ContentResolver resolver; 22 23@Override 24protected void onCreate(Bundle savedInstanceState) { 25super.onCreate(savedInstanceState); 26setContentView(R.layout.activity_update); 27ed_name= (EditText) findViewById(R.id.ed_name); 28ed_age = (EditText) findViewById(R.id.ed_age); 29ed_sex = (EditText) findViewById(R.id.ed_sex); 30xiugai = (Button) findViewById(R.id.but_tianjia); 31shanchu = (Button) findViewById(R.id.but_queding); 32Intent on = getIntent(); 33com = (JavaBean) on.getSerializableExtra("name"); 34//这里是取值,是否为空,如果为空就是从添加用户过来的,如果不为空就是从增加数据过来的 35if(com == null){ 36shanchu.setVisibility(View.GONE); 37}else{ 38xiugai.setVisibility(View.GONE); 39ed_name.setText(com.getName()+""); 40ed_age.setText(String.valueOf(com.getAge())+""); 41ed_sex.setText(com.getSex()+""); 42} 43xiugai.setOnClickListener(this); 44shanchu.setOnClickListener(this); 45 46} 47private void SqlInsert(){ 48ContentValues contentValues = new ContentValues(); 49contentValues.put("name",ed_name.getText().toString()); 50contentValues.put("age",ed_age.getText().toString()); 51contentValues.put("sex",ed_sex.getText().toString()); 52/* db.insert(contentValues); */ 53resolver = getContentResolver(); 54String str = "content://com.wuxianedu.provider/t_person"; 55Uri uri = Uri.parse(str); 56// long id = ContentUris.parseId(uri); 57Uri rUri = resolver.insert(uri,contentValues); 58Toast.makeText(UpdateActivity.this,"添加成功",Toast.LENGTH_SHORT).show(); 59} 60//修改数据 61private void SqlUpdate(){ 62resolver = getContentResolver(); 63String str = "content://com.wuxianedu.provider/t_person/"+(com.getId()); 64Log.e("main--get出来的ID-",""+com.getId()); 65//转换URI 66Uri uri = Uri.parse(str); 67long id = ContentUris.parseId(uri); 68Log.e("main--uri出来的ID-",""+id+""); 69ContentValues values = new ContentValues(); 70values.put("name",ed_name.getText().toString()); 71values.put("age",ed_age.getText().toString()); 72values.put("sex",ed_sex.getText().toString()); 73int index =resolver.update(uri,values,"_id = ?",new String[]{String.valueOf(id)}); ; 74Toast.makeText(UpdateActivity.this,"修改成功",Toast.LENGTH_SHORT).show(); 75} 76//判断 77protected void onActivityResult(int requestCode, int resultCode, Intent data) { 78if(requestCode != 5){ 79 80} 81} 82 83@Override 84public void onClick(View v) { 85switch (v.getId()){ 86case R.id.but_queding: 87SqlUpdate(); 88break; 89case R.id.but_tianjia: 90SqlInsert(); 91break; 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" 3xmlns:tools="http://schemas.android.com/tools" 4android:layout_width="match_parent" 5android:layout_height="match_parent" 6 //这里面只有一个ListView, 7tools:context="com.example.zuoye.MainActivity"> 8 9< ListView android:id="@+id/liebiao" 10android:layout_width="wrap_content" 11android:layout_height="wrap_content" 12android: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" 3android:orientation="horizontal" android:layout_width="match_parent" 4android:layout_height="match_parent"> 5< LinearLayoutandroid:layout_width="0dp" 6android:layout_height="wrap_content" 7android:layout_weight="5"> 8< TextView android:id="@+id/tv_name" 9android:layout_width="0dp" android:layout_gravity="center_vertical" 10android:layout_height="wrap_content" 11android:text="aaa" android:layout_weight="1" 12android:gravity="center"/> 13 14< TextView android:id="@+id/tv_age" 15android:layout_width="wrap_content" 16android:layout_height="wrap_content" android:layout_gravity="center_vertical" 17android:text="aaa" android:layout_weight="1" 18android:gravity="center"/> 19< TextView android:id="@+id/tv_sex" 20android:layout_width="wrap_content" 21android:layout_height="wrap_content" android:layout_gravity="center_vertical" 22android:text="aaa" android:layout_weight="1" 23android:gravity="center"/> 24< /LinearLayout> 25< Button android:id="@+id/but_name" 26android:layout_width="0dp" 27android:layout_height="40dp" 28android:layout_marginTop="2dp" 29android:text="修改" android:layout_weight="1" 30android:gravity="center"android:background="#3F51B5" 31android:textColor="#FFFFFF"android:padding="10dp" 32android:layout_marginRight="10dp"/> 33 34< Button android:id="@+id/but_delete" 35android:layout_width="0dp" 36android:layout_height="40dp" 37android:layout_marginTop="2dp" 38android:text="删除" android:layout_weight="1" 39android:gravity="center" android:background="#3F51B5" 40 41android: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操作

文章图片



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

    推荐阅读