Pages

Thursday 15 March 2012

Custom Content Provider


This will be useful for creating the own content provider. Follow the steps which has given below to create your own custom adapter. I thought that content provider and sqlite database are different. But what i thought is totally worng. The database can access only from that particular application. If you are creating the content provider which means creating URI for each row for the database. So from other application you can access tha database using the content provider URI. So both are inter related . You will understand if you follow the code.
Mimeprovider.java
package com.Androitanz.Provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
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.provider.BaseColumns;

/**
 * The provider creation,fetching and displaying
 *
 * @author Anitha
 *
 */
public class MimeProvider extends ContentProvider {
      /**
       * The instance sqlitedatabase
       */
      private SQLiteDatabase sqlDB;
      /**
       * The instance for DatabaseHelper
       */
      private DatabaseHelper dbHelper;
      /**
       * Database name for MIME app
       */
      private static final String DATABASE_NAME = "Friends.db";
      /**
       * Database version that we are using
       */

      private static final int DATABASE_VERSION = 1;
      /**
       * The table name using to store the information
       */

      private static final String TABLE_NAME = "Friends";

      private static final String TAG = "AndrointanZProvider";

      /**
       *
       * @author Lukshanu
       *
       */
      public static class ProviderDetails implements BaseColumns {
            public static final String AUTHORITY = "com.Androitanz.Provider.MimeProvider";

            // BaseColumn contains _id.

            public final static Uri CONTENT_URI = Uri
                        .parse("content://com.Androitanz.Provider.MimeProvider");

            // Table column
            public static final String FRIENDS_NAME = "FRIENDS_NAME";
      }

      private static class DatabaseHelper extends SQLiteOpenHelper {

            DatabaseHelper(Context context) {
                  super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            @Override
            public void onCreate(SQLiteDatabase db) {
                  // create table to store user names
                  db.execSQL("Create table "
                              + TABLE_NAME
                              + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, FRIENDS_NAME TEXT);");
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                  db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
                  onCreate(db);
            }
      }

      @Override
      public int delete(Uri uri, String selection, String[] selectionArgs) {
            // TODO Auto-generated method stub

            return 0;
      }

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

      @Override
      public Uri insert(Uri uri, ContentValues contentValues) {
            // get database to insert records
            sqlDB = dbHelper.getWritableDatabase();
            // insert record in user table and get the row number of recently
            long rowId = sqlDB.insert(TABLE_NAME, "", contentValues);
            if (rowId > 0) {
                  Uri rowUri = ContentUris.appendId(
                              ProviderDetails.CONTENT_URI.buildUpon(), rowId).build();
                  getContext().getContentResolver().notifyChange(rowUri, null);
                  return rowUri;
            }
            throw new SQLException("Failed to insert row into " + uri);
      }

      @Override
      public boolean onCreate() {
            dbHelper = new DatabaseHelper(getContext());
            return (dbHelper == null) ? false : true;
      }

      @Override
      public Cursor query(Uri uri, String[] projection, String selection,
                  String[] selectionArgs, String sortOrder) {
            SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            qb.setTables(TABLE_NAME);
            Cursor c = qb.query(db, projection, selection, null, null, null,
                        sortOrder);
            c.setNotificationUri(getContext().getContentResolver(), uri);
            return c;
      }

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

}
The Activity to get the inputs and to store it in the content provider.
ContentDisplay.java
package com.Androitanz.Activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.Androitanz.Provider.MimeProvider.ProviderDetails;

/**
 * The Screen to fetch the name to store it in the provider and database
 *
 * @author Anitha
 *
 */
public class ContentDisplay extends Activity {
      private EditText mContactNameEditText;
      private TextView mContactsText;
      private Button mContactSaveButton;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            // Obtain handles to UI objects
            mContactNameEditText = (EditText) findViewById(R.id.contactNameEditText);
            mContactSaveButton = (Button) findViewById(R.id.contactSaveButton);
            mContactsText = (TextView) findViewById(R.id.contactEntryText);
            mContactSaveButton.setOnClickListener(new View.OnClickListener() {

                  @Override
                  public void onClick(View v) {
                        String name = mContactNameEditText.getText().toString();
                        insertRecord(name);
                        mContactsText.append("\n" + name);
                  }
            });

            displayRecords();
      }

      private void insertRecord(String userName) {
            ContentValues values = new ContentValues();
            values.put(ProviderDetails.FRIENDS_NAME, userName);
            getContentResolver().insert(ProviderDetails.CONTENT_URI, values);
      }

      private void displayRecords() {
            // An array specifying which columns to return.
            String columns[] = new String[] { ProviderDetails._ID,
                        ProviderDetails.FRIENDS_NAME };
            Uri myUri = ProviderDetails.CONTENT_URI;
            Cursor cur = managedQuery(myUri, columns, // Which columns to return
                        null, // WHERE clause; which rows to return(all rows)
                        null, // WHERE clause selection arguments (none)
                        null // Order-by clause (ascending by name)
            );
            if (cur.moveToFirst()) {
                  String id = null;
                  String userName = null;
                  do {
                        // Get the field values
                        id = cur.getString(cur.getColumnIndex(ProviderDetails._ID));
                        userName = cur.getString(cur
                                    .getColumnIndex(ProviderDetails.FRIENDS_NAME));
                        Toast.makeText(this, id + " " + userName, Toast.LENGTH_LONG)
                                    .show();
                  } while (cur.moveToNext());
            }
      }
}

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

        <TableRow>
            <TextView android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:text="contactNameLabel"/>
        </TableRow>
        <TableRow>
            <EditText android:id="@+id/contactNameEditText"
                      android:layout_height="wrap_content"
                      android:layout_width="wrap_content"
                      android:layout_weight="1"/>
        </TableRow>
        <TableRow>
            <Button android:layout_height="wrap_content"
                    android:text="save"
                    android:id="@+id/contactSaveButton"
                    android:layout_width="fill_parent"
                    android:layout_weight="1"/>
        </TableRow>
        <TableRow>
              <TextView android:text="@+id/contactEntryText"
                    android:id="@+id/contactEntryText"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>
             </TableRow>

    </TableLayout>
</ScrollView>
The things need to be mentioned in the manifest file are as follows. The provider tag should come within the application tag
<provider
    android:authorities="com.Androitanz.Provider.MimeProvider"
    android:multiprocess="true"
    android:name="com.Androitanz.Provider.MimeProvider"></provider>

No comments:

Post a Comment