Android ContentProvider combined with LoaderManager to load data (text source code sharing)

Source: Internet
Author: User

As one of the four storage methods of Android, ContentProvider is widely applied. It exposes data addresses and allows other applications to access data and store images, address books, and other information, this blog post will detail the usage and introduction of ContentProvider, URIMatcher, LoaderManager, and cursorAdapter. When using ContentProvider, you must declare its attributes in the manifest configuration file like the Acticity file.


In addition, because we use loadermanager to load data, the MainAcitivity class must implement the LoaderCallback interface. By convention, let's take a look at Google's official documentation's explanation of contentprovider. ContentProvider manages a structured dataset. It encapsulates data and provides a data security mechanism. Standard interfaces of ContentProvider implement multi-threaded mechanism to connect data. Generally, loaderManager is used to asynchronously load data. When you want to access data in a ContentProvider, we use the ContentResolver object as the communication method in the context of the application. ContentResolver is used to parse the Request Code and return data.

Let's take a look at the directory structure of this project.


MainActivity code

Package com. example. f14_contentprovider; import java. util. arrayList; import java. util. hashMap; import java. util. list; import android.net. uri; import android. OS. bundle; import android. app. activity; import android. app. loaderManager; import android. app. loaderManager. loaderCallbacks; import android. content. contentResolver; import android. content. contentValues; import android. content. cursorLoader; import android. co Ntent. loader; import android. database. cursor; import android. view. menu; import android. view. view; import android. widget. button; import android. widget. listView; import android. widget. simpleCursorAdapter; public class MainActivity extends Activity implements LoaderCallbacks <Cursor> {private Button button; private ListView listView; private LoaderManager loaderManager; private SimpleCursorAdapter adapter; @ Over Rideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button1); listView = (ListView) this. findViewById (R. id. listView1); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubContentResolver resolver = getContentR Esolver (); Uri uri = Uri. parse ("content: // com. example. f14_contentprovider.PersonContentProvider/person "); ContentValues values = new ContentValues (); values. put ("name", "jack"); values. put ("address", "hangzhou"); resolver. insert (uri, values); loaderManager. restartLoader (1001, null, MainActivity. this) ;}}); loaderManager = getLoaderManager (); loaderManager. initLoader (1001, null, this) ;}@ Overridepublic Loade R <Cursor> onCreateLoader (int id, Bundle args) {// TODO Auto-generated method stub/*** CursorLoader is used to load programs, query ContentResolver, and return a pointer. This class implements the standard method for querying the cursor of the loader protocol. * The cursor query is executed in a background thread Based on AsyncTaskLoader so that it does not block the UI of the application. */CursorLoader loader = new CursorLoader (this); Uri uri = Uri. parse ("content: // com. example. f14_contentprovider.PersonContentProvider/person "); loader. setUri (uri); loader. setProjection (new String [] {"name", "address"}); return loader ;}@ SuppressWarnings ("deprecation") @ Overridepublic void onLoadFinished (Loader <Cursor> arg0, cursor arg1) {// TODO Auto-generated method stubList <HashMap <String, String> list = new ArrayList <HashMap <String, String> (); // load the data while (arg1.moveToNext () {HashMap <String, String> map = new HashMap <String, String> (); map. put ("name", arg1.getString (arg1.getColumnIndex ("name"); map. put ("address", arg1.getString (arg1.getColumnIndex ("address"); list. add (map);} adapter = new SimpleCursorAdapter (this, R. layout. item, arg1, new String [] {"name", "address"}, new int [] {R. id. textView1, R. id. textView2}); listView. setAdapter (adapter); adapter. notifyDataSetChanged (); // This method is triggered if the content changes.} @ Overridepublic void onLoaderReset (Loader <Cursor> arg0) {// TODO Auto-generated method stub }}
As shown above, in the MainAcitivity main method, you can see that in line 40-47 of the Code, when inserting data through the content provider contentProvider, it is connected through contentResolver, the insert method allows you to insert specified data tables and data to complete the operation. After the operation, call the restart Method of loadermanager to update the UI.
PersonContentProvider inherits the ContentProvider method.

Package com. example. f14_contentprovider; import android. content. contentProvider; import android. content. contentResolver; 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; // register providerpublic class PersonContentProvider extends ContentPr in the manifest File Ovider {private MyOpenHelper helper; private static final UriMatcher matcher = new UriMatcher (UriMatcher. NO_MATCH); // The class private static final int PERSONS = 1; private static final int PERSON = 2; private ContentResolver resolver; static {matcher. addURI ("com. example. f14_contentprovider.PersonContentProvider "," person ", PERSONS); matcher. addURI ("com. example. f14_contentprovider.PersonContentProvide R "," person/# ", PERSON) ;}@ Overridepublic int delete (Uri uri, String selection, String [] selectionArgs) {// TODO Auto-generated method stubreturn 0;} // when you need to match a URI, call the URI to create a query. The return type is, insert or delete a row. @ Overridepublic String getType (Uri arg0) {// TODO Auto-generated method stubint match = matcher. match (arg0); switch (match) {case PERSONS: return "vnd. android. cursor. dir/person "; case PERSON: return" vnd. android. cursor. item/person "; default: return null ;}@ Overridepublic Uri insert (Uri uri, ContentValues values) {// TODO Auto-generated method stubSQLiteDatabase database = helper. getWritableDatabase (); lon G id = database. insert ("person", null, values); Uri rUri = ContentUris. withAppendedId (uri, id); resolver. categorychange (rUri, null); return rUri;} @ Overridepublic boolean onCreate () {// TODO Auto-generated method stubhelper = new MyOpenHelper (getContext ()); resolver = getContext (). getContentResolver (); return true;} @ Overridepublic Cursor query (Uri uri, String [] projection, String selection, String [] select IonArgs, String sortOrder) {// TODO Auto-generated method stubCursor cursor = null; int flag = matcher. match (uri); SQLiteDatabase database = helper. getReadableDatabase (); switch (flag) {case PERSONS: cursor = database. query ("person", null, null); break; case PERSON: long _ id = ContentUris. parseId (uri); String where_value = "_ id =" + _ id; if (selection! = Null &&! Selection. equals ("") {where_value + = selection;} cursor = database. query ("person", projection, where_value, selectionArgs, null, null, sortOrder); break; default: break;} cursor. setNotificationUri (resolver, uri); return cursor;} @ Overridepublic int update (Uri arg0, ContentValues arg1, String arg2, String [] arg3) {// TODO Auto-generated method stubreturn 0 ;}}

Database creation class MyopenHelper

package com.example.f14_contentprovider;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class MyOpenHelper extends SQLiteOpenHelper {private static final int DATABASE_VERSION = 1;private static final String PERSON_TABLE_NAME = "person";public MyOpenHelper(Context context) {super(context, PERSON_TABLE_NAME, null, DATABASE_VERSION);// TODO Auto-generated constructor stub}@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubdb.execSQL("create table "+ PERSON_TABLE_NAME+ "(_id integer primary key autoincrement,name varchar(64),address varchar(64))");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub}}


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.