用自定义ContentProvider实现对数据库的增、删、改、查操作
本次对于数据库的操作是在不同的APP中进行的。下面的前四篇是在一个APP中,后面的是在另一个APP中
-------------------------------------------------------------------------------------------------
首先自定义一个SqliteOpenHelper.完成对数据库的创建和数据库内table的创建
package com.example.content_provider_03; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class My_Db_Helper extends SQLiteOpenHelper { public My_Db_Helper(Context context) { super(context, "hello.db", null, 1); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase arg0) { String sql="create table if not exists reg(_id integer primary key autoincrement,username varchar(20),password varchar(20))"; arg0.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }
---------------------------------------------------------------------------------------------------------------------------------------------
//自定义ContentProvider,重写必须的方法,完成对数据库的增删改查操作。
package com.example.content_provider_03; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; public class MyContentProvider extends ContentProvider { private My_Db_Helper helper; private String table="reg"; private static final int QUERYCODE=1; private static final int INSERTCODE=2; private static final int UPDATECODE=3; private static final int DELETECODE=4; private static UriMatcher mMatcher=new UriMatcher(UriMatcher.NO_MATCH); static { mMatcher.addURI("com.qianfeng.ly", "insert", INSERTCODE);//插入的匹配码 mMatcher.addURI("com.qianfeng.ly", "query", QUERYCODE); //查询匹配码 mMatcher.addURI("com.qianfeng.ly", "update", UPDATECODE); //编辑匹配码 mMatcher.addURI("com.qianfeng.ly", "delete", DELETECODE); //删除匹配码 } public int delete(Uri arg0, String arg1, String[] arg2) { int n=-1; if (mMatcher.match(arg0)==DELETECODE) { SQLiteDatabase db=helper.getWritableDatabase(); n=db.delete(table, arg1, arg2); } return n; } @Override public String getType(Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri arg0, ContentValues arg1) { if (mMatcher.match(arg0)==INSERTCODE) { SQLiteDatabase db=helper.getWritableDatabase(); db.insert(table, null, arg1); } return null; } //重写的 方法里面并没有此方法,但是必须有此方法 @Override public boolean onCreate() { helper=new My_Db_Helper(getContext()); return false; } @Override public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { Cursor cursor=null; if (mMatcher.match(arg0)==QUERYCODE) { SQLiteDatabase db=helper.getWritableDatabase(); cursor= db.query(table, arg1, arg2, arg3, null, null, arg4); } return cursor; } @Override public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { int n=-1; if (mMatcher.match(arg0)==UPDATECODE) { SQLiteDatabase db=helper.getWritableDatabase(); n=db.update(table, arg1, arg2, arg3); } return n; } }
-------------------------------------------------------------------------------------------------------------------------------------------
//在MainActivity中完成对数据库的插入操作
package com.example.content_provider_03; import android.os.Bundle; import android.app.Activity; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.view.Menu; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { private EditText username,password; private My_Db_Helper helper; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); username=(EditText)findViewById(R.id.username); password=(EditText)findViewById(R.id.password); helper=new My_Db_Helper(this); } public void RegH(View v) { ContentValues values=new ContentValues(); SQLiteDatabase db=helper.getWritableDatabase(); values.put("username", username.getText().toString()); values.put("password", password.getText().toString()); db.insert("reg", null, values); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
--------------------------------------------------------------------------------------------------------------------------------------
//布局界面在这里就不再赘述了
<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" > <TextView android:layout_marginTop="12dp" android:id="@+id/name" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="用户名:" /> <EditText android:layout_toRightOf="@id/name" android:layout_marginRight="10dp" android:id="@+id/username" android:layout_height="wrap_content" android:layout_width="match_parent" android:hint="请输入用户名" /> <TextView android:layout_marginTop="12dp" android:id="@+id/word" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text=" 密 码 :" android:layout_below="@id/name" /> <EditText android:layout_below="@id/name" android:id="@+id/password" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_toRightOf="@id/word" android:hint="请输入密码" /> <Button android:id="@+id/reg" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="注册" android:onClick="RegH" android:layout_below="@id/word" android:layout_centerHorizontal="true" /> </RelativeLayout>
=============================================================================================
这是另一个APP
package com.example.content_resolver03; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.net.Uri; import android.os.Bundle; import android.R.integer; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements View.OnClickListener { List<Map<String, Object>>data; ListView listView; TextView show_no; String quertUri="content://com.qianfeng.ly/query"; String insertUri="content://com.qianfeng.ly/insert"; String updateUri="content://com.qianfeng.ly/update"; String deleteUri="content://com.qianfeng.ly/delete"; private AlertDialog edDialog,delDialog; private EditText ed_name,ed_password; int position;//获得所点击的ListView的位置。 ContentResolver resolver; private Button bn1,bn2; boolean flag=true;//设置一个标志位 ,确定是进行添加还是编辑;因为要共用一个对话框 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bn1=(Button)findViewById(R.id.queryBn); bn2=(Button)findViewById(R.id.insertBn); bn1.setOnClickListener(this); bn2.setOnClickListener(this); initView(); registerForContextMenu(listView);//为选中的listView注册菜单选项 resolver=getContentResolver(); initDialog(); } public void initView() { listView=(ListView)findViewById(R.id.mylist); show_no=(TextView)findViewById(R.id.show_no); listView.setEmptyView(show_no); } //为搜索和添加按钮设置监听事件 这两个按钮不需要设置对话框; public void onClick(View v) { switch (v.getId()) { case R.id.queryBn: queryData();//列出所有项 break; case R.id.insertBn: flag=true; ed_name.setText(""); ed_password.setText(""); edDialog.show();//使添加或者编辑对话框显示 break; default: break; } } public void initDialog() { View view=getLayoutInflater().inflate(R.layout.dialog_item, null); ed_name=(EditText)view.findViewById(R.id.ed_name); ed_password=(EditText)view.findViewById(R.id.ed_password); //编辑和添加对话框 edDialog=new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_menu_add).setTitle("编辑联系人") .setView(view).setPositiveButton("确定",new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { if (flag) { insertData(); }else { updateData(); } } }).setNegativeButton("取消", null).create(); //删除对话框 delDialog=new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_menu_delete).setTitle("确定要删除吗") .setPositiveButton("确定", new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { deleteData(); } }).setNegativeButton("取消", null).create(); } //菜单选项 长按会出现 编辑||删除选项,并跳转到相应的界面。 @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { //获得菜单所对应的 XML文件 getMenuInflater().inflate(R.menu.main,menu); position=((AdapterContextMenuInfo)menuInfo).position; super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { //为选中的菜单选型设置监听事件。 switch (item.getItemId()) { case R.id.update: flag=false; edDialog.show(); Map<String, Object>map=data.get(position); ed_name.setText(map.get("username").toString()); ed_password.setText(map.get("password").toString()); break; case R.id.delete: delDialog.show(); break; default: break; } return super.onContextItemSelected(item); } public void queryData() { //对数据库内的数据进行搜索 ,当然 仅仅局限于将所有项以列表的形式列出来 Cursor cursor= resolver.query(Uri.parse(quertUri), null, null, null, null); data=CursorToList(cursor); SimpleAdapter adapter=new SimpleAdapter(this, data, R.layout.list_item, new String []{"username","password"}, new int[]{R.id.tv_name,R.id.tv_password}); listView.setAdapter(adapter); } public void insertData() { ContentValues values=new ContentValues(); values.put("username", ed_name.getText().toString()); values.put("password", ed_password.getText().toString()); resolver.insert(Uri.parse(insertUri), values); queryData(); } //编辑数据; public void updateData() { String id=data.get(position).get("_id").toString(); ContentValues values=new ContentValues(); values.put("username", ed_name.getText().toString()); values.put("password", ed_password.getText().toString()); int n=resolver.update(Uri.parse(updateUri), values, "_id=?", new String []{id}); if (n>0) { Toast.makeText(this, "编辑成功", 1).show(); } queryData();//更新数据库 } //删除数据: public void deleteData() { String id=data.get(position).get("_id").toString(); ContentValues values=new ContentValues(); values.put("username", ed_name.getText().toString()); values.put("password", ed_password.getText().toString()); int n=resolver.delete(Uri.parse(deleteUri), "_id=?", new String[]{id}); if (n>0) { Toast.makeText(this, "删除成功", 1).show(); } queryData();//更新数据库; } //将 得到的游标项转化成list public List<Map<String, Object>> CursorToList(Cursor cursor) { List<Map<String, Object>>list=new ArrayList<Map<String,Object>>(); ContentValues values=new ContentValues(); while(cursor.moveToNext()) { Map<String, Object>map=new HashMap<String, Object>(); map.put("_id", cursor.getInt(cursor.getColumnIndex("_id"))); map.put("username", cursor.getString(cursor.getColumnIndex("username"))); map.put("password", cursor.getString(cursor.getColumnIndex("password"))); list.add(map); } return list; } }
----------------------------------------------------------------------------------------------------------------------------------
接下来的是三个布局页面。
<LinearLayout 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:orientation="vertical" > <LinearLayout android:id="@+id/line" android:layout_height="wrap_content" android:layout_width="match_parent" android:orientation="horizontal" > <Button android:id="@+id/queryBn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="用我搜搜吧" /> <Button android:id="@+id/insertBn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="没有东西加一点吧" /> </LinearLayout> <ListView android:id="@+id/mylist" android:layout_height="match_parent" android:layout_width="match_parent" ></ListView> <TextView android:id="@+id/show_no" android:layout_height="match_parent" android:layout_width="match_parent" android:gravity="center" android:text="什么都没有哇" /> </LinearLayout>
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
<?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" > <EditText android:id="@+id/ed_name" android:layout_height="wrap_content" android:layout_width="match_parent" android:hint="请输入用户名" /> <EditText android:id="@+id/ed_password" android:layout_height="wrap_content" android:layout_width="match_parent" android:hint="请输入密码" /> </LinearLayout>
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
<?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/tv_name" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="一遍不行,就来无数遍" android:gravity="center" /> <TextView android:id="@+id/tv_password" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="不是运气不好,而是差一点努力" android:gravity="center" /> </LinearLayout>