Saturday, January 26, 2013

Android Content Provider

Content Provider==>


Every application has its own sandbox and cannot access data from other applications. If  access to functions not provided by its own sandbox is required, the application must explicitly declare permission upfront before installation.Android provides an interface called ContentProvider to act as a bridge between applications, enabling them to share and change each other’s data.A content provider allows a clean separation between the application layer and data layer. It requires a permission setting in the AndroidManifest XML file and can be accessed using a simple URI model. Some native databases Android makes available as content.

Creating a Custom Content Provider
After getting a sense of how to use a content provider, it is time to integrate one into the diary project used in previous recipes.This recipe shows how to expose diary entries to other selected applications.A custom content provider just extends the Android ContentProvider class, which contains six methods to optionally override:


> query()—Allows third-party applications to retrieve content.
> insert()—Allows third-party applications to insert content.
> update()—Allows third-party applications to update content.
> delete()—Allows third-party applications to delete content.
> getType()—Allows third-party applications to read each of URI structures supported.
> onCreate()—Creates a database instance to help retrieve the content.


import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class DataStorageTester extends Activity {
    /** Called when the activity is first created. */
TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.output);
         String myUri = "content://com.jitesh.datastorage/diaries";
    Uri CONTENT_URI = Uri.parse(myUri);
        ContentResolver crInstance = getContentResolver(); //get a content Resolver instance
        Cursor c = crInstance.query(CONTENT_URI, null, null, null, null);
        startManagingCursor(c);
        StringBuilder sb = new StringBuilder();
        if(c.moveToFirst()){
        do{
        sb.append(c.getString(1)).append("\n");
       
        }while(c.moveToNext());
        }
        tv.setText(sb.toString());
       
    }
}



No comments:

Post a Comment