ContentProvider complete code,in android

package org.dharani.contentProvider;

import java.util.ArrayList;

import org.dharani.contentProvider.MyContentProvider.UserInfo;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ContentProvider234Activity extends Activity {
    /** Content provider best code */
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btn1 = (Button) findViewById(R.id.button1);
        Button btn2 = (Button) findViewById(R.id.button2);
       
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues values = new ContentValues();
                values.put(UserInfo.isactive, "Y");
                Uri uri = getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
                Toast.makeText(ContentProvider234Activity.this, "Item Added",Toast.LENGTH_LONG).show();
            }
        });
        /*btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues values = new ContentValues();
                Uri uri;
                System.out.println("**** Time ****"+System.currentTimeMillis());
                for(int i=0;i<500;i++){
                    System.out.println("----i------"+i);
                    if(i==15)
                        values.put("myDBase", "Pavan Tilak"+i);   
                    else
                        values.put(UserInfo.isactive, "Pavan Tilak"+i);
                uri = getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
                }
                System.out.println("**** Time ****"+System.currentTimeMillis());
                Toast.makeText(ContentProvider234Activity.this, "Items Added successfully",Toast.LENGTH_LONG).show();
            }
        });*/

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String resultStr = "";
                Uri allTitles = Uri.parse("content://"+ MyContentProvider.PROVIDER_NAME + "/"+ UserInfo.DATABASE_TABLE);
                Cursor c = managedQuery(allTitles, null, null, null, "");
                if (c.moveToFirst()) {
                    do {
                        resultStr = c.getString(c.getColumnIndex(UserInfo._ID))+ ", "+ c.getString(c.getColumnIndex(UserInfo.isactive));
                        Toast.makeText(ContentProvider234Activity.this, resultStr,Toast.LENGTH_LONG).show();
                    } while (c.moveToNext());
                }
            }
        });
    }

    public void readContact() {

        ArrayList<String> contactList;
        contactList = new ArrayList<String>();

        String[] columns = new String[] { People.NAME, People.NUMBER };
        Uri mContacts = People.CONTENT_URI;
        Cursor mCur = managedQuery(mContacts, columns, null, null, People.NAME+ " ASC ");
        if (mCur.moveToFirst()) {
            do {
                contactList.add(mCur.getString(mCur.getColumnIndex(People.NAME)));
            } while (mCur.moveToNext());
        }
        Toast.makeText(this, contactList.size() + "", Toast.LENGTH_LONG).show();
    }
}

-------------------------------------------------------------------------------------
package org.dharani.contentProvider;

import android.content.ContentProvider;
import android.content.ContentResolver;
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.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class MyContentProvider extends ContentProvider {
    public static final String PROVIDER_NAME = "org.dharani.contentProvider";
    public static final Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/demodb");   
    private static final UriMatcher uriMatcher;
    private SQLiteDatabase demoDB;   

    public static final class UserInfo implements BaseColumns {
        public static final String DATABASE_TABLE = "userinfo";
        public static final int USERINFO = 1;
        public static final int USERINFO_ID = 2;
        public static final Uri CONTENT_URI = Uri.parse("content://"+ PROVIDER_NAME + "/userinfo");
        public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
        + "/todos";
        public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
        + "/todo";
        public static final String _ID = "_id";
        public static final String isactive = "isactive";
    }

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, UserInfo.DATABASE_TABLE,UserInfo.USERINFO);       
        uriMatcher.addURI(PROVIDER_NAME, UserInfo.DATABASE_TABLE + "/#",UserInfo.USERINFO);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        SQLiteConnectionManager dbHelper = new SQLiteConnectionManager(context);
        demoDB = dbHelper.getWritableDatabase();
        return (demoDB == null) ? false : true;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
        case UserInfo.USERINFO:
            return UserInfo.CONTENT_TYPE;
        case UserInfo.USERINFO_ID:
            return UserInfo.CONTENT_ITEM_TYPE;
        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }
    @Override
    public Uri insert(Uri uri, ContentValues values) {

        long rowID = demoDB.insert(UserInfo.DATABASE_TABLE, "", values);
        if (rowID > 0) {
            Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        sqlBuilder.setTables(UserInfo.DATABASE_TABLE);
        if (uriMatcher.match(uri) == UserInfo.USERINFO_ID)
            sqlBuilder.appendWhere(UserInfo._ID + " = "+ uri.getPathSegments().get(1));
        Cursor c = sqlBuilder.query(demoDB, 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 UserInfo.USERINFO:
            count = demoDB.delete(UserInfo.DATABASE_TABLE, selection,selectionArgs);
            break;

        case UserInfo.USERINFO_ID:
            String id = uri.getPathSegments().get(1);
            count = demoDB.delete(UserInfo.DATABASE_TABLE, UserInfo._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 UserInfo.USERINFO:
            count = demoDB.update(UserInfo.DATABASE_TABLE, values, selection,selectionArgs);
            break;
        case UserInfo.USERINFO_ID:
            count = demoDB.update(UserInfo.DATABASE_TABLE, values, UserInfo._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;
    }
}
--------------------------------------------------------------------------------------
package org.dharani.contentProvider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteConnectionManager extends SQLiteOpenHelper {

    private static final String DATABASENAME = "contentProvidDBase.sqlite";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_USERINFO = "CREATE TABLE userinfo(_id INTEGER NOT NULL CONSTRAINT USER_PK PRIMARY KEY AUTOINCREMENT,isactive TEXT DEFAULT 'Y')";
    public SQLiteConnectionManager(Context context) {
        super(context, DATABASENAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USERINFO);
        Log.d("@G SQLConnectionFactory", " CREATE_LEADSOURCE Table ");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}
--------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.dharani.contentProvider"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ContentProvider234Activity"
            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=".MyContentProvider"
            android:authorities="org.dharani.contentProvider" >
        </provider>
    </application>

</manifest>
-------------------------------------------------------------------------
create DataBase with name "contentProvidDBase.sqlite" and place it in assets folder.
and all above three classes placed in Same Package like:"org.dharani.contentProvider"

Comments

Popular posts from this blog

Custom Dialog with no title and full screen in Android

Best working code to set Date limits on Date Picker Dialog,in Android

code to display .pdf,.text,.DOC,.DOCX,.doc extension files exists in SDCard