撰写DataPersist类代码
// DataPersist.java
// …….
public class DataPersist extends ContentProvider {
private static final String DATABASE_NAME = "StudNewDB";
private static final int DATABASE_VERSION = 2;
private static final String TABLE_NAME = "StudTable";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super( context, DATABASE_NAME, null,
DATABASE_VERSION); }
@Override public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " +TABLE_NAME+" (" +"stud_no"
+ " TEXT," + "stud_name" + " TEXT" + ");");
String sql_1 = "insert into " + TABLE_NAME
+ " (stud_no, stud_name) values('S1001', 'Pam');";
String sql_2 = "insert into " + TABLE_NAME
+ " (stud_no, stud_name) values('S1002', 'Steve');";
String sql_3 = "insert into " + TABLE_NAME
+ " (stud_no, stud_name) values('S1003', 'John');";
try { db.execSQL(sql_1); db.execSQL(sql_2); db.execSQL(sql_3);
} catch (SQLException e) { Log.e("ERROR", e.toString()); }
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
private DatabaseHelper mOpenHelper;
@Override public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
return true; }
@Override public Cursor query(Uri uri, String[] projection,
String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, projection, null, null,
null, null, null);
return c;
}
@Override public String getType(Uri uri) { return null; }
@Override public Uri insert(Uri uri, ContentValues initialValues) {
return uri; }
@Override public int delete(Uri uri, String where, String[] whereArgs) {
return 0; }
@Override public int update(Uri uri, ContentValues values,
String where, String[] whereArgs)
{ return 0; }
}
撰写Activity类代码
// ac01.java
// …….
public class ac01 extends ListActivity {
public static int g_variable;
public static final String AUTHORITY = "com.misoo.provider.rx09-02";
public static final Uri CONTENT_URI =
Uri.parse("content://" + AUTHORITY + "/Student");
private static final String[] PROJECTION
= new String[]{ "stud_no", "stud_name"};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent.getData() == null)
intent.setData(CONTENT_URI);
Cursor cur = getContentResolver().query(getIntent().getData(),
PROJECTION, null, null, null);
ArrayList<Map<String, Object>> coll
= new ArrayList<Map<String, Object>>();
Map<String, Object> item;
cur.moveToFirst();
while (!cur.isAfterLast()) {
item = new HashMap<String, Object>();
item.put("c1", cur.getString(0) + ", " + cur.getString(1));
coll.add(item);
cur.moveToNext();
this.setListAdapter(new SimpleAdapter(this, coll,
android.R.layout.simple_list_item_1,
new String[] { "c1" }, new int[]
{ android.R.id.text1 }));
}
@Override
protected void onListItemClick(ListView l, View v, int position,
long id) { finish();}
}