RSS Feed

Use Of ContentValues Insert SQL Database Android Studio – Tidy SQL

With more complex inserts into an SQL database I find using ContextValue so much better that forming a complex string to SQL Insert.

Here is an example of how to use ContentValues.

First here is a declaration in my class that extends SQLiteOpenHelper

STEP 1

public class DatabaseCreate extends SQLiteOpenHelper
{

// Logcat tag
private static final String LOG = “InterLink Database”;

// Database Version
private static final int DATABASE_VERSION = 16;

// Database Name
private static final String DATABASE_NAME = “Interlink”;

// Table Names
private static final String TABLE_DIAGRAM = “DIAGRAM”;

// Common column names

private static final String ID = “ID”;
private static final String NAME = “Name”;
private static final String DESCRIPTION = “Description”;
private static final String CREATEDUSERID = “CreatedUserID”;
private static final String UPDATEUSERID = “UpdatedUserID”;
private static final String CREATEDDATETIME = “CreatedDateTime”;
private static final String UPDATEDDATETIME = “UpdatedDateTime”;

// This is my table declaration

private static final String CREATE_TABLE_DIAGRAM = “CREATE TABLE “
+ TABLE_DIAGRAM +
“(” +
ID + ” INTEGER PRIMARY KEY,” +
NAME + ” TEXT,” +
DESCRIPTION + ” TEXT,” +
CREATEDUSERID + ” INTEGER,” +
UPDATEUSERID + ” INTEGER,” +
CREATEDDATETIME + ” TEXT,” +
UPDATEDDATETIME + ” TEXT” +
“)”;

etc…

}

STEP 2

Here is the onCreate where I insert into my table diagram. Notice the use of “ContentValues” and the “put” clause. Also, notice how much easier it is to read and create the insert statement. Also note that you have to have access to the database, see variable db.

public void onCreate(SQLiteDatabase db)
{
Log.d(“DATABASE”, CREATE_TABLE_DIAGRAM);
db.execSQL(CREATE_TABLE_DIAGRAM);

// Insert Default Diagram

Log.d(“DATABASE”, “INSERT TABLE_DIAGRAM”);
ContentValues content = new ContentValues();
content.put(NAME, “Sample Diagram”);
content.put(DESCRIPTION, “This is a sample diagram to show how your own diagrams might look.”);
content.put(CREATEDUSERID, 1);
content.put(UPDATEUSERID, 1);
Date d = new Date();
content.put(CREATEDDATETIME, d.toString());
content.put(UPDATEDDATETIME, d.toString());

db.insert(TABLE_DIAGRAM, null, content);

}

Advertisements

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 )

Connecting to %s

%d bloggers like this: