Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android中數據存儲的contentprovider的使用方法

android中數據存儲的contentprovider的使用方法

編輯:關於Android編程

元數據接口   package com.example.contentproviderprojecrt; import android.net.Uri; import android.provider.BaseColumns; public interface MLDNbatabaseMetaData { //外部訪問,content地址://com.example.contentproviderproject public  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); } @Override public 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語句 } @Override public 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);  //實例化UriMatcher uriMatcher.addURI(MLDNbatabaseMetaData.AUTHORITY,  MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME, GET_MEMBER_LIST);//增加匹配項 uriMatcher.addURI(MLDNbatabaseMetaData.AUTHORITY, MLDNbatabaseMetaData.MemberTableMetaData.TABLE_NAME+"/#", GET_MEMBER_ITEM);//增加匹配項 } //刪除數據操作 @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db=this.helper.getWritableDatabase(); //以寫的方式打開 int result=0;//操作結果 switch(uriMatcher.match(uri)){//匹配傳入的Uri case 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; } @Override public String getType(Uri uri) { switch(uriMatcher.match(uri)){//匹配傳入的Uri case 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);//拋出異常 } } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db=this.helper.getWritableDatabase();//以寫的方式打開 long id=0;   //增加之後的ID switch(uriMatcher.match(uri)){//匹配傳入的Uri case 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); } } @Override public boolean onCreate() { this.helper=new MyDatabaseHelper(super.getContext());  //實例化DatabaseHelper return true;  //操作成功 } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db=this.helper.getReadableDatabase();//以讀的方式打開 switch(uriMatcher.match(uri)){   //匹配傳入的Uri case 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); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db=this.helper.getWritableDatabase();//以寫的方式打開 int result=0;   //操作結果 switch(uriMatcher.match(uri)){//匹配傳入的Uri case 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; @Override protected 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{//查詢按鈕事件 @Override public void onClick(View v) { Cursor result=MainActivity.this.textQuery(null);//查詢的結果集 List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();//用於設置SimpleAdapter for(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{//刪除按鈕事件 @Override public 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{//更新按鈕事件 @Override public 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{//增加按鈕事件 @Override public void onClick(View v) { long id=0;//保存接受ID id=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;//定義ContentResolver contentSesolver=super.getContentResolver();//取得contentSesolver ContentValues 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; //定義ContentResolver contentSesolver=super.getContentResolver();//取得contentSesolver ContentValues 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; } @Override public 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>    
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved