MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to insert data into a SQLite database in Android

In this article, we will learn what Sqlite android database is and how to use Sqlite database to store our records.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

In android, there are several ways to store data while working with android applications. We can store data by preferences, files or using database. Android provides a very tiny database named Sqlite. A Sqlite database provides a way to store database on the android device. Mostly all the android device has its own lightweight Sqlite database.

Sqlite Android Database Insert Operation in Detail:

In order to use Sqlite in our android application, we are required to inherit our class with SQLiteOpenHelper class. This class will be treated as a database controller of our application. The class SQLiteOpenHelper has two methods onCreate() and onUpgrade(), which are required to override into this child class. The method onCreate() is required to initialize our application for Sqlite database. It will be using getReadableDatabaes() or getWritableDatabase() methods to initialize database. These two methods are defined into class SQLiteQueryBuilder class. Hence, we are required to import SQLiteQueryBuilder class.

Listing 1: SqliteController.java

public SqliteController(Context applicationcontext) {
  super(applicationcontext, "androidsqlite.db", null, 1);
  Log.d(LOGCAT,"Created");
}

Listing 1 defines SqliteController class constructor that initializes android Sqlite database using application context instance of Context class type. Once database is initialized, a log will be displayed as created into the log console.

Now, Lets create a table into the database table name “student” and define three records into this table named “id”, “name” and “course”.

Listing 2: Create Student Table

@Override
public void onCreate(SQLiteDatabase database) {
  String query;
  query = "CREATE TABLE student ( id INTEGER PRIMARY KEY, name TEXT, course TEXT)";
  database.execSQL(query);
  Log.d(LOGCAT,"animals Created");
}

Listing 2 defines onCreate() method overridden that defines a query to create student table.

onCreate() method will be called for once, while application initializes and creates database to be used by the application. onUpgrade() method may be used to perform any other kind of database operation to be performed like database table modification and etc.

To create a record into the student table, we define a method insertRecord() into the SqliteController.java class file as defined into the Listing 3:

Listing 3: insertRecord() method

public void insertRecord(HashMap<String, String> queryValues) {
  SQLiteDatabase database = this.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put("Name", queryValues.get("name"));
  database.insert("student", null, values);
  database.close();
}

Listing 3 defines a method insertRecord() that accept string type hashmapped collection object that provides values to be inserted into the database. There are two instances of type SQLiteDatabase and ContentValues class types, created respectively. A put() method initializes values to be inserted into the database and insert() method of SQLiteDatabase class is used to insert record into the database that accept three parameters “table-name”, second will remain null and third will be the ContentValues class type instance variable. Once a record is inserted into the database, database connection should be closed using SQLiteDatabase class method close().

Listing 4: SqliteController.java

package com.test.sqlite;

import java.util.ArrayList;

import java.util.HashMap;

import android.util.Log;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SqliteController  extends SQLiteOpenHelper {
	private static final String LOGCAT = null;

	public SqliteController(Context applicationcontext) {
        super(applicationcontext, "androidsqlite.db", null, 1);
        Log.d(LOGCAT,"Created");
    }
	
	@Override
	public void onCreate(SQLiteDatabase database) {
		String query;
		query = "CREATE TABLE Students ( StudentId INTEGER PRIMARY KEY, StudentName TEXT)";
        database.execSQL(query);
        Log.d(LOGCAT,"Students Created");
	}
	@Override
	public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
		String query;
		query = "DROP TABLE IF EXISTS Students";
		database.execSQL(query);
        onCreate(database);
	}
	
	public void insertStudent(HashMap<String, String> queryValues) {
		SQLiteDatabase database = this.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("StudentName", queryValues.get("StudentName"));
		database.insert("Students", null, values);
		database.close();
	}
	
	public int updateStudent(HashMap<String, String> queryValues) {
		SQLiteDatabase database = this.getWritableDatabase();	 
	    ContentValues values = new ContentValues();
	    values.put("StudentName", queryValues.get("StudentName"));
	    return database.update("Students", values, "StudentId" + " = ?", new String[] { queryValues.get("StudentId") });
	    //String updateQuery = "Update  words set txtWord='"+word+"' where txtWord='"+ oldWord +"'";
	    //Log.d(LOGCAT,updateQuery);
	    //database.rawQuery(updateQuery, null);
	    //return database.update("words", values, "txtWord  = ?", new String[] { word });
	}
	
	public void deleteStudent(String id) {
		Log.d(LOGCAT,"delete");
		SQLiteDatabase database = this.getWritableDatabase();	 
		String deleteQuery = "DELETE FROM  Students where StudentId='"+ id +"'";
		Log.d("query",deleteQuery);		
		database.execSQL(deleteQuery);
	}
	
	public ArrayList<HashMap<String, String>> getAllStudents() {
		ArrayList<HashMap<String, String>> wordList;
		wordList = new ArrayList<HashMap<String, String>>();
		String selectQuery = "SELECT  * FROM Students";
	    SQLiteDatabase database = this.getWritableDatabase();
	    Cursor cursor = database.rawQuery(selectQuery, null);
	    if (cursor.moveToFirst()) {
	        do {
	        	HashMap<String, String> map = new HashMap<String, String>();
	        	map.put("StudentId", cursor.getString(0));
	        	map.put("StudentName", cursor.getString(1));
                wordList.add(map);
	        } while (cursor.moveToNext());
	    }
	 
	    // return contact list
	    return wordList;
	}
	
	public HashMap<String, String> getStudentInfo(String id) {
		HashMap<String, String> wordList = new HashMap<String, String>();
		SQLiteDatabase database = this.getReadableDatabase();
		String selectQuery = "SELECT * FROM Students where StudentId='"+id+"'";
		Cursor cursor = database.rawQuery(selectQuery, null);
		if (cursor.moveToFirst()) {
	        do {
					//HashMap<String, String> map = new HashMap<String, String>();
	        	wordList.put("StudentName", cursor.getString(1));
				   //wordList.add(map);
	        } while (cursor.moveToNext());
	    }				    
	return wordList;
	}	
}

