执行代码必须要数据库有值才能体现出来:
新建一个类 继承contentprovider 重写方法(主要讲解query方法 其他方法步骤一样);
当数据库有值的时候调用query方法
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
Log.i("test","query");
DbHelper dbHelper= new DbHelper(getContext(),"data.db",null,1);
database = dbHelper.getWritableDatabase();
// Cursor cursor=database.rawQuery("select * from data",null);
return database.rawQuery("select * from data",null);
}
配置文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="包名"><application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> ... <provider android:authorities="包名..." android:name="新建类的包名加类名" android:exported="true"></provider> ... </application>
另外一个Module内:
就可实现对其他Module的访问package com.example.g160628_android_25_contentprovider01; import android.content.ContentProvider; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { private ContentResolver cr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取第16次课的数据 cr = getContentResolver(); Uri uri=Uri.parse("content://com.example.g160628_android_16_sqlite.demp"); Cursor cursor= cr.query(uri,null,null,null,null); Log.i("test","cursor: "+cursor.moveToNext()); while (cursor.moveToNext()){ String user=cursor.getString(cursor.getColumnIndex("name")); String pass=cursor.getString(cursor.getColumnIndex("pass")); Log.i("test","账号:"+user+" 密码:"+pass); } } }