1. 程式人生 > >Android組件系列----ContentProvider內容提供者【2】

Android組件系列----ContentProvider內容提供者【2】

resolv blank lan int 復制 pad otto rtp wrap

二、代碼舉例:

終於全部project文件的文件夾結構例如以下:

技術分享

PersonDao是增刪改查數據庫的工具類,並在PersonContentProvider中得到調用。DBHelper用於初始化SQLite數據庫。

PersonContentProvider用於向外提供增刪改查的接口。並終於在ContentResolverTest的Test.java中進行單元測試,實現CRUD。

以下來看一下詳細的實現步驟。

新建project文件ContetProviderTest01。

(1)新建類PersonDao:用於進行對SQLite的CRUD操作。代碼例如以下:

PersonDao.java:

技術分享
 1 package com.example.contentprovidertest01.dao;
 2 
 3 import android.content.ContentValues;
 4 import android.content.Context;
 5 import android.database.Cursor;
 6 import android.database.sqlite.SQLiteDatabase;
 7 
 8 import com.example.contentprovidertest01.db.DBHelper;
 9 
10 public class PersonDao {
11 private DBHelper helper = null; 12 13 public PersonDao(Context context) { 14 helper = new DBHelper(context); 15 } 16 17 //方法:插入操作,返回的long類型為:插入當前行的行號 18 public long insertPerson(ContentValues values) { 19 long id = -1; 20 SQLiteDatabase database = null;
21 try { 22 database = helper.getWritableDatabase(); 23 id = database.insert("person", null, values); 24 } catch (Exception e) { 25 e.printStackTrace(); 26 } finally { 27 if (database != null) { 28 database.close(); 29 } 30 } 31 return id; 32 } 33 34 public int deletePerson(String whereClause, String[] whereArgs) { 35 int count = -1; 36 SQLiteDatabase database = null; 37 try { 38 database = helper.getWritableDatabase(); 39 count = database.delete("person", whereClause, whereArgs); 40 } catch (Exception e) { 41 e.printStackTrace(); 42 } finally { 43 if (database != null) { 44 database.close(); 45 } 46 } 47 return count; 48 } 49 50 public int updatePerson(ContentValues values, String whereClause, 51 String[] whereArgs) { 52 SQLiteDatabase database = null; 53 int count = -1; 54 try { 55 database = helper.getWritableDatabase(); 56 count = database.update("person", values, whereClause, whereArgs); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } finally { 60 if (null != database) { 61 database.close(); 62 } 63 } 64 return count; 65 } 66 67 public Cursor queryPersons(String selection, String[] selectionArgs) { 68 SQLiteDatabase database = null; 69 Cursor cursor = null; 70 try { 71 database = helper.getReadableDatabase(); 72 cursor = database.query(true, "person", null, selection, 73 selectionArgs, null, null, null, null); 74 } catch (Exception e) { 75 e.printStackTrace(); 76 } finally { 77 if (null != database) { 78 // database.close(); 79 } 80 } 81 return cursor; 82 } 83 84 }
技術分享

Android組件系列----ContentProvider內容提供者【2】