Content Provider for SQLite

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Content Provider for SQLite

Postby nickmoi451 » Mon Apr 08, 2013 4:18 am

This sample code will show you how to create a list of Physical Constants in SQLite database and insert, detete data in SQLite database via ContentProvider.
andoird-content-provider
Step 1: Create SQLite database using DatabaseHelper.java class.

Code: Select all
class DatabaseHelper extends SQLiteOpenHelper {
  private static final String DATABASE_NAME="constants.db";

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

  @Override
  public void onCreate(SQLiteDatabase db) {
    Cursor c=db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='constants'", null);

    try {
      if (c.getCount()==0) {
        db.execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, value REAL);");

        ContentValues cv=new ContentValues();

        cv.put(Provider.Constants.TITLE, "Gravity, Death Star I");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Earth");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_EARTH);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Jupiter");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_JUPITER);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Mars");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_MARS);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Mercury");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_MERCURY);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Moon");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_MOON);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Neptune");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_NEPTUNE);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Pluto");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_PLUTO);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Saturn");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_SATURN);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Sun");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_SUN);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, The Island");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_THE_ISLAND);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Uranus");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_URANUS);
        db.insert("constants", Provider.Constants.TITLE, cv);

        cv.put(Provider.Constants.TITLE, "Gravity, Venus");
        cv.put(Provider.Constants.VALUE, SensorManager.GRAVITY_VENUS);
        db.insert("constants", Provider.Constants.TITLE, cv);
      }
    }
    finally {
      c.close();
    }
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    android.util.Log.w("Constants", "Upgrading database, which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS constants");
    onCreate(db);
  }
}




Step 2: Create ContentProvider. Provider Class.


Code: Select all
public class Provider extends ContentProvider {
    private static final int CONSTANTS = 1;
    private static final int CONSTANT_ID = 2;
    private static final UriMatcher MATCHER;
    private static final String TABLE = "constants";

    public static final class Constants implements BaseColumns {
        public static final Uri CONTENT_URI = Uri
                .parse("content://com.nineandroid.constants.Provider/constants");
        // Expose a content URI for this provider. This URI will be used to
        // access the Content Provider
        // from within application components using a ContentResolver
        /**
         * SQL table columns
         */
        public static final String DEFAULT_SORT_ORDER = "title";
        public static final String TITLE = "title";
        public static final String VALUE = "value";
    }

    static {
        MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
        MATCHER.addURI("com.nineandroid.constants.Provider", "constants",
                CONSTANTS);
        MATCHER.addURI("com.nineandroid.constants.Provider", "constants/#",
                CONSTANT_ID);
    }

    private DatabaseHelper dbHelper = null;

    /**
     * @author 9Android.net
     */
    @Override
    public boolean onCreate() {
        Log.d("Provider", "onCreate");
        dbHelper = new DatabaseHelper(getContext());
        return ((dbHelper == null) ? false : true);
    }

    @Override
    public Cursor query(Uri url, String[] projection, String selection,
            String[] selectionArgs, String sort) {
        Log.d("Provider", "query");
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(TABLE);
        String orderBy;
        if (TextUtils.isEmpty(sort)) {
            orderBy = Constants.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sort;
        }
        Cursor c = qb.query(dbHelper.getReadableDatabase(), projection,
                selection, selectionArgs, null, null, orderBy);
        c.setNotificationUri(getContext().getContentResolver(), url);
        return (c);
    }

    /**
     * Return the MIME type of the data at the given URI. This should start with
     * "vnd.android.cursor.item" for a single record, or
     * "vnd.android.cursor.dir" for multiple items. This method can be called
     * from multiple threads, as described in
     */
    @Override
    public String getType(Uri url) {
        Log.d("Provider", "getType");
        if (isCollectionUri(url)) {
            return ("vnd.android.cursor.dir/vnd.nineandroid.constant");
        }
        return ("vnd.android.cursor.item/vnd.nineandroid.constant");
    }

    @Override
    public Uri insert(Uri url, ContentValues initialValues) {
        long rowID = dbHelper.getWritableDatabase().insert(TABLE,
                Constants.TITLE, initialValues);
        if (rowID > 0) {
            Uri uri = ContentUris.withAppendedId(
                    Provider.Constants.CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(uri, null);
            return (uri);
        }
        throw new SQLException("Failed to insert row into " + url);
    }

    @Override
    public int delete(Uri url, String where, String[] whereArgs) {
        int count = dbHelper.getWritableDatabase().delete(TABLE, where,
                whereArgs);
        getContext().getContentResolver().notifyChange(url, null);
        return (count);
    }

    @Override
    public int update(Uri url, ContentValues values, String where,
            String[] whereArgs) {
        int count = dbHelper.getWritableDatabase().update(TABLE, values, where,
                whereArgs);
        getContext().getContentResolver().notifyChange(url, null);
        return (count);
    }

    private boolean isCollectionUri(Uri url) {
        return (MATCHER.match(url) == CONSTANTS);
    }
}




Step 3: Declare Provider in Manifest.


Code: Select all
<!--?xml version="1.0" encoding="utf-8"?-->




Step 4: ConstantsBrowser Activity.
Code: Select all
   

public class ConstantsBrowser extends ListActivity {
    //Key for Option Menu
    private static final int ADD_ID = Menu.FIRST + 1;
    private static final int DELETE_ID = Menu.FIRST + 3;
    //SQLite Database Projection(Column names)
    private static final String[] PROJECTION = new String[] {
            Provider.Constants._ID, Provider.Constants.TITLE,
            Provider.Constants.VALUE };
    private Cursor constantsCursor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // call Provider.query() to get Cursor
        // Wrapper around ContentResolver.query(android.net.Uri, String[],
        // String, String[],
        // String) that gives the resulting Cursor to call startManagingCursor
        // so that the activity will manage its lifecycle for you.

        constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,
                PROJECTION, null, null, null);
        ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
                constantsCursor, new String[] { Provider.Constants.TITLE,
                        Provider.Constants.VALUE }, new int[] { R.id.title,
                        R.id.value });
        setListAdapter(adapter);
        registerForContextMenu(getListView());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, ADD_ID, Menu.NONE, "Add").setIcon(R.drawable.add)
                .setAlphabeticShortcut('a');
        return (super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case ADD_ID:
            add();
            return (true);
        }
        return (super.onOptionsItemSelected(item));
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
                .setIcon(R.drawable.delete).setAlphabeticShortcut('d');
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case DELETE_ID:
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                    .getMenuInfo();
            delete(info.id);
            return (true);
        }
        return (super.onOptionsItemSelected(item));
    }

   /**
    * Add Constant Value to SQLite database via ContentProvider
    */
    private void add() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View addView = inflater.inflate(R.layout.add_edit, null);
        final DialogWrapper wrapper = new DialogWrapper(addView);
        new AlertDialog.Builder(this)
                .setTitle(R.string.add_title)
                .setView(addView)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                processAdd(wrapper);
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // ignore, just dismiss
                            }
                        }).show();
    }

    /**
     *
     * @param rowId
     */
    private void delete(final long rowId) {
        if (rowId > 0) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.delete_title)
                    .setPositiveButton(R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    processDelete(rowId);
                                }
                            })
                    .setNegativeButton(R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {
                                    // ignore, just dismiss
                                }
                            }).show();
        }
    }

    private void processAdd(DialogWrapper wrapper) {
        ContentValues values = new ContentValues(2);

        values.put(Provider.Constants.TITLE, wrapper.getTitle());
        values.put(Provider.Constants.VALUE, wrapper.getValue());

        getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
        constantsCursor.requery();
    }

    /**
     * Delete Constant Value to SQLite database via ContentProvider
     */
    private void processDelete(long rowId) {
        String[] args = { String.valueOf(rowId) };

        getContentResolver().delete(Provider.Constants.CONTENT_URI,
                Provider.Constants._ID + "=?", args);
        constantsCursor.requery();
    }

    /**
     *
     * @author 9Android.net
     *
     */
    class DialogWrapper {
        EditText titleField = null;
        EditText valueField = null;
        View base = null;

        DialogWrapper(View base) {
            this.base = base;
            valueField = (EditText) base.findViewById(R.id.value);
        }

        String getTitle() {
            return (getTitleField().getText().toString());
        }

        float getValue() {
            return (new Float(getValueField().getText().toString())
                    .floatValue());
        }

        private EditText getTitleField() {
            if (titleField == null) {
                titleField = (EditText) base.findViewById(R.id.title);
            }

            return (titleField);
        }

        private EditText getValueField() {
            if (valueField == null) {
                valueField = (EditText) base.findViewById(R.id.value);
            }

            return (valueField);
        }
    }
}


Download code: http://www.dl.9android.net/index.php?ac ... 1364252645
Source: http://www.9android.net/content-provider/
nickmoi451
Freshman
Freshman
 
Posts: 6
Joined: Mon Apr 08, 2013 2:12 am

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 10 guests