private DbHelper dbHelper;自定义一个类继承ContentProvider(内容提供者)重新里面的六个方法,通过getContentResolver()来调用ContentProvider(内容提供者)中的方法private SQLiteDatabase sqLiteDatabase; private UriMatcher uriMatcher; @Override public boolean onCreate() { Log.i("test","onCreate"); dbHelper = new DbHelper(getContext(),"person.db",null,2); sqLiteDatabase = dbHelper.getReadableDatabase(); return false; } @Nullable @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Log.i("test","query1111"); return sqLiteDatabase.query(false,"person",projection,selection,selectionArgs,null,null,sortOrder,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"); sqLiteDatabase.insert("person","name",values); return null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { Log.i("test","delete"); sqLiteDatabase.delete("person",selection,selectionArgs); return 0; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { Log.i("test","update"); sqLiteDatabase.update("person",values,selection,selectionArgs); return 0; }
内容访问者:
添加数据public void add(View view){ String name=t_main_name.getText().toString();//获取EditText中name的值 String age=et_main_age.getText().toString(); //获取EditText中age的值 uri = Uri.parse("content://com.example.android_16_sqlite.PERSONS");// //保存到数据库中 ContentValues values=new ContentValues();//Map values.put("name",name); values.put("age",age); values.putNull("_id"); cr.insert(uri,values); }
查询所有数据
public void getDate(View view){ //查询所有 //协议:content:// uri = Uri.parse("content://com.example.android_16_sqlite.PERSONS"); //查询数据 cursor = cr.query(uri,null,null,null,null); while (cursor.moveToNext()){ int pid= cursor.getInt(cursor.getColumnIndex("_id")); String sname= cursor.getString(cursor.getColumnIndex("name")); int age= cursor.getInt(cursor.getColumnIndex("age")); } PersonDate();}
修改数据public void update(View view){ String id=editText.getText().toString(); String name=t_main_name.getText().toString(); String age=et_main_age.getText().toString(); uri = Uri.parse("content://com.example.android_16_sqlite.PERSONS"); //要修改的值保存到数据库中 ContentValues values=new ContentValues();//Map values.put("name",name); values.put("age",age); cr.update(uri,values,"_id=?",new String[]{id+""}); }删除数据public void delete(View view){ String id=editText.getText().toString(); uri = Uri.parse("content://com.example.android_16_sqlite.PERSONS"); cr.delete(uri,"_id=?",new String[]{id+""}); }
自定义ContentProvider的简单增删除改
最新推荐文章于 2022-09-26 20:45:00 发布