How to Use contentprovider for data storage in android

Source: Internet
Author: User

Metadata interface package com. example. contentproviderprojecrt; import android.net. uri; import android. provider. baseColumns; public interface MLDNbatabaseMetaData {// external access, content address: // com. example. contentproviderprojectpublic static final String AUTHORITY = "com. example. contentproviderproject "; // database name public static final String DATABASE_NAME =" mldn. db "; // The database VERSION public static final int VERSION = 1; // The Element Definition of the member table, directly inherited with _ ID and _ COUNT static variable public static interface MemberTableMetaData extends BaseColumns {// data table name public static final String TABLE_NAME = "member"; // The URI address for external access public static final Uri CONTENT_URI = Uri. parse ("content: //" + AUTHORITY + "/" + TABLE_NAME); // obtain all data in the member table public static final String CONTACT_LIST = "vnd. android. cursor. dir/vnd. contentproviderproject. member "; // get the public static final String CONTACT_ITEM =" vnd. Android. cursor. item/vnd. contentproviderproject. member "; // field name public static final String MEMBER_NAME =" name "; public static final String MEMBER_AGE =" age "; public static final String MEMBER_BIRTHDAY =" birthday "; // The sort field public static final String SORT_ORDER = "_ id DESC" ;}} displayed defines the database operation assistant 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) {// create a database super (context, MLDNbatabaseMetaData. DATABASE_NAME, null, MLDNbatabaseMetaData. VERSION) ;}@ Overridepublic void onCreate (SQLiteDatabase db) {// CREATE a TABLE String SQL = "CREATE TABLE" + MLDNbatabaseMeta Data. 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" + ")" mongodb.exe cSQL (SQL); // Execute SQL statements} @ Overridepublic void onUpgrade (SQLi TeDatabase db, int oldVersion, int newVersion) {// update TABLE String SQL = "drop table if exists" comment mldnbatabasemetadata.membertablemetadata.table_name1_db.exe cSQL (SQL); // execute the SQL statement this. onCreate (db); // update database} defines the table operation contentProvider class package com. example. contentproviderprojecrt; import android. content. contentProvider; import android. content. contentUris; import android. content. contentValues; import android. content. uriMatc Her; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; import android.net. uri; public class MemberContentProvider extends ContentProvider {private static UriMatcher uriMatcher = null; // defines the UriMatcher object private static final int GET_MEMBER_LIST = 1; // mark all constants in the query as private static final int GET_MEMBER_ITEM = 2; // mark private MyDatabaseHelper helper = null according to the constant in the ID query; // The static {uriMatcher of the database operation class Object = New UriMatcher (uriMatcher. NO_MATCH); // instantiate UriMatcheruriMatcher. addURI (MLDNbatabaseMetaData. AUTHORITY, MLDNbatabaseMetaData. memberTableMetaData. TABLE_NAME, GET_MEMBER_LIST); // Add the matching item uriMatcher. addURI (MLDNbatabaseMetaData. AUTHORITY, MLDNbatabaseMetaData. memberTableMetaData. TABLE_NAME + "/#", GET_MEMBER_ITEM); // Add a match} // delete data operation @ Overridepublic int delete (Uri uri, String selection, String [] selectionArgs) {S QLiteDatabase db = this. helper. getWritableDatabase (); // enable int result = 0 in write mode; // switch (uriMatcher. match (uri) {// match the imported 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, sel EctionArgs); break; default: throw new UnsupportedOperationException ("not support operation" + uri);} return result ;}@ Overridepublic String getType (Uri uri) {switch (uriMatcher. match (uri) {// match the input Uricase GET_MEMBER_LIST: return MLDNbatabaseMetaData. memberTableMetaData. CONTACT_LIST; case GET_MEMBER_ITEM: return MLDNbatabaseMetaData. memberTableMetaData. CONTACT_ITEM; default: throw new UnsupportedOperationExcep Tion ("not support operation" + uri); // throw an exception} @ Overridepublic Uri insert (Uri uri, ContentValues values) {SQLiteDatabase db = this. helper. getWritableDatabase (); // enable long id = 0 in write mode; // The added IDswitch (uriMatcher. match (uri) {// match the imported Uricase GET_MEMBER_LIST: id = db. insert (MLDNbatabaseMetaData. memberTableMetaData. TABLE_NAME, MLDNbatabaseMetaData. memberTableMetaData. _ ID, values); String uriPath = uri. toString (); // retrieves the address S Tring path = uriPath + "/" + id; // create a new URI address, 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 (); // instantiate DatabaseHelperreturn true; // operation successful} @ Overridepublic Cursor query (Uri uri, String [] projection, String selection, String [] selectionArg S, String sortOrder) {SQLiteDatabase db = this. helper. getReadableDatabase (); // open the switch (uriMatcher. match (uri) {// match the input 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. memberTableM EtaData. 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 (); // enable int result = 0 in write mode; // switch (uriMatcher. match (uri) {// match the imported Uricase GET_MEMBER_LIST: r Esult = 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 Program package com. ex Ample. 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; I Mport 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 me MberList = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); super. setContentView (R. layout. activity_main); this. insertBut = (Button) super. findViewById (R. id. insertBut); // obtain the button this. insertBut. setOnClickListener (new InsertOnClickListener (); // click the event this. updateBut = (Button) super. findViewById (R. id. updateBut); // obtain the button this. updateBut. setOnClickListener (new Update OnClickListener (); // click the event this. deleteBut = (Button) super. findViewById (R. id. deleteBut); // obtain the button this. deleteBut. setOnClickListener (new DeleteOnClickListener (); // click the event this. queryBut = (Button) super. findViewById (R. id. queryBut); // obtain the button this. queryBut. setOnClickListener (new QueryOnClickListener (); // click the event this. memberList = (ListView) super. findViewById (R. id. memberList); // get ListView} private class QueryOnClick Listener implements OnClickListener {// query button event @ Overridepublic void onClick (View v) {Cursor result = MainActivity. this. textQuery (null); // query result set List <Map <String, Object> list = new ArrayList <Map <String, Object> (); // set SimpleAdapterfor (result. moveToFirst ();! Result. isAfterLast (); result. moveToNext () {// cyclically retrieve the data 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); // Save the Retrieved Data} MainActivity. this. memberList. setAdapter (new SimpleAdapter (MainActivity. this, // encapsulate the data list, // data set R. layout. member, // display layout file new String [] {"_ id", "name", "age", "birthday"}, // matched Map key new int [] {R. id. _ id, R. id. name, R. id. age, R. id. birthday}); // ID in the layout file} private class DeleteOnClickListener implements OnClickListener {// delete button event @ Overridepublic void onClick (View v) {long result = 0; // return the number of deleted data records. result = MainActivity. this. textDelete (String. valueOf (2); Toast. makeText (MainActivity. this, "result =" + result, Toast. LENGTH_LONG ). show () ;}} priv Ate class UpdateOnClickListener implements OnClickListener {// Update button event @ Overridepublic void onClick (View v) {long result = 0; // return the number of updated data records result = MainActivity. this. textUpdate ("1", "Li yuanjing", 18, "1998-01-01"); Toast. makeText (MainActivity. this, "result =" + result, Toast. LENGTH_LONG ). show () ;}} private class InsertOnClickListener implements OnClickListener {// Add button event @ Overridepublic void onClick (View v) {long id = 0; // save Accept IDid = MainActivity. this. textInsert ("Li yuanjing", 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) {// query all data return super. getContentResolver (). query (MLDNbatabaseMetaData. memberTableMetaData. CONTENT_URI, null, MLDNbatabaseMetaData. memberTableMetaDa Ta. SORT_ORDER);} else {// query the specified ID data return super. getContentResolver (). query (Uri. withAppendedPath (MLDNbatabaseMetaData. memberTableMetaData. CONTENT_URI, _ id), null, MLDNbatabaseMetaData. memberTableMetaData. SORT_ORDER) ;}} private long textDelete (String _ id) {ContentResolver contentSesolver = super. getContentResolver (); // define to obtain the ContentResolver object int result = 0; if (_ id = null | "". equals (_ id) {// delete all data resul T = contentSesolver. delete (MLDNbatabaseMetaData. memberTableMetaData. CONTENT_URI, null, null);} else {// Delete the specified data 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; // define ContentResolvercontentSesolver = super. getContentResolve R (); // get contentSesolverContentValues values = new ContentValues (); // set the content 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 Conte NtUris. parseId (resultUri); // resolution ID returned} private long textUpdate (String _ id, String name, int age, String birthday) {long result = 0; ContentResolver contentSesolver = null; // define ContentResolvercontentSesolver = super. getContentResolver (); // get contentSesolverContentValues values = new ContentValues (); // set the content values. put (MLDNbatabaseMetaData. memberTableMetaData. MEMBER_NAME, name); values. put (MLDNbatabaseMetaData. memberTabl EMetaData. MEMBER_AGE, age); values. put (MLDNbatabaseMetaData. memberTableMetaData. MEMBER_BIRTHDAY, birthday); if (_ id = null | "". equals (_ id) {// update all result = contentSesolver. update (MLDNbatabaseMetaData. memberTableMetaData. CONTENT_URI, values, null, null);} else {// update formulated data result = contentSesolver. update (Uri. withAppendedPath (MLDNbatabaseMetaData. memberTableMetaData. CONTENT_URI, _ id), values, null, null);} Uri res UltUri = 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 = "add data"/> <Button android: id = "@ + id/updateBut" android: layout _ Width = "wrap_content" android: layout_height = "wrap_content" android: text = "modify data"/> <Button android: id = "@ + id/deleteBut" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "delete data"/> <Button android: id = "@ + id/queryBut" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "query data"/> </LinearLayout> <ListView android: id = "@ + id/memberList" androi D: 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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.