ContenProvider:简单查询及修改
1.提供数据来源,在本地创建数据库文件
package util; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by ASUS on 2017/2/7. */ public class DbUtil extends SQLiteOpenHelper{ public DbUtil(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } //创建表的操作 @Override public void onCreate(SQLiteDatabase db) { //创建表 db.execSQL("create table person(_id integer primary key autoincrement,name,age)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
2.编写简单布局文件
如图一:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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" android:orientation="vertical" tools:context="com.asus.android_16_sqlite.MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="ID" android:id="@+id/et_main_id" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="用户名" android:id="@+id/et_main_username" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="年龄" android:id="@+id/et_main_userage" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存" android:onClick="save" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查询" android:onClick="query" android:layout_weight="1" /> </LinearLayout> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/list"> </ListView> </LinearLayout>
3.ContentProvider内容提供者,内容来源:数据库
首先写一个类,继承ContentProvider
他会重写6个方法,
如下:
package provider; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.support.annotation.Nullable; import android.util.Log; import util.DbUtil; /** * Created by ASUS on 2017/2/8. */ public class MyContentProvider extends ContentProvider{ private SQLiteDatabase db; private UriMatcher uriMatcher; @Override public boolean onCreate() { Log.i("test","onCreate"); DbUtil dbUtil=new DbUtil(getContext(),"person.db",null,2); db = dbUtil.getReadableDatabase(); //实例化URI匹配器 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); //添加规则 //1.查询所有 uriMatcher.addURI("com.asus.android_16_sqlite.PERSON","person",1); //2.查询单个 uriMatcher.addURI("com.asus.android_16_sqlite.PERSON","person/#",2); // uriMatcher.addURI("com.asus.android_16_sqlite.PERSON","person/#/#/#",3); return false; } @Nullable @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { //根据URI匹配器开始匹配uri int code=uriMatcher.match(uri); switch (code) { case 1 : //查询所有 Log.i("test","query所有"); //获取数据库中所有的数据 return db.query(false,"person",projection,selection,selectionArgs,null,null,sortOrder,null); case 2 : //查询单个 //获取#的值 long id=ContentUris.parseId(uri); Log.i("test","query单个"); return db.rawQuery("select * from person where _id=?",new String[]{id+""}); } return null; } @Nullable @Override public String getType(Uri uri) { Log.i("test","getType"); return null; } @Nullable @Override public Uri insert(Uri uri, ContentValues values) { Log.i("test","insert"); return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { Log.i("test","delete"); return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { Log.i("test","update"); // db.execSQL(" update person set name=?,age=? where _id=? ",new String[]{""+2,""+2,""+2}); // String str=""+uriMatcher.match(uri); // Log.i("text",str); return db.update("person",values,selection,selectionArgs); } }4.MainActivity:
package com.asus.android_24_contentprovider; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private ContentResolver contentResolver; private EditText et_main_id; private Uri uri; private ListView listview_main_person; private Cursor cursor; private SimpleCursorAdapter simpleCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentResolver = getContentResolver(); et_main_id = (EditText) findViewById(R.id.et_main_id); listview_main_person = (ListView) findViewById(R.id.listview_main_person); } public void getData(View view){ //判断输入框的值是否为空 if (TextUtils.isEmpty(et_main_id.getText().toString())){ //为空,查询所有 uri = Uri.parse("content://com.asus.android_16_sqlite.PERSON/person"); }else{ //不为空,查询单个 String id=et_main_id.getText().toString(); uri = Uri.parse("content://com.asus.android_16_sqlite.PERSON/person/"+id); } cursor = contentResolver.query(uri,null,null,null,null); simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.items_listview,cursor,new String[]{"_id","name","age"},new int[]{R.id.tv_items_id,R.id.tv_items_name,R.id.tv_items_age}); //给ListView设置适配器 listview_main_person.setAdapter(simpleCursorAdapter); //给ListView设置长按事件 listview_main_person.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { private TextView tv_dialog_id; private EditText et_dialog_age; private EditText et_dialog_name; @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { LinearLayout root= (LinearLayout) view; String _id=((TextView) root.findViewById(R.id.tv_items_id)).getText().toString(); String name=((TextView) root.findViewById(R.id.tv_items_name)).getText().toString(); String age=((TextView) root.findViewById(R.id.tv_items_age)).getText().toString(); final AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); final AlertDialog alertDialog=builder.create(); //点击空白处,不取消对话框 alertDialog.setCancelable(false); // View v= LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_dialog,null); View v=View.inflate(MainActivity.this,R.layout.activity_dialog,null); tv_dialog_id = (TextView) v.findViewById(R.id.tv_dialog_id); et_dialog_name = (EditText) v.findViewById(R.id.et_dialog_name); et_dialog_age = (EditText) v.findViewById(R.id.et_dialog_age); tv_dialog_id.setText(_id); et_dialog_name.setText(name); et_dialog_age.setText(age); ((Button)v.findViewById(R.id.bt_dialog_ok)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String id=tv_dialog_id.getText().toString(); String name=et_dialog_name.getText().toString(); String age=et_dialog_age.getText().toString(); // Toast.makeText(MainActivity.this, ""+ et_dialog_name.getText().toString(), Toast.LENGTH_SHORT).show(); uri = Uri.parse("content://com.asus.android_16_sqlite.PERSON/person/"); ContentValues values=new ContentValues(); values.put("name",""+et_dialog_name.getText().toString()); values.put("age",""+et_dialog_age.getText().toString()); contentResolver.update(uri,values,"_id=?",new String[]{id}); //重新查询,刷新 cursor = contentResolver.query(uri,null,null,null,null); //通知适配器发生该变 simpleCursorAdapter.changeCursor(cursor); //关闭当前的对话框 alertDialog.dismiss(); } }); ((Button)v.findViewById(R.id.bt_dialog_no)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //关闭当前的对话框 alertDialog.dismiss(); } }); alertDialog.setView(v); alertDialog.show(); return true; } }); while (cursor.moveToNext()){ int id=cursor.getInt(cursor.getColumnIndex("_id")); String name=cursor.getString(cursor.getColumnIndex("name")); int age=cursor.getInt(cursor.getColumnIndex("age")); Log.i("test",id+" "+name+" "+age); } } }5.记得要注册内容提供者在AndroidManifest.xml中
<!--配置内容提供者--> <provider android:authorities="com.asus.android_16_sqlite.PERSON" android:name="provider.MyContentProvider" android:exported="true" > </provider>提示,本DemoListView设置长按功能,布局文件自己写即可。
这样,自定义内容提供者就写好了。ContentResolver:简单查询及修改然后,我们写内容访问者:步骤差不多:1.写布局文件如图二<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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" android:orientation="vertical" tools:context="com.asus.android_24_contentprovider.MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/et_main_id" android:hint="请输入ID" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="获取数据" android:onClick="getData" /> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/listview_main_person" > </ListView> </LinearLayout>2.MainActvitypackage com.asus.android_24_contentprovider; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private ContentResolver contentResolver; private EditText et_main_id; private Uri uri; private ListView listview_main_person; private Cursor cursor; private SimpleCursorAdapter simpleCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contentResolver = getContentResolver(); et_main_id = (EditText) findViewById(R.id.et_main_id); listview_main_person = (ListView) findViewById(R.id.listview_main_person); } public void getData(View view){ //判断输入框的值是否为空 if (TextUtils.isEmpty(et_main_id.getText().toString())){ //为空,查询所有 uri = Uri.parse("content://com.asus.android_16_sqlite.PERSON/person"); }else{ //不为空,查询单个 String id=et_main_id.getText().toString(); uri = Uri.parse("content://com.asus.android_16_sqlite.PERSON/person/"+id); } cursor = contentResolver.query(uri,null,null,null,null); simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.items_listview,cursor,new String[]{"_id","name","age"},new int[]{R.id.tv_items_id,R.id.tv_items_name,R.id.tv_items_age}); //给ListView设置适配器 listview_main_person.setAdapter(simpleCursorAdapter); //给ListView设置长按事件 listview_main_person.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { private TextView tv_dialog_id; private EditText et_dialog_age; private EditText et_dialog_name; @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { LinearLayout root= (LinearLayout) view; String _id=((TextView) root.findViewById(R.id.tv_items_id)).getText().toString(); String name=((TextView) root.findViewById(R.id.tv_items_name)).getText().toString(); String age=((TextView) root.findViewById(R.id.tv_items_age)).getText().toString(); final AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); final AlertDialog alertDialog=builder.create(); //点击空白处,不取消对话框 alertDialog.setCancelable(false); // View v= LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_dialog,null); View v=View.inflate(MainActivity.this,R.layout.activity_dialog,null); tv_dialog_id = (TextView) v.findViewById(R.id.tv_dialog_id); et_dialog_name = (EditText) v.findViewById(R.id.et_dialog_name); et_dialog_age = (EditText) v.findViewById(R.id.et_dialog_age); tv_dialog_id.setText(_id); et_dialog_name.setText(name); et_dialog_age.setText(age); ((Button)v.findViewById(R.id.bt_dialog_ok)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String id=tv_dialog_id.getText().toString(); String name=et_dialog_name.getText().toString(); String age=et_dialog_age.getText().toString(); // Toast.makeText(MainActivity.this, ""+ et_dialog_name.getText().toString(), Toast.LENGTH_SHORT).show(); uri = Uri.parse("content://com.asus.android_16_sqlite.PERSON/person/"); ContentValues values=new ContentValues(); values.put("name",""+et_dialog_name.getText().toString()); values.put("age",""+et_dialog_age.getText().toString()); contentResolver.update(uri,values,"_id=?",new String[]{id}); //重新查询,刷新 cursor = contentResolver.query(uri,null,null,null,null); //通知适配器发生该变 simpleCursorAdapter.changeCursor(cursor); //关闭当前的对话框 alertDialog.dismiss(); } }); ((Button)v.findViewById(R.id.bt_dialog_no)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //关闭当前的对话框 alertDialog.dismiss(); } }); alertDialog.setView(v); alertDialog.show(); return true; } }); while (cursor.moveToNext()){ int id=cursor.getInt(cursor.getColumnIndex("_id")); String name=cursor.getString(cursor.getColumnIndex("name")); int age=cursor.getInt(cursor.getColumnIndex("age")); Log.i("test",id+" "+name+" "+age); } } }