Android SQLite Database

Android platform includes the SQLite embedded database and provides out of the box support to use it via Android APIs. In this tutorial we shall see how to get started with SQLite database in Android. SQLite is nothing but a relational database and our sql skills will help.

How to Use SQLite with Android?

To use SQLite in Android, a java class should be created as a sub class of SQLiteOpenHelper. This class will act as a database controller which will have the methods to perform the CRUD operations. This custom java class should override the methods named onCreate() and onUpgrade().

onCreate() method will be called for the first time when the Android application is run. First the database instance should be created using the method like getReadableDatabase() or getWritableDatabase() based on the type of access required. Android supports this method by providing in-built methods. For that, SQLiteQueryBuilder class should be imported.

Android SQLite Database

An Example for SQLite Database with Android

Download Source of Android SQLite Database

Lets have three Android Activity for List, Add and Edit operations and ensure that these are declared in manifest file. And then we need to create subclass of SQLiteHelper to manage SQLite database.

Setup the Database

DBController.java is going to be our custom java class that will manage the SQLite database. We should extend SQLiteOpenHelper and override the essential methods. The constructor is the hook that will be used to setup the database. While running the Android application, the database will be created for the first time.

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

Initial Database Table Creation and Upgrade

SQLiteOpenHelper provides callback methods and we should override it to get our job done. Those callback methods that we can override are onCreate(), onUpgrade(), onOpen() and onDowngrade(). And onCreate() and onUpgrade() are abstract methods and must be overridden.

onCreate(SQLiteDatabase database) – is the method which is called first time when the database is created and we need to use this method to create the tables and populate it as per the need.

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

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) – is the method called when upgrade is done. We can drop the datbase and reset if required.

	@Override
	public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
		String query;
		query = "DROP TABLE IF EXISTS animals";
		database.execSQL(query);
		onCreate(database);
	}

Ads by Google

Create, Read, Update and Delete (CRUD) Operations

We shall have other user defined methods to handle the sql CRUD operations. The animals table will be created when the onCreate() method is invoked while installing the application. For performing operaations like insert, update, the SQLiteDatabase instance should be created using the methods like getReadableDatabase() or getWritableDatabase(). ContentValues() are used to pass values to the query.

Create

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

Read

	public HashMap<String, String> getAnimalInfo(String id) {
		HashMap<String, String> wordList = new HashMap<String, String>();
		SQLiteDatabase database = this.getReadableDatabase();
		String selectQuery = "SELECT * FROM animals where animalId='"+id+"'";
		Cursor cursor = database.rawQuery(selectQuery, null);
		if (cursor.moveToFirst()) {
			do {
				wordList.put("animalName", cursor.getString(1));
			} while (cursor.moveToNext());
		}				    
		return wordList;
	}	

Update

	public int updateAnimal(HashMap<String, String> queryValues) {
		SQLiteDatabase database = this.getWritableDatabase();	 
		ContentValues values = new ContentValues();
		values.put("animalName", queryValues.get("animalName"));
		return database.update("animals", values, "animalId" + " = ?", new String[] { queryValues.get("animalId") });
	}

Delete

	public void deleteAnimal(String id) {
		Log.d(LOGCAT,"delete");
		SQLiteDatabase database = this.getWritableDatabase();	 
		String deleteQuery = "DELETE FROM  animals where animalId='"+ id +"'";
		Log.d("query",deleteQuery);		
		database.execSQL(deleteQuery);
	}

DBController.java

Complete code is as follows,

