在数据库的项目中新建一个类:
package com.zking.administrator.g160618_android16_sqlite; import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.zking.db.DBHelper; /** * Created by Administrator on 2017/7/17 0017. */ public class MyProvider extends ContentProvider { @Override public boolean onCreate() { Log.i("test","onCreate"); return false; } @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(),"G160618.db",null,2); SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase(); //sqLiteDatabase.rawQuery("select * from login",null); return sqLiteDatabase.rawQuery("select * from login",null); } @Nullable @Override public String getType(@NonNull Uri uri) { Log.i("test","getType"); return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) { Log.i("test","insert"); return null; } @Override public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) { Log.i("test","delete"); return 0; } @Override public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) { Log.i("test","update"); return 0; } }项目配置:
<!--配置内容提供者--> <provider android:authorities="com.zking.administrator.g160618_android16_sqlite.bte" android:name=".MyProvider" android:exported="true" ></provider>想要获取的数据库的项目:
ContentResolver contentProvider=getContentResolver(); Uri uri=Uri.parse("content://com.zking.administrator.g160618_android16_sqlite.bte"); Cursor cursor=contentProvider.query(uri,null,null,null,null); while(cursor.moveToNext()){ //通过列名获取数据库数据 int uid=cursor.getInt(cursor.getColumnIndex("uid")); String uname=cursor.getString(cursor.getColumnIndex("uname")) ; String upass=cursor.getString(cursor.getColumnIndex("upass")) ; Log.i("test",uid+" "+uname+" "+upass); }