【ContentWriter】
package com.jikexueyuan.contentwriter;import android.content.ContentProvider;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.net.Uri;public class Myprovider extends ContentProvider { public static final Uri URI = Uri.parse("content://com.jikexueyuan.cp"); SQLiteDatabase database; @Override public int delete(Uri arg0, String arg1, String[] arg2) { return 0; } @Override public String getType(Uri arg0) { return null; } @Override public Uri insert(Uri arg0, ContentValues arg1) { database.insert("tab", "_id", arg1);// database.close(); return null; } @Override public boolean onCreate() { database = getContext().openOrCreateDatabase("mycp.db3", Context.MODE_PRIVATE, null); database.execSQL("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)"); return true; } @Override public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3, String arg4) { Cursor cursor = database.query("tab", null, null, null, null, null, null); return cursor; } @Override public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) { return 0; }}
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { write(); } }); } public void write() { ContentValues values; values = new ContentValues(); values.put("name", "Java"); getContentResolver().insert(Myprovider.URI, values); values = new ContentValues(); values.put("name", "Swift"); getContentResolver().insert(Myprovider.URI, values); values = new ContentValues(); values.put("name", "Python"); getContentResolver().insert(Myprovider.URI, values); values = new ContentValues(); values.put("name", "C#"); getContentResolver().insert(Myprovider.URI, values); }}
【ContentReader】
public class MainActivity extends Activity { Uri URI = Uri.parse("content://com.jikexueyuan.cp"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Cursor cursor = getContentResolver().query(URI, null, null, null, null); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { String value = cursor.getString(cursor.getColumnIndex("name")); Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show(); cursor.moveToNext(); } }}