package com.javapapers.android.sqlitestorageoption;

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 DBController  extends SQLiteOpenHelper {
	private static final String LOGCAT = null;

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

	@Override
	public void onCreate(SQLiteDatabase database) {
		String query;
		query = "CREATE TABLE animals ( animalId INTEGER PRIMARY KEY, animalName TEXT)";
		database.execSQL(query);
		Log.d(LOGCAT,"animals Created");
	}
	@Override
	public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
		String query;
		query = "DROP TABLE IF EXISTS animals";
		database.execSQL(query);
		onCreate(database);
	}

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

	public int updateAnimal(HashMap<String, String> queryValues) {
		SQLiteDatabase database = this.getWritableDatabase();	 
		ContentValues values = new ContentValues();
		values.put("animalName", queryValues.get("animalName"));
		return database.update("animals", values, "animalId" + " = ?", new String[] { queryValues.get("animalId") });
	}

	public void deleteAnimal(String id) {
		Log.d(LOGCAT,"delete");
		SQLiteDatabase database = this.getWritableDatabase();	 
		String deleteQuery = "DELETE FROM  animals where animalId='"+ id +"'";
		Log.d("query",deleteQuery);		
		database.execSQL(deleteQuery);
	}

	public ArrayList<HashMap<String, String>> getAllAnimals() {
		ArrayList<HashMap<String, String>> wordList;
		wordList = new ArrayList<HashMap<String, String>>();
		String selectQuery = "SELECT  * FROM animals";
		SQLiteDatabase database = this.getWritableDatabase();
		Cursor cursor = database.rawQuery(selectQuery, null);
		if (cursor.moveToFirst()) {
			do {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("animalId", cursor.getString(0));
				map.put("animalName", cursor.getString(1));
				wordList.add(map);
			} while (cursor.moveToNext());
		}
		return wordList;
	}

	public HashMap<String, String> getAnimalInfo(String id) {
		HashMap<String, String> wordList = new HashMap<String, String>();
		SQLiteDatabase database = this.getReadableDatabase();
		String selectQuery = "SELECT * FROM animals where animalId='"+id+"'";
		Cursor cursor = database.rawQuery(selectQuery, null);
		if (cursor.moveToFirst()) {
			do {
				wordList.put("animalName", cursor.getString(1));
			} while (cursor.moveToNext());
		}				    
		return wordList;
	}	
}

NOTE: If you are interested only in the core database handling, with this the tutorial is over. What follows is, we are going to create a simple Android app which will provide user interface to operate on the database. Just giving a finishing touch to this database tutorial.

Launcher Activity

This activity will be launched first, on running this Android database application. The layout for this activity includes a ListView and its entry is supplied by the other xml file. This is done by the ListViewAdapter. The following xml files shows how to list data.

activity_main.xml

<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="Animals"
            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>

view_animal_entry.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    	<TextView
        android:id="@+id/animalId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />
 
       <TextView
           android:id="@+id/animalName"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_marginBottom="5dp"
           android:layout_marginTop="5dp"
           android:paddingLeft="6dip"
           android:paddingTop="6dip"
           android:textColor="#A4C739"
           android:textSize="17sp"
           android:textStyle="bold" />

</LinearLayout>

After designing the layout, the list of animals will be retrieved from the database using the java class and it should be the sub class of ListActivity. Then the list of data will be loaded into the design layout using the list adapter as shown below..

ListAdapter adapter = new SimpleAdapter( MainActivity.this,animalList, R.layout.view_animal_entry, new String[] { "animalId","animalName"}, new int[] {R.id.animalId, R.id.animalName}); 
setListAdapter(adapter);

On clicking each item shown in the ListView, then we will be redirected to a separate layout edit or delete the selected list item. For that, OnItemClickListener should be set to the ListView instance. This will be done by the following code.

ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
	@Override 
	public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
		animalId = (TextView) view.findViewById(R.id.animalId);
		String valAnimalId = animalId.getText().toString();					  
		Intent  objIndent = new Intent(getApplicationContext(),EditAnimal.class);
		objIndent.putExtra("animalId", valAnimalId); 
		startActivity(objIndent); 
	}
});

List Database

To add new entry into the animals database, we need to click the add icon shown at the top right corner of the animal list layout.

Add Activity

To Add new animal entry into the table, this activity is used. So the add layout should be designed with the list of widgets as shown as follows

add_new_animal.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 Animal"
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="Animal" />

<EditText
android:id="@+id/animalName"
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/animalName"
android:layout_below="@+id/animalName"
android:layout_marginTop="32dp"
android:text="Save"      
android:onClick="addNewAnimal" />
</RelativeLayout>
</LinearLayout>

while clicking the save button, the following method will be invoked.

public void addNewAnimal(View view) {
	HashMap<String, String> queryValues =  new  HashMap<String, String>();
	queryValues.put("animalName", animalName.getText().toString());
	controller.insertAnimal(queryValues);
	this.callHomeActivity(view);
}

In this method, the content of TextView is read and put into hashmap to send as an argument of the DBController methods to perform insert. After insert, the launcher activity will be called to see the recently added item.

Add to Database

The entire logic for the add activity is as shown in the following code

Newanimal.java

package com.javapapers.android.sqlitestorageoption;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import com.javapapers.android.sqlitestorageoption.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;


public class NewAnimal extends Activity{
	EditText animalName;
	DBController controller = new DBController(this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_new_animal);
		animalName = (EditText) findViewById(R.id.animalName);
	}
	public void addNewAnimal(View view) {
		HashMap<String, String> queryValues =  new  HashMap<String, String>();
		queryValues.put("animalName", animalName.getText().toString());
		controller.insertAnimal(queryValues);
		this.callHomeActivity(view);
	}
	public void callHomeActivity(View view) {
		Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
		startActivity(objIntent);
	}	
}

Edit Activity

It is similar to the add process, only difference is it displays the data from the database. The design and logic is shown by the following code.

activity_edit_animal.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="Edit Animal"
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/textView2"
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="Task" />

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

<requestFocus />
</EditText>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/animalName"
android:layout_below="@+id/animalName"
android:layout_marginTop="19dp"
android:onClick="editAnimal"
android:text="Edit" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_centerHorizontal="true"
android:onClick="removeAnimal"
android:text="Delete" />

</RelativeLayout>

</LinearLayout>

Editanimal.java

package com.javapapers.android.sqlitestorageoption;

import java.util.Calendar;
import java.util.HashMap;
import android.os.Bundle;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.EditText;
import com.javapapers.android.sqlitestorageoption.R;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

public class EditAnimal extends Activity{
	EditText animalName;
	DBController controller = new DBController(this);
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_animal);
		animalName = (EditText) findViewById(R.id.animalName);
		Intent objIntent = getIntent();
		String animalId = objIntent.getStringExtra("animalId");
		Log.d("Reading: ", "Reading all contacts..");
		HashMap<String, String> animalList = controller.getAnimalInfo(animalId);
		Log.d("animalName",animalList.get("animalName"));
		if(animalList.size()!=0) {
			animalName.setText(animalList.get("animalName"));
		}
	}
	public void editAnimal(View view) {
		HashMap<String, String> queryValues =  new  HashMap<String, String>();
		animalName = (EditText) findViewById(R.id.animalName);
		Intent objIntent = getIntent();
		String animalId = objIntent.getStringExtra("animalId");
		queryValues.put("animalId", animalId);
		queryValues.put("animalName", animalName.getText().toString());

		controller.updateAnimal(queryValues);
		this.callHomeActivity(view);
	}
	public void removeAnimal(View view) {
		Intent objIntent = getIntent();
		String animalId = objIntent.getStringExtra("animalId");
		controller.deleteAnimal(animalId);
		this.callHomeActivity(view);
	}
	public void callHomeActivity(View view) {
		Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
		startActivity(objIntent);
	}
}

Download Source of Android SQLite Database

Now we have a database! Ho – Ho – Ho! Go ahead and launch this app and enjoy access to SQLite database in Android.

This Android tutorial was added on 21/02/2013.

previous post: try-with-resources

next post: Observer Design Pattern

