android中資料存放區的contentprovider的使用方法

來源:互聯網
上載者:User

中繼資料介面 package com.example.contentproviderprojecrt;import android.net.Uri;import android.provider.BaseColumns;public interface MLDNbatabaseMetaData {//外部存取,content地址://com.example.contentproviderprojectpublic  static final String AUTHORITY="com.example.contentproviderproject";//資料庫的名稱public static final String DATABASE_NAME="mldn.db";//資料庫的版本public static final int VERSION=1;//member表的元素定義,直接繼承與_ID和_COUNT靜態變數public static interface MemberTableMetaData extends BaseColumns{//資料表的名稱public static final String TABLE_NAME="member";//外部存取的URI地址public static final Uri CONTENT_URI=Uri.parse("content://"+AUTHORITY+"/"+TABLE_NAME);//取得member表中的所有資料public static final String CONTACT_LIST="vnd.android.cursor.dir/vnd.contentproviderproject.member";//取得一個member資訊public static final String CONTACT_ITEM="vnd.android.cursor.item/vnd.contentproviderproject.member";//欄位名稱public static final String MEMBER_NAME="name";public static final String MEMBER_AGE="age";public static final String MEMBER_BIRTHDAY="birthday";//顯示時候的排序欄位public static final String SORT_ORDER="_id DESC";}} 定義資料庫操作類助手 package com.example.contentproviderprojecrt;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;public class MyDatabaseHelper extends SQLiteOpenHelper {public MyDatabaseHelper(Context context) {//建立資料庫super(context, MLDNbatabaseMetaData.DATABASE_NAME, null, MLDNbatabaseMetaData.VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {// 建立表String sql="CREATE TABLE "+MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME+" ("+MLDNbatabaseMetaData.MemberTableMetaData._ID+" INTEGER  PRIMARY KEY,"+MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_NAME+" VARCHAR(50)  NOT NULL,"+MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_AGE+"  INTEGER  NOT NULL,"+MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY+"   DATE   NOT NULL"+")";db.execSQL(sql);//執行SQL語句}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//更新表String sql="DROP TABLE IF EXISTS "+MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME;db.execSQL(sql);//執行SQL語句this.onCreate(db);//更新資料庫}}  定義表操作contentProvider類 package com.example.contentproviderprojecrt;import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.content.UriMatcher;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.net.Uri;public class MemberContentProvider extends ContentProvider {private static UriMatcher uriMatcher=null;   //定義UriMatcher對象private static final int GET_MEMBER_LIST=1;   //查詢全部的常量標記private static final int GET_MEMBER_ITEM=2;   //根據ID查詢的常量標記private MyDatabaseHelper helper=null;      //資料庫操作類對象static{uriMatcher=new UriMatcher(uriMatcher.NO_MATCH);  //執行個體化UriMatcheruriMatcher.addURI(MLDNbatabaseMetaData.AUTHORITY, MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, GET_MEMBER_LIST);//增加匹配項uriMatcher.addURI(MLDNbatabaseMetaData.AUTHORITY,MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME+"/#", GET_MEMBER_ITEM);//增加匹配項}//刪除資料操作@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs) {SQLiteDatabase db=this.helper.getWritableDatabase(); //以寫的方式開啟int result=0;//操作結果switch(uriMatcher.match(uri)){//匹配傳入的Uricase GET_MEMBER_LIST:result=db.delete(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, selection, selectionArgs);break;case GET_MEMBER_ITEM:long id=ContentUris.parseId(uri);String where="_id="+id;result=db.delete(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, where, selectionArgs);break;default:throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);}return result;}@Overridepublic String getType(Uri uri) {switch(uriMatcher.match(uri)){//匹配傳入的Uricase GET_MEMBER_LIST:return MLDNbatabaseMetaData.MemberTableMetaData.CONTACT_LIST;case GET_MEMBER_ITEM:return MLDNbatabaseMetaData.MemberTableMetaData.CONTACT_ITEM;default:throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);//拋出異常}}@Overridepublic Uri insert(Uri uri, ContentValues values) {SQLiteDatabase db=this.helper.getWritableDatabase();//以寫的方式開啟long id=0;   //增加之後的IDswitch(uriMatcher.match(uri)){//匹配傳入的Uricase GET_MEMBER_LIST:id=db.insert(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME,MLDNbatabaseMetaData.MemberTableMetaData._ID, values);String uriPath=uri.toString();//取出地址String path=uriPath+"/"+id;   //建立新的URI地址return Uri.parse(path);case GET_MEMBER_ITEM:return null;default:throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);}}@Overridepublic boolean onCreate() {this.helper=new MyDatabaseHelper(super.getContext());  //執行個體化DatabaseHelperreturn true;  //操作成功}@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {SQLiteDatabase db=this.helper.getReadableDatabase();//以讀的方式開啟switch(uriMatcher.match(uri)){   //匹配傳入的Uricase GET_MEMBER_LIST:return db.query(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME,projection, selection, selectionArgs, null, null, sortOrder);case GET_MEMBER_ITEM:long id=ContentUris.parseId(uri);String where="_id="+id;return db.query(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, projection, where, selectionArgs, null, null, sortOrder);default:throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);}}@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {SQLiteDatabase db=this.helper.getWritableDatabase();//以寫的方式開啟int result=0;   //操作結果switch(uriMatcher.match(uri)){//匹配傳入的Uricase GET_MEMBER_LIST:result=db.update(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, values, null, null);break;case GET_MEMBER_ITEM:long id=ContentUris.parseId(uri);String where="_id="+id;result=db.update(MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, values, where, selectionArgs);break;default:throw new UnsupportedOperationException("NOT SUPPORT OPERATION "+uri);}return result;}}  Acitivity程式 package com.example.contentproviderprojecrt;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import android.net.Uri;import android.os.Bundle;import android.app.Activity;import android.content.ContentResolver;import android.content.ContentUris;import android.content.ContentValues;import android.database.Cursor;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;public class MainActivity extends Activity {private Button insertBut=null;    private Button updateBut=null;    private Button deleteBut=null;    private Button queryBut=null;    private ListView memberList=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);super.setContentView(R.layout.activity_main);this.insertBut=(Button)super.findViewById(R.id.insertBut);//擷取按鈕this.insertBut.setOnClickListener(new InsertOnClickListener());//設定按鈕單擊事件this.updateBut=(Button)super.findViewById(R.id.updateBut);//擷取按鈕this.updateBut.setOnClickListener(new UpdateOnClickListener());//設定按鈕單擊事件this.deleteBut=(Button)super.findViewById(R.id.deleteBut);//擷取按鈕this.deleteBut.setOnClickListener(new DeleteOnClickListener());//設定按鈕單擊事件this.queryBut=(Button)super.findViewById(R.id.queryBut);//擷取按鈕this.queryBut.setOnClickListener(new QueryOnClickListener());//設定按鈕單擊事件this.memberList=(ListView)super.findViewById(R.id.memberList);//擷取ListView}private class QueryOnClickListener implements OnClickListener{//查詢按鈕事件@Overridepublic void onClick(View v) {Cursor result=MainActivity.this.textQuery(null);//查詢的結果集List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();//用於設定SimpleAdapterfor(result.moveToFirst();!result.isAfterLast();result.moveToNext()){//迴圈取出資料Map<String,Object> map=new HashMap<String, Object>();map.put("_id", result.getInt(0));map.put("name", result.getString(1));map.put("age", result.getInt(2));map.put("birthday", result.getString(3));list.add(map);  //儲存取出的資料}   MainActivity.this.memberList.setAdapter(new SimpleAdapter(    MainActivity.this, //將資料封裝    list, //資料集合    R.layout.member,//顯示的布局檔案    new String[]{"_id","name","age","birthday"}, //匹配的Map  key    new int[]{R.id._id,R.id.name,R.id.age,R.id.birthday})); //布局檔案裡面對應的ID}}private class DeleteOnClickListener implements OnClickListener{//刪除按鈕事件@Overridepublic void onClick(View v) {long result=0;//返回刪除了多少條資料result=MainActivity.this.textDelete(String.valueOf(2));Toast.makeText(MainActivity.this, "result="+result, Toast.LENGTH_LONG).show();}}private class UpdateOnClickListener implements OnClickListener{//更新按鈕事件@Overridepublic void onClick(View v) {long result=0;//返回更新了多少條資料result=MainActivity.this.textUpdate("1", "李元靜", 18, "1998-01-01");Toast.makeText(MainActivity.this, "result="+result, Toast.LENGTH_LONG).show();}}private class InsertOnClickListener implements OnClickListener{//增加按鈕事件@Overridepublic void onClick(View v) {long id=0;//儲存接受IDid=MainActivity.this.textInsert("李元靜", 21, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));Toast.makeText(MainActivity.this, "id="+id, Toast.LENGTH_LONG).show();}}private  Cursor textQuery(String _id){if(_id==null || "".equals(_id)){//查詢全部資料return super.getContentResolver().query(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, null, null, null,MLDNbatabaseMetaData.MemberTableMetaData.SORT_ORDER);}else{//查詢指定ID資料return super.getContentResolver().query(Uri.withAppendedPath(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, _id), null, null, null,MLDNbatabaseMetaData.MemberTableMetaData.SORT_ORDER);}}private long textDelete(String _id){ContentResolver contentSesolver=super.getContentResolver();//定義取得ContentResolver對象int result=0;if(_id==null || "".equals(_id)){//刪除全部資料result=contentSesolver.delete(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, null, null);}else{//刪除指定資料result=contentSesolver.delete(Uri.withAppendedPath(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, _id), null, null);}return result;}private long textInsert(String name,int age,String birthday){ContentResolver contentSesolver=null;//定義ContentResolvercontentSesolver=super.getContentResolver();//取得contentSesolverContentValues values=new ContentValues();//設定內容values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_NAME, name);values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_AGE, age);values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY, birthday);Uri resultUri=contentSesolver.insert(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, values);return ContentUris.parseId(resultUri);//解析ID返回}private long textUpdate(String _id,String name,int age,String birthday){long result=0;ContentResolver contentSesolver=null; //定義ContentResolvercontentSesolver=super.getContentResolver();//取得contentSesolverContentValues values=new ContentValues();//設定內容values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_NAME, name);values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_AGE, age);values.put(MLDNbatabaseMetaData.MemberTableMetaData.MEMBER_BIRTHDAY, birthday);if(_id==null || "".equals(_id)){//更新全部result=contentSesolver.update(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, values, null, null);}else{//更新制定資料result=contentSesolver.update(Uri.withAppendedPath(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI,_id), values, null, null);}Uri resultUri=contentSesolver.insert(MLDNbatabaseMetaData.MemberTableMetaData.CONTENT_URI, values);return result;}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}  Layout:activity_mail.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >    <LinearLayout   android:orientation="horizontal"   android:layout_width="fill_parent"   android:layout_height="wrap_content" >   <Button       android:id="@+id/insertBut"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:text="添加資料"/>   <Button       android:id="@+id/updateBut"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:text="修改資料"/>   <Button       android:id="@+id/deleteBut"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:text="刪除資料"/>   <Button       android:id="@+id/queryBut"       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:text="查詢資料"/></LinearLayout><ListView    android:id="@+id/memberList"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/></LinearLayout>  member.xml <?xml version="1.0" encoding="utf-8"?><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content" >    <TableRow >        <TextView             android:id="@+id/_id"            android:layout_width="30px"            android:layout_height="wrap_content"/>        <TextView             android:id="@+id/name"            android:layout_width="100px"            android:layout_height="wrap_content"/>        <TextView             android:id="@+id/age"            android:layout_width="30px"            android:layout_height="wrap_content"/>        <TextView             android:id="@+id/birthday"            android:layout_width="150px"            android:layout_height="wrap_content"/>    </TableRow></TableLayout>  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.