赞
踩
/***************************MainActivity**********************************************/
package com.cs.dxm.contentprovidertest; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); // 设置URI Uri uri_user = Uri.parse("content://com.cs.dxm.contentprovidertest/user"); // 插入表中数据 ContentValues values = new ContentValues(); values.put("_id", 4); values.put("name", "zzl"); // 获取ContentResolver ContentResolver resolver = getContentResolver(); // 通过ContentResolver 根据URI 向ContentProvider中插入数据 resolver.insert(uri_user,values); // 通过ContentResolver 向ContentProvider中查询数据 Cursor cursor = resolver.query(uri_user, new String[]{"_id","name"}, null, null, null); while (cursor.moveToNext()){ System.out.println("query book:" + cursor.getInt(0) +" "+ cursor.getString(1)); // 将表中数据全部输出 } cursor.close(); // 关闭游标 /** * 对job表进行操作 */ // 和上述类似,只是URI需要更改,从而匹配不同的URI CODE,从而找到不同的数据资源 Uri uri_job = Uri.parse("content://com.cs.dxm.contentprovidertest/job"); // 插入表中数据 ContentValues values2 = new ContentValues(); values2.put("_id", 4); values2.put("job", "LOL Player"); // 获取ContentResolver ContentResolver resolver2 = getContentResolver(); // 通过ContentResolver 根据URI 向ContentProvider中插入数据 resolver2.insert(uri_job,values2); // 通过ContentResolver 向ContentProvider中查询数据 Cursor cursor2 = resolver2.query(uri_job, new String[]{"_id","job"}, null, null, null); while (cursor2.moveToNext()){ System.out.println("query job:" + cursor2.getInt(0) +" "+ cursor2.getString(1)); // 将表中数据全部输出 } cursor2.close(); // 关闭游标 } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
/*****************************MyProvider **************************************/
package com.cs.dxm.contentprovidertest; 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 MyProvider extends ContentProvider { private Context mContext; DBHelper mDbHelper = null; SQLiteDatabase db = null; public static final String AUTOHORITY = "com.cs.dxm.contentprovidertest"; // 设置ContentProvider的唯一标识 public static final int User_Code = 1; public static final int Job_Code = 2; // UriMatcher类使用:在ContentProvider 中注册URI private static final UriMatcher mMatcher; static{ mMatcher = new UriMatcher(UriMatcher.NO_MATCH); // 初始化 mMatcher.addURI(AUTOHORITY,"user", User_Code); mMatcher.addURI(AUTOHORITY, "job", Job_Code); // 若URI资源路径 = content://cn.scu.myprovider/user ,则返回注册码User_Code // 若URI资源路径 = content://cn.scu.myprovider/job ,则返回注册码Job_Code } @Override public boolean onCreate() { mContext = getContext(); // 在ContentProvider创建时对数据库进行初始化 // 运行在主线程,故不能做耗时操作,此处仅作展示 mDbHelper = new DBHelper(getContext()); db = mDbHelper.getWritableDatabase(); // 初始化两个表的数据(先清空两个表,再各加入一个记录) db.execSQL("delete from user"); db.execSQL("insert into user values(1,'Carson');"); db.execSQL("insert into user values(2,'Kobe');"); db.execSQL("delete from job"); db.execSQL("insert into job values(1,'Android');"); db.execSQL("insert into job values(2,'iOS');"); return true; } @Override public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) { // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名 // 该方法在最下面 String table = getTableName(uri); // // 通过ContentUris类从URL中获取ID // long personid = ContentUris.parseId(uri); // System.out.println(personid); // 查询数据 return db.query(table,projection,selection,selectionArgs,null,null,sortOrder,null); } @Override public String getType(Uri uri) { return null; } @Override public Uri insert(Uri uri,ContentValues values) { // 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名 // 该方法在最下面 String table = getTableName(uri); // 向该表添加数据 db.insert(table, null, values); // 当该URI的ContentProvider数据发生变化时,通知外界(即访问该ContentProvider数据的访问者) mContext.getContentResolver().notifyChange(uri, null); // // 通过ContentUris类从URL中获取ID // long personid = ContentUris.parseId(uri); // System.out.println(personid); return uri; } @Override public int delete(Uri uri,String selection,String[] selectionArgs) { return 0; } @Override public int update(Uri uri,ContentValues values,String selection,String[] selectionArgs) { return 0; } /** * 根据URI匹配 URI_CODE,从而匹配ContentProvider中相应的表名 */ private String getTableName(Uri uri){ String tableName = null; switch (mMatcher.match(uri)) { case User_Code: tableName = DBHelper.USER_TABLE_NAME; break; case Job_Code: tableName = DBHelper.JOB_TABLE_NAME; break; } return tableName; } }
/***********************DBHelper ********************************/
package com.cs.dxm.contentprovidertest; import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context,String name,SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } public DBHelper(Context context,String name,SQLiteDatabase.CursorFactory factory, int version,DatabaseErrorHandler errorHandler) { super(context, name, factory, version, errorHandler); } // public DBHelper(Context context,String name, int version,SQLiteDatabase.OpenParams openParams) { // super(context, name, version, openParams); // } // 数据库名 private static final String DATABASE_NAME = "finch.db"; // 表名 public static final String USER_TABLE_NAME = "user"; public static final String JOB_TABLE_NAME = "job"; private static final int DATABASE_VERSION = 1; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + USER_TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + " name TEXT)"); db.execSQL("CREATE TABLE IF NOT EXISTS " + JOB_TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT," + " job TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
/*****************************AndroidManifest.xml*****************************************/
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cs.dxm.contentprovidertest"> <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" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:exported="true" android:authorities="com.cs.dxm.contentprovidertest" android:name=".MyProvider"/> </application> </manifest>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。