86 comments on “Android SQLite Database

    • after importing your projects i am getting errors. why ?

      • you getting errors because something is not right .

        Now get up log look at the log and correct the errors

        Rather than asking blindliy

  1. Dear Joe,
    I came acroos your blog, and its very useful. Could you please have a tag for Android, and all the posts are not tagged properly.

    Thanks
    Senthilkumar .J

    • Thanks Senthilkumar.

      Now I added ‘Android’ in menu. :-)

  2. Good one Its great that you have in to android.

  3. Hi Joe

    I am following your tutorials from past one year thank you so much for this kind of wonderful tutorials may i know which server is you are using for javapapers like(tomcat)?

  4. Hi Joe,

    will you please help me , i am irritating with one error in java in apachetomcat7 starting problem in eclipse , it is worked 4 days back well but now i dont know what happened its not working the error is like ” Server Tomcat v7.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.” I changed time in server editor but not solved i re-installed eclipse and server also same problem plzzzzzz help meeee . . . .

  5. Where is the main class? Plz upload the code for the main class

  6. Hi Joe,
    Please expand the coding window.Because not able to view frequently,each time scrolling it and saw that so oly.
    Thanks

  7. Just want to drop a note of thanks that and let you know your tutorials are awesome. Liked your blog design as well, very neat.

  8. hello sir when i am running my project,there is an error says illegal argument exception ?please help me for solving this error

  9. I need the same one, but instead of list view , i need it in table with two or more columns.
    how can i do it.?

  10. Joe please help me out..

    I need the same one, but instead of list view , i need it in table with two or more columns.
    how can i do it.?

    Awaiting ur reply

  11. Hello, For the first time i opened your site and when i saw this page i got very much impressed . i hope your tutorials will help me further. can u tell me if i wan to apply background image in android application, then what code would be use?
    Thanks

  12. Hi Joe,
    Your blog is very useful..can you tel me the difference between getreadabledatabase () and getwritabledatabase() ?

    Regards
    ~kavitha

  13. cannot add two values in animales table only one value add animalName please check to add more columns in this table

  14. Hi joe,i read your tutorial from last few months…plz provide tutorial for dropbox sync and google drive sync with android…

    • mmm…. thats a good idea. Soon I will write about them :-)

  15. Hi Joe,

    Thanks to Javapapers and for your effort.
    I have a problem in Android.
    Please provide some solution for this.
    I have 3 android applications which will use single database. When i am inserting one record from 1st application it will be reflect in 2nd application.
    For this in development process its working. But when i am installing the apk’s in mobile for 2nd apk giving error not installed. Why this error..?Please resolve myproblem.

    Thanks & Regards,
    Anush.

  16. this is semi help full can u add other crud parts, like updating and deleting

  17. how to add more than one two columns?

  18. Thanks for this helpful post !!I have been searching lots of sqlite tutorials etc but this one’s the best for a novice like me :)

  19. How can we a csv file and then insert it into sqlite database??

    pls help

  20. Hi joe,
    Thank you very much for nice post.I m new in java as well as Android.It helped me much to under stand the Sqlite functionality . But I have a question “if I want to add image of animal what should I change or add in following code

    public void addNewAnimal(View view) {
    HashMap queryValues = new HashMap();
    queryValues.put(“animalName”, animalName.getText().toString());
    controller.insertAnimal(queryValues);
    this.callHomeActivity(view);
    }

    I’hv already add imageView and modify ur animal table adding column name photo Blob. actually I want to know how can get image in Hashmap?

  21. after reading a csv file..how to insert it into sqlite database??

    pls help

  22. Very Easy tutorial for beginners…Thanks

  23. thank u so much for this tutorial.it is very helpful

  24. Excelent ,the best one!

    Joe,

    I want to run the same App but crating the database on the SD Card ,any suggestion?

    Thanks a lot.

  25. I feel nice to see ur website……. it’s nice nd keep it ONNNNNNNNNNNNNNNNN !!!!!!!!!!!!! i think some android quizes should also be here …. :-)

  26. Hi joe…Ur tutorial is really helpful and Ur website design is really cool….

  27. Hi Joe,

    I need a little assistance here. I am n00b to Android. I am developing an app for my office friends in which I need to sync my app data with a web app running on my office PC.

    Q1:- how and where to deploy my web app so that I can use it from my android app using internet.

    Q2:- how to write a sync code for my android app.

  28. i need the same one,but want imageview instead of listview

  29. hi joe good guide!!!! thank’s!!!
    I want add 2 Button for moveToNext row and moveToPrevious row…how to select next row for view on EditText???

    How TO DO???

  30. I got a problem in main.xml,I’m using the Eclipse IDE

  31. I am following your tutorials since I have started learning android and they are great…I appreciate you work..Thanks a lot for your tutorials

  32. Respected Sir how can we find the internal database of your application . where is data folder is placed in eclipse in which database placed
    Thanks

  33. nice tutorial joe! Helps me alot to get start for my new project :))Thanx!!

  34. its good.but i need code for access external database from android apps.if any one know help me to find some thing.

  35. I have been following your for the last 2 years….. I have seen myself developed quite a lot of knowledge in android as well as java… hats off……

  36. hi joe.. thanks a lot for your wonderful blog.. now I have developed a passion for these technologies for android and java..without this site I wouldn’t have climbed the ladder of success in software field.. once again thaks a lot..

  37. Sir,
    Your Description on the topics is very nice…

  38. Dear Sir,

    Above example is very good to understand.

    I am creating sales app on emulator using sqlite
    1)Could you please provide me an example for multiple tables?
    2)I also need a proper guidance on how to connect Sqlite with remote server database?

    Thank you

  39. Thanks a lot for the article. It gave a good insight on how to have an app with DB. But, I have few clarifications. I wish to manually retrieve the DB files from SQLiteManager to see if the tables are created properly? Where is the DB stored and how can it be located? In case of emulator or device, where is it stored? Pls suggest.

    Thanks in advance

    • I got the location of the DB.. It is stored in /data/data/package_name/databases.

      We can log in from emulator through adb shell, go to this location, and perform sql operations.

  40. Nice Tutorial.. Its help me lot. Thank you.

  41. iam getting an error in intent . can u pls say me what we have to write in mainActivity.java

  42. Sir Joe what if instead of textview i will make to be buttons where the data is displayed, can you give me specific code and where can i put it. tnx…

  43. hi.
    i am new to the android development please help me while i have been executed and added the names the list is not visible the error i am getting is package not installed

  44. Great site… I have a question for you though, what if I had (3) activities to be writable. (Ex. Wild Animals, Zoo Animals & Domestic Animals). Each activity has to display a list, but the list can’t display the same material throughout, but is stored in the database. How could I acheive this?

  45. It’s very helpfull……….thanx

  46. db.execSQL(“CREATE TABLE “+employeeTable+”
    (“+colID+” INTEGER PRIMARY KEY AUTOINCREMENT, “+
    colName+” TEXT, “+colAge+” Integer, “+colDept+”
    INTEGER NOT NULL ,FOREIGN KEY (“+colDept+”) REFERENCES
    “+deptTable+” (“+colDeptID+”));”);

    Sir in the above code an error occurs:”string literal is not closed by a double quote”

    how can i fix this problem…..pls help!!!

  47. I am writing an app that queries an already created database (read only).
    How do I connect to the database via a file that is already created?
    All examples I have seen create the database on the fly.

  48. Where does androidsqlite.db locate? in what folder?

  49. easy way to learn android & tel best web site..

  50. I am beginner to android! i tried this example and dint understand the ListAdapter what is ‘animalList’(data) under view?

  51. sir its a good example in sqlite but can you send any foreign key concept example publish..plz sir help me

  52. hi..sir
    i am new for andorid..i know very well java..but sir i tired this example..but i run my application the give me error application stop unexptedly please try again on emulator..plz help me..i tired before one week..stil not run sucessfuly my aplication..

  53. Can i view the database in DDMS using your project?

    Thanks
    shru

  54. wonderful Article…. very helpful to me…

  55. How could I use this in Visual Studio? No java files.

  56. Hi Joe

    Thanks for this useful post:)

    In all of your CRUD methods above, except insertAnimal method, don’t others need to close SQLitedatabase instance like this? “database.close();”

    Thank you!

  57. Dear Joe, Thank you. It is a very nice tutorial.

  58. Dear Joe

    Nice post for learners like me. Can you please help me with why I am getting this error? Thanks in advance. All I am trying is to click checkboxes in a list and save them in SQLite. When I am displaying in a toast the selected items it is showing correctly. But when I am trying to show items that are stored in SQLite in toast, it is showing repetitive long list of numbers: Here is the code:

    btn5.setOnClickListener(new Button.OnClickListener(){
    @Override public void onClick(View v) {

    String selected = “”;
    int getClicks = lv.getCount();
    SparseBooleanArray sparseBooleanArray = lv.getCheckedItemPositions();
    for(int i = 0; i < getClicks; i++){
    if(sparseBooleanArray.get(i)) {
    selected += lv.getItemAtPosition(i).toString() + "\n";
    pl.execSQL("INSERT INTO phonelist (MOBILE) VALUES ('"
    + selected + "');");
    }
    }
    getPhoneList();
    Toast.makeText(ContactListActivity.this, selected, Toast.LENGTH_LONG).show();
    Toast.makeText(ContactListActivity.this, addedPhoneList.toString(), Toast.LENGTH_LONG).show();
    }
    });
    }

    private void getPhoneList(){

    Cursor c = pl.rawQuery("SELECT * FROM phonelist", null);
    if (c != null) {
    if (c.moveToFirst()) {
    do {
    String mobi = c.getString(c
    .getColumnIndex("MOBILE"));
    addedPhoneList.add(mobi);
    } while (c.moveToNext());
    }
    }

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>