In the same way, it is also defined few other methods to update, and create student into the database.

Listing 6: Activity Manage.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    
    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:background="#000000"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="Student"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/button1"
            android:layout_width="41dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="#454545"
            android:onClick="showAddForm"
            android:text="+"
            android:textColor="#FFFFFF"
            android:textSize="30sp" />

    </RelativeLayout>
     <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/relativeLayout1"
        android:orientation="vertical"
        android:layout_marginTop="40dp">

    <ListView
         android:id="@android:id/list"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true">
     </ListView>
     </RelativeLayout>

</RelativeLayout>

Listing 6 defines the main acitivity xml file to create view shown into the figure 1 as below:

Main Activity

Figure 1: Main Activity

Figure 1 shows the main activity that loads, while application loads. It list all the inserted items into the database.

Now lets define the activity to add a student record into the database as listed into Listing 7:

Listing 7: add_new_student.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#CCCCCC"
    android:orientation="vertical"
    android:paddingTop="1dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:padding="5dp"
        android:text="Add Student"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF" />

       <RelativeLayout
     android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"
        android:orientation="vertical"
        android:padding="10dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="30dp"
        android:text="Student" />

    <EditText
        android:id="@+id/studentName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/btnadd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/studentName"
        android:layout_below="@+id/studentName"
        android:layout_marginTop="32dp"
        android:text="Save"      
    	android:onClick="addNewStudent" />

   

</RelativeLayout>
        

</LinearLayout>

Listing 7 defines a xml file add_new_student.xml file that creates an activity to be shown into the application as shown into the figure 2 as below:

Add new student record

Figure 2: Add new student record

Figure 2 shows an activity to insert a student record into the database.

Now lets define main activity java class that will configure all the inserted records and at the start activity as listed into the Listing 8:

Listing 8: MainActivity.java

package com.test.sqlite;

import java.util.ArrayList;
import java.util.HashMap;

import com.javapapers.android.sqlitestorageoption.R;
import com.test.sqlite.SqliteController;
import com.test.sqlite.NewStudent;

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ListView;


public class MainActivity extends ListActivity {
	Intent intent;
	TextView studentId;
	SqliteController controller = new SqliteController(this);
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ArrayList<HashMap<String, String>> studentList =  controller.getAllStudents();
		if(studentList.size()!=0) {
			ListView lv = getListView();
			lv.setOnItemClickListener(new OnItemClickListener() {
				  @Override 
				  public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					  studentId = (TextView) view.findViewById(R.id.studentId);
				  }
			}); 
			ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "studentId","studentName"}, new int[] {R.id.studentId, R.id.studentName}); 
			setListAdapter(adapter);
		}
	}
	public void showAddForm(View view) {
		Intent objIntent = new Intent(getApplicationContext(), NewStudent.class);
		startActivity(objIntent);
	}
}

Listing 8 defines MainActivity class that inherits ListActivity class and list all the inserted records into the database.

Next defines the android application configuration file AndroidManifestFile.xml file in Listing 9:

Listing 9: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javapapers.android.sqlitestorageoption"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.test.sqlite.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <activity
            android:name="com.test.sqlite.NewStudent"
            android:label="" >
        </activity>
        <activity
            android:name="com.test.sqlite.EditStudent"
            android:label="" >
        </activity>
    </application>

</manifest>

Listing 9 defines all the activity classes and package name with minimum and maximum android API level support to this written database application named “Student Database”.

Conclusion:

In this article, we learn about Sqlite android database and also learnt about its use into our database application. We learnt how to create database, database tables and also learnt inserting and displaying database table records into the main activity.

See also:



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login