Android Basics – Learn how to insert records to the SQLite Database

So far you have seen how to fetch data from the SQLite database using Cursor. Inserting and updating data is also pretty simple.

The following code inserts data to the survey table.

try {
    SurveyDBHelper surveyDBHelper = new SurveyDBHelper(this);
    SQLiteDatabase db = surveyDBHelper.getReadableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(SurveyDBHelper.SURVEY_TABLE_NAME_COLUMN, userNameId.getText().toString());
    cv.put(SurveyDBHelper.SURVEY_TABLE_EMAIL_COLUMN, userEmailId.getText().toString());
    cv.put(SurveyDBHelper.SURVEY_TABLE_AGE_COLUMN, userAgeId.getText().toString());

    db.insert(SurveyDBHelper.SURVEY_TABLE, null, cv);

    db.close();
}catch (SQLiteException e){
    Log.v(TAG, "Exception "+e.getMessage());
}

In the above code fragment you need to create a Content Value object which stores key value pairs. This object is then used for insert.

Follow the video to understand this better. The source code is available here for reference.

Author: codesmartly

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s