Android database topics

       Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. Content providers are the standard interface that connects data in one process with code running in another process.
       When you want to access data in a content provider, you use the ContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.
Primary methods to be Implemented
       onCreate() which is called to initialize the provider
       query(Uri, String[], String, String[], String) which returns data to the caller
       insert(Uri, ContentValues) which inserts new data into the content provider
       update(Uri, ContentValues, String, String[]) which updates existing data in the content provider
       delete(Uri, String, String[]) which deletes data from the content provider
       getType(Uri) which returns the MIME type of data in the content provider
Accessing a Provider
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table           mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
Content URI : content://user_dictionary/words
user_dictionary : Authority
Words :Table Path
content:// : scheme
Content Provider Permissions
       <uses-permission android:name="android.permission.READ_USER_DICTIONARY“>
       Snippet for inserting values
ContentValuesmNewValues = new ContentValues();
    * Sets the values of each column and inserts the word. The arguments to the "put" * method are "column name" and "value" */
mNewValues.put(UserDictionary.Words.APP_ID, "example.user"); mNewValues.put(UserDictionary.Words.LOCALE, "en_US"); mNewValues.put(UserDictionary.Words.WORD, "insert"); mNewValues.put(UserDictionary.Words.FREQUENCY, "100");
mNewUri = getContentResolver().insert( UserDictionary.Word.CONTENT_URI, // the user dictionary content URI mNewValues // the values to insert );
Same way we can use update and delete.
Note : we should call ContentResolver.query() on  a separate way to do this using the cursor loader class
Creating a Content Provider
       The abstract class ContentProvider defines six abstract methods that you must implement as part of your own concrete subclass. All of these methods except onCreate() are called by a client application that is attempting to access your content provider:
       query() Retrieve data from your provider. Use the arguments to select the table to query, the rows and columns to return, and the sort order of the result. Return the data as a Cursor object.
       insert() Insert a new row into your provider. Use the arguments to select the destination table and to get the column values to use. Return a content URI for the newly-inserted row.
       update() Update existing rows in your provider. Use the arguments to select the table and rows to update and to get the updated column values. Return the number of rows updated.
       delete() Delete rows from your provider. Use the arguments to select the table and the rows to delete. Return the number of rows deleted.
       getType() Return the MIME type corresponding to a content URI. This method is described in more detail in the section Implementing Content Provider MIME Types. onCreate() Initialize your provider. The Android system calls this method immediately after it creates your provider. Notice that your provider is not created until a ContentResolver object tries to access it.
Sqlite Database
       Store structured data in a private database.
       The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database.
       The database is private to the application.
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
public void onCreate(SQLiteDatabasedb) {
       To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.
       execute SQLite queries using the SQLiteDatabasequery() methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others. For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for building queries.
       Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns.
       The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
       To get a SharedPreferences object for your application, use one of two methods:
       getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
       getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name
       Call edit() to get a SharedPreferences.Editor.
       Add values with methods such as putBoolean() and putString().
       Commit the new values with commit()
       public class PrefDemo extends Activity {
           /** Called when the activity is first created. */
       public void onCreate(Bundle savedInstanceState) {
       SharedPreferencessPref = PreferenceManager.getDefaultSharedPreferences(this);
       int counter = sPref.getInt("counter", 0);
       TextViewtxtView = (TextView) findViewById(;
       txtView.setText("App started  " + counter + "  times");
       SharedPreferences.Editor editor = sPref.edit();
       editor.putInt("counter", ++counter);
       For retreving values from shared prefernce several methods are there like getString(),getInt().
Internal storage
       We can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
       To create and write a private file to the internal storage:
       Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
       Write to the file with write().
       Close the stream with close().
       String FILENAME = "hello_file";
      String string = "hello world!";
FileOutputStreamfos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
       To read a file from internal storage:
       Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
       Read bytes from the file with read().
       Then close the stream with close().
External storage:
       Every Android-compatible device supports a shared "external storage" that we can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
       getExternalStorageState() will return true if external storage is available.


Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams