064 Java Android Program to Demonstrate Content Providers in Android
Posted by Superadmin on February 27 2017 04:17:09
Here is source code of the Program to Demonstrate Content Providers in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

 

A content provider manages access to a central repository of data. A provider is part of an Android application, which often provides its own UI for working with the data. However, content providers are primarily intended to be used by other applications, which access the provider using a provider client object. Together, providers and provider clients offer a consistent, standard interface to data that also handles inter-process communication and secure data access.

A content provider presents data to external applications as one or more tables that are similar to the tables found in a relational database. A row represents an instance of some type of data the provider collects, and each column in the row represents an individual piece of data collected for an instance.

Each Android application runs in its own process having its own permissions which keeps an application data hidden from another application. But sometimes it is required to share data across applications. This is where content providers plays its part , it helps to share data between different applications.

Content providers let you centralize data in one place and have different applications access it as they need. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete data content using insert(), update(), delete(), and query() methods. In almost all cases this data is stored in an SQlite database.

for more info. go to :-
http://developer.android.com/guide/topics/providers/content-providers.html

MainActivity.java

package com.example.mycontentprovider;
 
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    public void onClickAddTask(View view) {
        // Add a new student record
        ContentValues values = new ContentValues();
 
        values.put(ActivityProvider.Task_NAME,
                ((EditText) findViewById(R.id.taskName)).getText().toString());
 
        values.put(ActivityProvider.Activity,
                ((EditText) findViewById(R.id.taskPerform)).getText().toString());
 
        Uri uri = getContentResolver().insert(ActivityProvider.CONTENT_URI,
                values);
 
        Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG)
                .show();
    }
 
    public void onClickRetrieveTasks(View view) {
        // Retrieve student records
        String URL = "content://com.example.provider.Task/activities";
        Uri uri = Uri.parse(URL);
        Cursor cur = managedQuery(uri, null, null, null, "name");
        if (cur.moveToFirst()) {
            do {
                Toast.makeText(
                        this,
                        cur.getString(cur.getColumnIndex(StudentsProvider._ID))
                                + ", "
                                + cur.getString(cur
                                        .getColumnIndex(StudentsProvider.Task_NAME))
                                + ", "
                                + cur.getString(cur
                                        .getColumnIndex(StudentsProvider.Activity)),
                        Toast.LENGTH_SHORT).show();
            } while (cur.moveToNext());
        }
    }
}

ActiivtyProvider

 
package com.example.mycontentprovider;
 
import java.util.HashMap;
 
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
 
public class ActivityProvider extends ContentProvider {
 
    static final String PROVIDER_NAME = "com.example.provider.Task";
    static final String URL = "content://" + PROVIDER_NAME + "/activities";
    static final Uri CONTENT_URI = Uri.parse(URL);
 
    static final String _ID = "_id";
    static final String Task_NAME = "name";
    static final String Activity = "activity";
 
    private static HashMap<String, String> MAP;
 
    static final int ACTIVITIES = 1;
    static final int ACTIVITY_ID = 2;
 
    static final UriMatcher uriMatcher;
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "activities", ACTIVITIES);
        uriMatcher.addURI(PROVIDER_NAME, "activities/#", ACTIVITY_ID);
    }
 
    private SQLiteDatabase db;
    static final String DATABASE_NAME = "Activty";
    static final String TABLE_NAME = "students";
    static final int DATABASE_VERSION = 1;
    static final String CREATE_DB = " CREATE TABLE " + TABLE_NAME
            + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + " name TEXT NOT NULL, " + " activity TEXT NOT NULL);";
 
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
 
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_DB);
        }
 
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }
 
    @Override
    public boolean onCreate() {
        Context context = getContext();
        DatabaseHelper dbHelper = new DatabaseHelper(context);
        db = dbHelper.getWritableDatabase();
        return (db == null) ? false : true;
    }
 
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowID = db.insert(TABLE_NAME, "", values);
 
        if (rowID > 0) {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to add a record into " + uri);
    }
 
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
 
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(TABLE_NAME);
 
        switch (uriMatcher.match(uri)) {
        case ACTIVITIES:
            qb.setProjectionMap(MAP);
            break;
        case ACTIVITY_ID:
            qb.appendWhere(_ID + "=" + uri.getPathSegments().get(1));
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        if (sortOrder == null || sortOrder == "") {
            sortOrder = Task_NAME;
        }
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
 
        return c;
    }
 
    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
 
        switch (uriMatcher.match(uri)) {
        case ACTIVITIES:
            count = db.delete(TABLE_NAME, selection, selectionArgs);
            break;
        case ACTIVITY_ID:
            String id = uri.getPathSegments().get(1);
            count = db.delete(TABLE_NAME,
                    _ID
                            + " = "
                            + id
                            + (!TextUtils.isEmpty(selection) ? " AND ("
                                    + selection + ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
 
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
 
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int count = 0;
 
        switch (uriMatcher.match(uri)) {
        case ACTIVITIES:
            count = db.update(TABLE_NAME, values, selection, selectionArgs);
            break;
        case ACTIVITY_ID:
            count = db.update(
                    TABLE_NAME,
                    values,
                    _ID
                            + " = "
                            + uri.getPathSegments().get(1)
                            + (!TextUtils.isEmpty(selection) ? " AND ("
                                    + selection + ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
 
    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
        case ACTIVITIES:
            return "vnd.android.cursor.dir/vnd.example.activities";
        case ACTIVITY_ID:
            return "vnd.android.cursor.item/vnd.com.example.provider.Task."
                    + "activities";
        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }
}

Activity_main.xml

<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="Task Name" />
 
    <EditText
        android:id="@+id/taskName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Activity to perform" />
 
    <EditText
        android:id="@+id/taskPerform"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
 
    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickAddTask"
        android:text="Add Task" />
 
    <Button
        android:id="@+id/btnRetrieve"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickRetrieveTasks"
        android:text="Retrieve all Tasks" />
 
</LinearLayout>

AndoridManifest.xml

 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mycontentprovider"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.mycontentprovider.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <provider
            android:name="ActivityProvider"
            android:authorities="com.example.provider.Task" >
        </provider>
    </application>
 
</manifest>