North Border Software

Home Tutorials Hints & Tips About
Share on Facebook Share on Twitter

Getting Started in Android Development

Part 39 - Adding an Entry to the SQLite Database

In this tutorial we continue with the SQLite example and create methods to add entries and view the database. We finally get a chance to test the work so far.

Starting with the SqliteActivity we can add some code to the "add entry" button's case statement.

The first two lines retrieve the text we enter from the two EditText fields in the associated layout actvity_sql.xml.

memberName = nameText.getText().toString();
memberStatus = statusText.getText().toString();

We then create an object of the MembersDatabase class and pass the context "this". This is in fact a call to the constructor.

MembersDatabase newMember = new MembersDatabase(this);

We then open the database, create the entry and close the database.;
newMember.addEntry(memberName, memberStatus);

The methods to open and close were created in the last tutorial. Adding the code for the addEntry(memberName, memberStatus) will generate an error. You can have Android Studio resolve this error by having it automatically create the method's framework in the file. It will also take care of setting up the string parameters for the Member's name and their status.

The code for the addEntry() method is below:

public long addEntry(String memberName, String memberStatus) {
   ContentValues contentValues = new ContentValues();
   contentValues.put(KEY_NAME, memberName);
   contentValues.put(KEY_STATUS, memberStatus);
   return memebersDatabase.insert(DATABASE_TABLE, null, contentValues);

The insert() method returns the row ID of the newly created record. This value is a long value and so this is why we need to use the statement memebersDatabase.insert(DATABASE_TABLE, null, contentValues) after the return statement.

We use content values when working with database data. The first thing we need to do is create an object of the ContentValues class. We add the data to the database by using the put() method.  The Key is the column headings we defined in the beginning and we simply associate the string values we passed with the relevant key. We then finally insert the record into the database.

After this tutorial you file should look similar to the one below:

Your file should look similar to the one below:

Download Download tutorial set 2

© 2015 North Border Software All rights reserved
Privacy and Cookies Terms of Use Disclaimer Copyright
North Border Software Logo

Android Apps and Training