Thursday, April 1, 2010

Content Provider Example - 3

Sample Code - MainActivity.java
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btn1 = (Button) findViewById(R.id.Button01);
        Button btn2 = (Button) findViewById(R.id.Button02);
       
        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(MainActivity.this, "Item Added",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(MainActivity.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();
    }
}

-------------
MyContentProvider.java
public class MyContentProvider extends ContentProvider {
    public static final String PROVIDER_NAME = "com.contentproviderexample.mycontentprovider";
    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 = "vnd.android.cursor.dir/vnd.contentproviderexample.userinfo";
        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.contentproviderexample.userinfo";
        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;
    }
}
--------
SQLiteConnectionManager .java
public class SQLiteConnectionManager extends SQLiteOpenHelper {

    private static final String DATABASENAME = "DEMODB";
    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) {
    }
}


No comments:

Post a Comment