自定义提供者
1 import android.content.Context; 2 import android.database.DatabaseErrorHandler; 3 import android.database.sqlite.SQLiteDatabase; 4 import android.database.sqlite.SQLiteDatabase.CursorFactory; 5 import android.database.sqlite.SQLiteOpenHelper; 6 7 public class DBHelper extends SQLiteOpenHelper { 8 9 public DBHelper(Context context) { 10 super(context, "users.db", null, 1); 11 } 12 13 @Override 14 public void onCreate(SQLiteDatabase db) { 15 // TODO 初始化数据库 16 db.execSQL("create table t_user(_id integer primary key,uname,upass,money)"); 17 18 db.execSQL("create table t_order(_id integer primary key,user_id,price,productname)"); 19 20 db.execSQL("insert into t_user(uname,upass,money) values(‘lisi‘,‘123‘,200)"); 21 22 db.execSQL("insert into t_user(uname,upass,money) values(‘zhangsi‘,‘1234‘,2000)"); 23 } 24 25 @Override 26 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 27 // TODO 数据库升级时执行该方法 28 if(newVersion>oldVersion) 29 { 30 db.execSQL("drop table if exists t_user"); 31 db.execSQL("drop table if exists t_order"); 32 //并且重新初始化数据库也可以不重新加载 33 onCreate(db); 34 } 35 36 } 37 38 39 40 }
DBHelper
1 import com.qianfeng.gp08_day25_contentprovider1.tool.DBHelper; 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 11 public class UserContentProvider extends ContentProvider { 12 13 //声明该ContentProvider的唯一标识--通常使用包名+数据库名--必须小写 14 public static final String AUTHORITY ="com.qianfeng.gp08_day25_contentprovider1.users"; 15 16 //为该组件中可以被外界访问的数据库中的资源定义Code标识 17 public static final int CODE_USER = 1; 18 public static final int CODE_ORDER = 8; 19 20 //定义访问资源的Uri的匹配器对象--使用该类生成被访问的资源的Uri 21 private static UriMatcher uriMatcher; 22 23 static{ 24 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 25 //content://com.qianfeng.gp08_day25_contentprovider1.users/user 26 uriMatcher.addURI(AUTHORITY, "user", CODE_USER); 27 28 //content://com.qianfeng.gp08_day25_contentprovider1.users/order 29 uriMatcher.addURI(AUTHORITY, "order", CODE_ORDER); 30 } 31 32 private DBHelper dbHelper; 33 34 @Override 35 public boolean onCreate() { 36 // TODO 初始化 数据库操作的工具类 37 dbHelper = new DBHelper(getContext()); 38 return false; 39 } 40 41 @Override 42 public Cursor query(Uri uri, String[] projection, String selection, 43 String[] selectionArgs, String sortOrder) { 44 SQLiteDatabase db = dbHelper.getReadableDatabase(); 45 Cursor cursor = null; 46 47 int code = uriMatcher.match(uri); 48 49 switch(code) 50 { 51 case CODE_USER: 52 cursor = db.query("t_user", projection, selection, selectionArgs, null, null, sortOrder); 53 break; 54 case CODE_ORDER: 55 cursor = db.query("t_order", projection, selection, selectionArgs, null, null, sortOrder); 56 break; 57 } 58 return cursor; 59 } 60 61 62 @Override 63 public Uri insert(Uri uri, ContentValues values) { 64 // TODO 向数据库中插入数据 65 SQLiteDatabase db =dbHelper.getWritableDatabase(); 66 if(uriMatcher.match(uri)==CODE_USER) 67 { 68 long id = db.insert("t_user", null, values); 69 70 //返回新插入的记录的 Uri 71 //content://com.qianfeng.gp08_day25_contentprovider1.users/user/6 72 return ContentUris.withAppendedId(uri, id); 73 } 74 return null; 75 } 76 77 @Override 78 public int delete(Uri uri, String selection, String[] selectionArgs) { 79 // TODO 删除数据库中的数据 80 SQLiteDatabase db = dbHelper.getWritableDatabase(); 81 int num = 0; 82 if(uriMatcher.match(uri)==CODE_USER) 83 { 84 num = db.delete("t_user", selection, selectionArgs); 85 } 86 return num; 87 } 88 89 @Override 90 public int update(Uri uri, ContentValues values, String selection, 91 String[] selectionArgs) { 92 // TODO 修改数据库中的数据 93 SQLiteDatabase db = dbHelper.getWritableDatabase(); 94 if(uriMatcher.match(uri)==CODE_USER) 95 { 96 return db.update("t_user", values, selection, selectionArgs); 97 } 98 return 0; 99 } 100 101 102 @Override 103 public String getType(Uri uri) { 104 // TODO Auto-generated method stub 105 return null; 106 } 107 108 }
usercontentprovider
查询
1 package com.qianfeng.gp08_day25_contentresolver3; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import entity.Person; 9 import android.net.Uri; 10 import android.os.Bundle; 11 import android.app.Activity; 12 import android.app.AlertDialog; 13 import android.content.ContentResolver; 14 import android.content.ContentUris; 15 import android.content.ContentValues; 16 import android.content.DialogInterface; 17 import android.content.DialogInterface.OnClickListener; 18 import android.database.Cursor; 19 import android.view.ContextMenu; 20 import android.view.Menu; 21 import android.view.MenuItem; 22 import android.view.View; 23 import android.view.ContextMenu.ContextMenuInfo; 24 import android.view.View.OnCreateContextMenuListener; 25 import android.widget.AdapterView.AdapterContextMenuInfo; 26 import android.widget.ArrayAdapter; 27 import android.widget.EditText; 28 import android.widget.ListView; 29 import android.widget.Toast; 30 31 /** 32 * 访问自定义的ContentProvider---UserContentProvider 33 * 34 * @author qq 35 * 36 */ 37 public class MainActivity extends Activity { 38 39 private ListView listView; 40 private List<Person> datas; 41 private ArrayAdapter adapter; 42 43 private Uri userUri = Uri 44 .parse("content://com.qianfeng.gp08_day25_contentprovider1.users/user"); 45 private String[] columns = { "_id", "uname", "upass", "money" }; 46 private int current; 47 private boolean isAdd; 48 private EditText edit_name, edit_pass, edit_money; 49 private View view; 50 private AlertDialog editDialog, deleteDialog; 51 52 @Override 53 protected void onCreate(Bundle savedInstanceState) { 54 super.onCreate(savedInstanceState); 55 setContentView(R.layout.activity_main); 56 57 listView = (ListView) findViewById(R.id.listView); 58 edit_name = (EditText) findViewById(R.id.edit_name); 59 edit_pass = (EditText) findViewById(R.id.edit_pass); 60 edit_money = (EditText) findViewById(R.id.edit_money); 61 datas = new ArrayList<Person>(); 62 adapter = new ArrayAdapter<Person>(this, 63 android.R.layout.simple_list_item_1, datas); 64 65 listView.setAdapter(adapter); 66 registerForContextMenu(listView); 67 68 loadData(); 69 initDialog(); 70 } 71 72 private void loadData() { 73 74 Cursor cursor = getContentResolver().query(userUri, columns, null, 75 null, null); 76 77 while (cursor.moveToNext()) { 78 long id = cursor.getLong(0); 79 String name = cursor.getString(1); 80 String pass = cursor.getString(2); 81 int money = cursor.getInt(3); 82 Person person = new Person(); 83 person.set_id(id); 84 person.setMoney(money); 85 person.setUname(name); 86 datas.add(person); 87 } 88 cursor.close();//------------------------- 89 adapter.notifyDataSetChanged(); 90 } 91 92 @Override 93 public void onCreateContextMenu(ContextMenu menu, View v, 94 ContextMenuInfo menuInfo) { 95 getMenuInflater().inflate(R.menu.item, menu); 96 current = ((AdapterContextMenuInfo) menuInfo).position; 97 super.onCreateContextMenu(menu, v, menuInfo); 98 } 99 100 @Override 101 public boolean onContextItemSelected(MenuItem item) { 102 switch (item.getItemId()) { 103 case R.id.action_update: 104 isAdd = false; 105 edit_name.setText(datas.get(current).getUname()); 106 edit_pass.setText(datas.get(current).getPass()); 107 edit_money.setText("" + datas.get(current).getMoney()); 108 editDialog.show(); 109 break; 110 case R.id.action_delete: 111 deleteDialog.show(); 112 break; 113 case R.id.action_add: 114 isAdd = true; 115 edit_name.setText(""); 116 edit_pass.setText(""); 117 edit_money.setText(""); 118 editDialog.show(); 119 break; 120 } 121 return super.onContextItemSelected(item); 122 } 123 124 private void showDatas() { 125 datas.clear(); 126 ContentResolver resolver = getContentResolver(); 127 // 先从联系人表中查询所有人的信息 128 Cursor cursor = resolver.query(userUri, columns, null, null, null); 129 while (cursor.moveToNext()) { 130 long id = cursor.getLong(0); 131 String name = cursor.getString(1); 132 String pass = cursor.getString(2); 133 int money = cursor.getInt(3); 134 Person person = new Person(); 135 person.set_id(id); 136 person.setMoney(money); 137 person.setUname(name); 138 person.setPass(pass); 139 datas.add(person); 140 } 141 cursor.close();//---------------------- 142 adapter.notifyDataSetChanged(); 143 } 144 145 public void initDialog() { 146 view = getLayoutInflater().inflate(R.layout.dialog, null); 147 edit_name = (EditText) view.findViewById(R.id.edit_name); 148 edit_pass = (EditText) view.findViewById(R.id.edit_pass); 149 edit_money = (EditText) view.findViewById(R.id.edit_money); 150 151 editDialog = new AlertDialog.Builder(this).setTitle("联系人添加对话框") 152 .setIcon(android.R.drawable.ic_menu_add).setView(view) 153 .setPositiveButton("确定", new OnClickListener() { 154 @Override 155 public void onClick(DialogInterface dialog, int which) { 156 String name = edit_name.getText().toString(); 157 String pass = edit_pass.getText().toString(); 158 String money = edit_money.getText().toString(); 159 160 ContentValues value = new ContentValues(); 161 162 if (isAdd) { 163 if(!name.equals("")) 164 { 165 value.put("uname", name); 166 value.put("upass", pass); 167 value.put("money", money); 168 getContentResolver().insert(userUri, value); 169 } 170 else Toast.makeText(MainActivity.this, "名字不能为空", Toast.LENGTH_SHORT).show(); 171 } else { 172 value.put("uname", name); 173 value.put("upass", pass); 174 value.put("money", money); 175 long id = datas.get(current).get_id(); 176 getContentResolver().update(userUri, value, "_id="+id, null); 177 } 178 showDatas(); 179 } 180 }).setNegativeButton("取消", null).setCancelable(false).create(); 181 182 deleteDialog = new AlertDialog.Builder(this).setTitle("提示") 183 .setMessage("确实要删除吗?") 184 .setIcon(android.R.drawable.ic_menu_delete) 185 .setPositiveButton("确定", new OnClickListener() { 186 187 @Override 188 public void onClick(DialogInterface dialog, int which) { 189 long id = datas.get(current).get_id(); 190 getContentResolver().delete(userUri, "_id=" + id, null); 191 192 showDatas(); 193 } 194 }).setNegativeButton("取消", null).setCancelable(false).create(); 195 } 196 197 }
MainActivity
查询结果放在listView中长按有上下文菜单选择增删改访问数据库操作数据库
时间: 2024-10-16 01:45:43