刚开始学习ContentProvider时是学的系统的ContentProvider,没碰到什么问题,但是在学习自定义ContentProvider的实现时,唉,碰到好几个问题,花了我好多时间。
我碰到的问题:
1. java.lang.IllegalArgumentException: column '_id' does not exist
解决方法:创建数据表时插入一个名为_id的列,类型为自增量,因为在使用Cursor相关的Adapter时需要用到这个列
2.Failed to find provider for user 0 ; expected to find a valid ContentProvider for
解决方法:在第一个应用的AndroidManifest.xml中添加如下代码
但是当我使用API 30时却还是会报错,报空指针异常,到现在还没解决,真的菜啊,所以为了让程序运行起来,我就选择API 29 ,就能正常运行了
3.注意:在数据库类里写sql语句时,最容易出错,比如少了空格拼接起来就是错误的sql语句,英文逗号写成中文逗号,进行增删改查时表名,列名要写正确
4.Uri里的authorities也非常容易搞错,搞错了就会报 uri 找不到异常
5.还有很多小问题就不一一描述了,细心认真点,相信你们自己能解决
为了让你们(新手,包括我自己)能正确的运行起我的程序来,我把所有类,布局文件和配置信息都贴出来。如果你去看别人写的自定义ContentProvider的实现,你会发现有这几个问题,不敢说全部,大多数是这样,自定义ContentProvider的实现本来就是面向新手的,所以把信息都写全来才好去学习和模仿加创新。
1.缺少布局文件,对于我这种小白来说真的就离谱,id都不知道哪个是哪个
2.缺少一些类,不如数据库类。
3.只贴出一些重要代码片段来,对于小白来说,的确不好搞
4.缺少配置信息,这只能看看,要想模仿就难了,一大堆BUG等着你
5.完整的源码要VIP或者收费
项目里的代码详解我就不说了,大多数都有解释,实在不懂的,可以自行百度,肯定比我在这说的清楚详细易懂,我这篇给文章主要还是让各位实现自定义ContentProvider,能跑起来
先来看看我效果
20211021
序号:1 姓名:小明 工作:Android Development
然后我在输入框中输入,只要序号是1,不管姓名和工作输的是什么,都会将
序号:1 姓名:小明 工作:Android Development 这条记录删除。
(感兴趣的可以自己去改改)
首先看一下我的项目结构,你就知道要写哪些类和布局文件了
模块gamedemo是第一个应用
MainActivity代码如下
import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements View.onClickListener { private static final String TAG = "lzs"; private DbHelp dbHelp; private SQLiteDatabase db; private TextView userTv; private Button btn_query; private Button btn_insert; private Button btn_delete; private Button btn_update; private int m=2; private int n=3; private EditText xuhao; private EditText xingming; private EditText zhiye; private int id; private String name; private String job; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.dbHelp = new DbHelp(this); //创建数据库 this.db = this.dbHelp.getWritableDatabase(); init(); //初始化控件 } private void init() { btn_query = findViewById(R.id.btn_query); btn_insert = findViewById(R.id.btn_insert); btn_delete = findViewById(R.id.btn_delete); btn_update = findViewById(R.id.btn_update); xuhao = findViewById(R.id.xuhao); xingming = findViewById(R.id.xingming); zhiye = findViewById(R.id.zhiye); btn_query.setonClickListener(this); btn_insert.setonClickListener(this); btn_delete.setonClickListener(this); btn_update.setonClickListener(this); } @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { super.onDestroy(); db.close(); dbHelp.close(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_query: btn_query(); break; case R.id.btn_insert: btn_insert(); break; case R.id.btn_delete: btn_delete(); break; case R.id.btn_update: btn_update(); break; } } //查询函数 private void btn_query(){ Cursor user = this.db.query("user", null, null, null, null, null, null); this.userTv = findViewById(R.id.id_user_db); //清空文本,防止重复查询而多次显示 if(!TextUtils.isEmpty(this.userTv.getText())) { this.userTv.setText(""); } while (user.moveTonext()){ String id = user.getString(0); String name = user.getString(1); String jobs = user.getString(2); this.userTv.append("序号:"+id+" 姓名:"+name+" 工作:"+jobs+"n"); } } //插入函数(没有用SQL语句,用的是Android的方式) private void btn_insert(){ if(!TextUtils.isEmpty(xuhao.getText())&&!TextUtils.isEmpty(xingming.getText())&&!TextUtils.isEmpty(zhiye.getText())){ id = Integer.parseInt(xuhao.getText().toString()); name = xingming.getText().toString(); job = zhiye.getText().toString(); Cursor result=db.rawQuery("select * from user where _id = "+id,null); if(!result.isAfterLast()){ Toast.makeText(MainActivity.this,"插入失败,改记录已存在或序号重复!",Toast.LENGTH_SHORT).show(); }else { Uri uri_user = Uri.parse("content://cn.sch.myprovider/user"); // 向user表插入数据 ContentValues values3 = new ContentValues(); values3.put("_id", id); values3.put("name", name); values3.put("jobs", job); // 获取ContentResolver ContentResolver resolver3 = getContentResolver(); // 通过ContentResolver 根据URI 向ContentProvider中插入数据 resolver3.insert(uri_user, values3); Toast.makeText(MainActivity.this,"插入成功",Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(MainActivity.this,"请填写完整,不能为空!",Toast.LENGTH_SHORT).show(); } } //删除函数(利用SQL语句删除,你也可以用Android的方式删除),因为序号是唯一的,所以直接根据提供的序号删除就可以了 private void btn_delete(){ if(!TextUtils.isEmpty(xuhao.getText())){ id = Integer.parseInt(xuhao.getText().toString()); Cursor result=db.rawQuery("select _id from user where _id="+id,null); if(!result.isAfterLast()){ db.execSQL("delete from user where _id="+id); Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this,"删除失败,没有该条记录!",Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(MainActivity.this,"请填写完整,不能为空!",Toast.LENGTH_SHORT).show(); } } //更新函数(利用SQL语句更新,你也可以用Android的方式更新),因为序号唯一,所以直接根据输入的序号更改就可以了 private void btn_update(){ if(!TextUtils.isEmpty(xuhao.getText())&&!TextUtils.isEmpty(xingming.getText())&&!TextUtils.isEmpty(zhiye.getText())){ id = Integer.parseInt(xuhao.getText().toString()); name = xingming.getText().toString(); job = zhiye.getText().toString(); Cursor result=db.rawQuery("select * from user where _id="+id,null); if(!result.isAfterLast()){ db.execSQL("update user set _id="+id +" where _id="+id); db.execSQL("update user set name='"+name +"' where _id="+id);//注意是 set='name' 如果不清楚可以再去看看数据库的知识 db.execSQL("update user set jobs='"+job +"' where _id="+id); Toast.makeText(MainActivity.this,"更新成功",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this,"更新失败,改记录不存在!",Toast.LENGTH_SHORT).show(); } }else { Toast.makeText(MainActivity.this,"请填写完整,不能为空!",Toast.LENGTH_SHORT).show(); } } }
MainActivity的布局文件activity_main.xml 代码如下
MyProvide代码如下
import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; public class MyProvide extends ContentProvider { private Context mContext; private DbHelp dbHelp = null; private SQLiteDatabase db = null; public static final String AUTHORITY = "cn.sch.myprovider"; public static final int User_Code = 1; private UriMatcher mMatcher; @Override public boolean onCreate() { mContext = getContext(); mMatcher = new UriMatcher(UriMatcher.NO_MATCH); //初始化 // 若URI资源路径 = content://cn.sch.myprovider/user ,则返回注册码User_Code mMatcher.addURI(AUTHORITY, "user", User_Code); dbHelp = new DbHelp(mContext); this.db = dbHelp.getWritableDatabase(); // 初始化表的数据 db.execSQL("delete from user"); db.execSQL("insert into user values(1,'xiaoming','Android Development')"); db.execSQL("insert into user values(2,'xiaohua','Java Development')"); return true; } @Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String tableName = getTableName(uri); return db.query(tableName,projection,selection,selectionArgs,null,null,sortOrder,null); } @Override public String getType( Uri uri) { return null; } @Override public Uri insert( Uri uri, ContentValues values) { String tableName = getTableName(uri); //向表中插入数据 db.insert(tableName,null,values); mContext.getContentResolver().notifyChange(uri,null); return uri; } @Override public int delete( Uri uri, String selection, String[] selectionArgs) { String tableName = getTableName(uri); int count=db.delete(tableName, null, null); if(count>0){ getContext().getContentResolver().notifyChange(uri, null); return count; } return 0; } @Override public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs) { String tableName = getTableName(uri); int count = db.update(tableName, values, selection,selectionArgs); if(count>0){ getContext().getContentResolver().notifyChange(uri, null); return count; } return 0; } private String getTableName(Uri uri) { String tableName = null; switch (mMatcher.match(uri)){ case User_Code: tableName = DbHelp.USER_TABLE_NAME; break; } return tableName; } }
DbHelp代码如下
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DbHelp extends SQLiteOpenHelper { // 数据库名 private static final String DATAbase_NAME = "finch.db"; // 表名 public static final String USER_TABLE_NAME = "user"; //数据库版本号 private static final int DATAbase_VERSION = 1; public DbHelp(Context context) { super(context, DATAbase_NAME, null, DATAbase_VERSION); } @Override public void onCreate(SQLiteDatabase db) { //创建数据库表 //注意;如果你第一次运行后第二次又改动创建数据语句时,并且只改动了属性,没有该表名,那么当你再次运行App时会发现会报错,新改动的属性不存在 //解决方法:手动将已建好的那个表删除,或者删除App重新安装,这样你改动的属性才能生效 db.execSQL("CREATE TABLE IF NOT EXISTS "+USER_TABLE_NAME+"(_id INTEGER PRIMARY KEY AUTOINCREMENT,"+" name TEXT,"+"jobs TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
第一个应用的AndroidManifest.xml
第一个应用的build.gradle
plugins { id 'com.android.application' } android { compileSdk 29 defaultConfig { applicationId "com.example.gamedemo" minSdk 21 targetSdk 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' }
模块contentprovidertest是第二个应用
MainActivity代码如下
package com.example.contentprovidertest; import android.Manifest; import android.content.ContentResolver; import android.content.ContentValues; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; public class MainActivity extends AppCompatActivity implements View.onClickListener { private static final String TAG = "lzs"; private TextView userTv; private Button btn_query2; private Button btn_insert2; private Button btn_delete2; private Button btn_update2; private EditText xuhao2; private EditText xingming2; private EditText zhiye2; private int id; private String name; private String job; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.userTv = findViewById(R.id.id_tv); //动态获取权限 if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED ||ActivityCompat.checkSelfPermission (this, Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED) { init(); //初始化控件 }else { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},0x10); } } private void init() { xuhao2 = findViewById(R.id.xuhao2); xingming2 = findViewById(R.id.xingming2); zhiye2 = findViewById(R.id.zhiye2); btn_query2 = findViewById(R.id.btn_query2); btn_insert2 = findViewById(R.id.btn_insert2); btn_delete2 = findViewById(R.id.btn_delete2); btn_update2 = findViewById(R.id.btn_update2); btn_query2.setonClickListener(this); btn_insert2.setonClickListener(this); btn_delete2.setonClickListener(this); btn_update2.setonClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_query2: btn_query2(); break; case R.id.btn_insert2: btn_insert2(); break; case R.id.btn_delete2: btn_delete2(); break; case R.id.btn_update2: btn_update2(); break; } } private void btn_update2() { id = Integer.parseInt(xuhao2.getText().toString()); name = xingming2.getText().toString(); job = zhiye2.getText().toString(); if(!TextUtils.isEmpty(xuhao2.getText())&&!TextUtils.isEmpty(xingming2.getText())&&!TextUtils.isEmpty(zhiye2.getText())){ Uri uri = Uri.parse("content://cn.sch.myprovider/user"); ContentResolver resolver2 = getContentResolver(); ContentValues values2 = new ContentValues(); values2.put("_id", id); values2.put("name", name); values2.put("jobs", job); resolver2.update(uri,values2,"_id="+id,null); Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this,"请填写完整,不能为空!",Toast.LENGTH_SHORT).show(); } } private void btn_delete2() { id = Integer.parseInt(xuhao2.getText().toString()); if(!TextUtils.isEmpty(xuhao2.getText())){ Uri uri = Uri.parse("content://cn.sch.myprovider/user"); ContentResolver resolver2 = getContentResolver(); resolver2.delete(uri,"_id ="+id,null); Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show(); }else { Toast.makeText(MainActivity.this,"请填写完整,不能为空!",Toast.LENGTH_SHORT).show(); } } private void btn_insert2() { this.userTv.setText(""); id = Integer.parseInt(xuhao2.getText().toString()); name = xingming2.getText().toString(); job = zhiye2.getText().toString(); if(!TextUtils.isEmpty(xuhao2.getText())&&!TextUtils.isEmpty(xingming2.getText())&&!TextUtils.isEmpty(zhiye2.getText())){ Uri uri = Uri.parse("content://cn.sch.myprovider/user"); // 插入表中数据 ContentValues values2 = new ContentValues(); values2.put("_id", id); values2.put("name", name); values2.put("jobs", job); // 获取ContentResolver ContentResolver resolver2 = getContentResolver(); // 通过ContentResolver 根据URI 向ContentProvider中插入数据 resolver2.insert(uri, values2); // 通过ContentResolver 向ContentProvider中查询数据 Cursor cursor2 = resolver2.query(uri, new String[]{"_id", "name","jobs"}, null, null, null); while (cursor2.moveTonext()) { // 将表中数据全部输出 this.userTv.append(" 序号:" + cursor2.getInt(0) + " 姓名:" + cursor2.getString(1) +" 工作:"+cursor2.getString(2)+ "n"); } Toast.makeText(MainActivity.this,"插入成功",Toast.LENGTH_SHORT).show(); // 关闭游标 cursor2.close(); }else { Toast.makeText(MainActivity.this,"请填写完整,不能为空!",Toast.LENGTH_SHORT).show(); } } private void btn_query2() { Uri uri = Uri.parse("content://cn.sch.myprovider/user"); Cursor query = getContentResolver().query(uri, null, null, null, null); //清空文本,防止重复查询而多次显示 if(!TextUtils.isEmpty(this.userTv.getText())) { this.userTv.setText(""); } while (query.moveTonext()) { int id = query.getInt(0); String name = query.getString(1); String job = query.getString(2); this.userTv.append(" 序号:" + id + " 姓名:" + name +" 工作:"+job+ "n"); } query.close(); } }
MainActivity的activity_main.xml代码如下
第二个应用的AndroidManifest.xml
第二个应用的build.gradle
plugins { id 'com.android.application' } android { compileSdk 29 defaultConfig { applicationId "com.example.contentprovidertest" minSdk 21 targetSdk 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' }
如果又遇到啥问题,可以留言,一起来解决。
到此所有代码展示完毕,希望你们喜欢,觉得不错的可以给我个赞哈,嘿嘿。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)