Saturday 1 December 2012

Content Provider in Android


Content Provider


Android application can use a file or SqlLite database to store data. Content provider provides the way by which you can share the data between multiple applications. For example contact data is used by multiple applications and must be stored in Content Provider to have common access. A content provider is a class that implements a standard set of methods to let other applications store and retrieve the type of data that is handled by that content provider. If you want your data to be public and handle by many applications create your own content provider.

Application can perform following operations on content provider -
      1.    Querying data
      2.    Modifying records
      3.    Adding records
      4.    Deleting records

Standard Content Provider: Android provide some standard content provider, which are already implemented in Android e.g. contacts, images on device etc. Using these content providers the application can access contact information, images available on the device etc.

Querying data: The query string in content provider is different than standard sql query. For any operation like select, add, delete, modify we required content provider URI. The URI consist of three parts, the string “content://”, segment representing kind of data to retrieve and optional ID of specific item of the specified content provider. Here are some examples of query string:
content://media/internal/images URI return the list of all internal images on the device.
content://contacts/people/ URI return the list of all contact names on the device.
content://contacts/people/45 URI return the single result row, the contact with ID=45.
Although this is the general form of the query, query URIs are somewhat arbitrary and confusing. For this android provide list of helper classes in android.provider package that define these query strings so you should not need to know the actual URI value for different data types.




One More Example:

Content Provider
Intended Data
Browser
Browser bookmarks, browser history, etc.
CallLog
Missed calls, call details, etc.
Contacts
Contact details
MediaStore
Media files such as audio, video and images
Settings
Device settings and preferences

To query a content provider, you provide a query string in the form of a URI, with an optional specifier for a particular row, using the following syntax:
   <standard_prefix>://<authority>/<data_path>/<id>
For example, to retrieve all the bookmarks stored by your web browsers (in Android), you would use the following content URI:
   content://browser/bookmarks
Similarly, to retrieve all the contacts stored by the Contacts application, the URI would look like this:
   content://contacts/people
To retrieve a particular contact, you can specify the URI with a specific ID:
   content://contacts/people/3
Of course, you can access all this information programmatically as well.

Let’s see the program:

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>
HomeActivity.java

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;

public class HomeActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        ContentValues cv = new ContentValues();
        cv.put("ename", "Tara");
        cv.put("esal", 2000);
        getContentResolver().insert(ProviderOutsideWorld.Emp.EMP_URI, cv);
       
        Cursor c = getContentResolver().query(ProviderOutsideWorld.Emp.EMP_URI, null, null, null, null);
        if(c!=null)
        {
            while(c.moveToNext())
            {
                        String name = c.getString(1);
                        int sal = c.getInt(2);
                        Toast.makeText(getApplicationContext(), "Name:"+name+"Sal:"+sal, 0).show();
            }
        }
    }
}


MyProvider.java

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

public class MyProvider extends ContentProvider
{
            public static final String MY_DB = "providerDB";
            public static final String MY_AUTHORITY = "providerAuthority";
            public static UriMatcher myUriMatcher = null;
            private MyHelper mh;
           
            static
            {
                        myUriMatcher =  new UriMatcher(-1);
                        myUriMatcher.addURI(MY_AUTHORITY, "emp", 1);
            }
           
            public class MyHelper extends SQLiteOpenHelper
            {

                        public MyHelper(Context context, String name, CursorFactory factory,
                                                int version) {
                                    super(context, name, factory, version);
                                    // TODO Auto-generated constructor stub
                        }

                        @Override
                        public void onCreate(SQLiteDatabase db)
                        {
                                    db.execSQL("create table Emp(_id integer primary key, ename text,esal integer);");
                        }

                        @Override
                        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                                    // TODO Auto-generated method stub
                                   
                        }
                       
            }

            @Override
            public int delete(Uri arg0, String arg1, String[] arg2) {
                        // TODO Auto-generated method stub
                        return 0;
            }

            @Override
            public String getType(Uri arg0) {
                        // TODO Auto-generated method stub
                        return null;
            }

            @Override
            public Uri insert(Uri uri, ContentValues values)
            {
                        SQLiteDatabase sdb = mh.getWritableDatabase();
                        switch(myUriMatcher.match(uri))
                        {
                        case 1:
                                        sdb.insert("Emp", null, values);
                                        break;
                        }
                        return null;
            }

            @Override
            public boolean onCreate()
            {
                        mh = new MyHelper(getContext(), MY_DB, null, 1);
                        return false;
            }

            @Override
            public Cursor query(Uri uri, String[] projection, String selection,
                                    String[] selectionArgs, String sortOrder)
            {
                        SQLiteDatabase sdb = mh.getReadableDatabase();
                        Cursor c = null;
                        switch(myUriMatcher.match(uri))
                        {
                        case 1:
                                       c = sdb.query("Emp", null, null, null, null, null, null);
                                       break;
                        }
                        return c;
            }

            @Override
            public int update(Uri uri, ContentValues values, String selection,
                                    String[] selectionArgs) {
                        // TODO Auto-generated method stub
                        return 0;
            }
}

ProviderOutsideWorld .java

import android.net.Uri;

public class ProviderOutsideWorld
{
            public static final class Emp
            {
                        public static final Uri EMP_URI = Uri.parse("content://"+MyProvider.MY_AUTHORITY+"/emp");
                        public static String _ID = "_id"; //integer
                        public static String ENAME = "ename"; //String
                        public static String ESAL = "esal"; //integer
            }
}

Final Result:


2 comments:

  1. Abe tara its not working,, its a run time eorror, illegal argument exception

    ReplyDelete
  2. This can happen if the user either dismisses the view, Not able to write the Value or u missing something. Can You post line where you getting exception??

    ReplyDelete