You are on page 1of 25

How to retrieve data from a SQLite database in Android | Anu's crazy ...

1 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Anu's crazy world

How to retrieve data from a SQLite database in Android


Posted on December 19, 2011

Hello Android fellows let us Retrieve today

I mean lets learn how to retrieve data from a SQLite database in

Android. This is the second part of the SQLite blog series. In my previous post I have shown you how to insert
data to a SQLite database. I am continuing from there. So please have a look on my previous post before you go
through this post directly.
If you guys can remember, you did not able to see anything when we started our undergraduate GPA Android
application last time. But after coding to retrieve data form the SQLite database, you will be able to see the
existing or the registered undergraduates names in our first UI (User Interface) as shown below.

Figure 1

Hey you can only see names of the undergraduates. What happen to the other details? :O Dont worry and dont
be hurry, you can see those details when you click on a name of an undergraduate as in Figure 2

Figure 2

Enough fancy stories. Let me explain the logic and the techniques behind this. The basic logic is similar to what we
have done when we inserting data. That means to contact the database we need a helper class which extends
the SQLiteOpenHelper class. Then we need a readable SQLite database. If you can remember my previous post,
there we have used a writable database because we wanted to insert data. But today we are going to retrieve data.
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

2 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

OK, now we have a SQLite database that can be read. How are we going to read it? Cursor class will give you a
hand to fulfill your target. By using a while loop, we can traverse each and every raw of the particular table. Lets
look at the code now. The comment in the code is more clear than the explanation here, because I have explain
almost all the lines with comments.

package com.anuja.sqlite;
import java.util.ArrayList;
import java.util.List;
import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Intent;
android.database.Cursor;
android.database.sqlite.SQLiteDatabase;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.AdapterView;
android.widget.AdapterView.OnItemClickListener;
android.widget.ArrayAdapter;
android.widget.Button;
android.widget.ListAdapter;
android.widget.ListView;
android.widget.Toast;

public class UndergraduateListActivity extends Activity implements OnClickListener, OnItemClickListener {


private ListView uGraduateNamesListView;
private Button addNewUndergraduateButton;

// We need some kind of Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter uGraduateListAdapter;
// We need this while we read the query using Cursor and pass data
private ArrayList<UndergraduateDetailsPojo> pojoArrayList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.names_listview);
// Initialize UI components
uGraduateNamesListView = (ListView) findViewById(R.id.uGraduateListView);
uGraduateNamesListView.setOnItemClickListener(this);
addNewUndergraduateButton = (Button) findViewById(R.id.namesListViewAddButton);
addNewUndergraduateButton.setOnClickListener(this);
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();

// For the third argument, we need a List that contains Strings.


//We decided to display undergraduates names on the ListView.
//Therefore we need to create List that contains undergraduates names
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList()
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
@Override
public void onClick(View v) {
Intent addNewUndergraduateIntent = new Intent(this, AddNewUndergraduateActivity.class);
startActivity(addNewUndergraduateIntent);
}
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

3 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

// To create a List that contains undergraduate names, we have to read the SQLite database
//We are going to do it in the separate method
public List<String> populateList(){
// We have to return a List which contains only String values. Lets create a List first
List<String> uGraduateNamesList = new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
// Then we need to get a readable database
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, Stri
Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null,
// Above given query, read all the columns and fields of the table
startManagingCursor(cursor);

// Cursor object read all the fields. So we make sure to check it will not miss any by looping th
while (cursor.moveToNext()) {
// In one loop, cursor read one undergraduate all details
// Assume, we also need to see all the details of each and every undergraduate
// What we have to do is in each loop, read all the values, pass them to the POJO cla
//and create a ArrayList of undergraduates
String ugName = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAM
String ugUniId = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NA
double ugGpa = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_NAM
// Finish reading one raw, now we have to pass them to the POJO
UndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();
ugPojoClass.setuGraduateName(ugName);
ugPojoClass.setuGraduateUniId(ugUniId);
ugPojoClass.setuGraduateGpa(ugGpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojoArrayList.add(ugPojoClass);
// But we need a List of String to display in the ListView also.
//That is why we create "uGraduateNamesList"
uGraduateNamesList.add(ugName);
}
// If you don't close the database, you will get an error
sqliteDatabase.close();
return uGraduateNamesList;
}

// If you don't write the following code, you wont be able to see what you have just insert to the databa
@Override
protected void onResume() {
super.onResume();
uGraduateListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}

// On ListView you just see the name of the undergraduate, not any other details
// Here we provide the solution to that. When the user click on a list item, he will redirect to a page w
//he can see all the details of the undergraduate
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Clicked on :" + arg2, Toast.LENGTH_SHORT).show();
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

4 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

// We want to redirect to another Activity when the user click an item on the ListView
Intent updateDeleteUgraduateIntent = new Intent(this, UpdateDeleteUndergraduateActivity.class

// We have to identify what object, does the user clicked, because we are going to pass only clic
// What we are going to do is, get the ID of the clicked item and get the values from the ArrayLi
//same array id.
UndergraduateDetailsPojo clickedObject = pojoArrayList.get(arg2);
// We have to bundle the data, which we want to pass to the other activity from this activity
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedUgraduateName", clickedObject.getuGraduateName());
dataBundle.putString("clickedUgraduateUniId", clickedObject.getuGraduateUniId());
dataBundle.putDouble("clickedUgraduateGpa", clickedObject.getuGraduateGpa());
// Attach the bundled data to the intent
updateDeleteUgraduateIntent.putExtras(dataBundle);
// Start the Activity
startActivity(updateDeleteUgraduateIntent);
}
}

Above is the full code for retrieve. I will explain the scenario from where I have stopped. Now you have the data
set which we have read from the SQLite database. You have a ListView that you can visualize the out put to the
user. You can combine the UI component and the data set by using an Adapter. Here I have used an
ArrayAdapter.
Figure 2 relate with a new Activity. You can see, that I have call a new Activity with in the OnItemClick method.
Those things I have covered in my previous blogs. Therefore dont ask me to repeat it here
I think this is more than enough for todays blog post. I will upload the source code to GitHub after completing
Update and Delete functions as well.
Wish all of you a Merry Christmas!!!
About these ads

You May Like


1.

Rate this:

17 Votes
Share this:

Be the first to like this.

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

5 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Related

How to insert data in to a SQLite database in


Android

How to Update and Delete data from SQLite


database in Android

How to retrieve data from a SQL table in


PHP

About anujarosha
An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
View all posts by anujarosha

This entry was posted in Android Examples and tagged Android, Cursor, Retrieve, SQLite, SQLiteOpenHelper. Bookmark the permalink.

59 Responses to
kalpataru Nayak says:
December 28, 2011 at 4:03 pm

i want to know about your UpdateDeleteUndergraduateActivity.


help me !
Reply

anujarosha says:
December 28, 2011 at 7:44 pm

Hi Nayak,
It is an Activity class. Therefore you should have an XML layout relate to that class. Figure 2 shows the UI for that
layout. What I have done in the background is getting the Bundle content and set the values of the EditText fields
accordingly. If you have no idea how to use Bundle class, please go through this post
(http://anujarosha.wordpress.com/2011/03/07/how-to-get-the-content-that-user-type-in-a-edittext-field-in-oneactivity-to-another-activity-in-android/)
I will upload the full source code to GitHub after I have completed the Update and Delete function blog post.
Good luck
Reply

avital says:
May 6, 2012 at 1:49 am

Hi,
Thanks for the article. When will the source code be available?

kalpataru Nayak says:


December 29, 2011 at 11:08 am

Hi & Thanks Anujarosha,


I want to know that if someone wants to delete some name with related information from the LISTview and automatic row
updation means rows without any gap of blank row .how we could do that .
help me !
thanks in advance
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

6 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Reply

anujarosha says:
December 29, 2011 at 7:32 pm

Hi Nayak,
You are asking about Delete function which is going to be my next blog post

I will definitely show you the

source code. Till then take an effort. Ill give you a hint. Removing an item in the middle of the ListView means,
removing that items whole data from the SQLite database.
- Put a Delete button in the XML file in Figure 2
- Get values given in the EditText fields
- Use SQLiteOpenHelper
- Use SQLiteDatabase
- String[] for whereClauseArgument
- Finally use the delete query
Good luck!!!
Reply

kirti says:
February 8, 2012 at 1:54 pm

hi my code is fine on the emulator but when i used the api file on real device it will not show the retriving data of database
Reply

anujarosha says:
February 9, 2012 at 7:29 pm

hi Kirti,
I have checked the source again with a device.
Model : Acer A500
Android Version : 3.2.1
It is working for me. Can you please send me more details about your issue?
Reply

kirti says:
February 9, 2012 at 5:51 pm

hi
Is thair any setting have to do on my android phone to show the data of database.When i used to installed the apk file into my
android phone.It was not displayed any data of database.
Reply

anujarosha says:
February 9, 2012 at 7:36 pm

hi Kirti,
As far as I know, you no need to do any kind of settings. We retrieve data using our own application. You cant see
the raw database just like we can see in phpMyAdmin in your REAL device. But you can see in the emulator with
the help of SQLite browser.

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

7 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Reply

kirti says:
February 10, 2012 at 1:43 pm

hi thnks
i got the problem i was thought that it used static database table on every device that,s why i did not insert
the values by using the edit text & because of that the the value was that shown. actually i want to used the
staic data everywhere.

Aqeela says:
March 6, 2012 at 10:53 pm

Hi,
I got a problem when adding more columns saying dat no column inserted when I have specified that column. Can you
provide your email address so that I can attach the database file, I would be grateful if you can look at it and see what the
issues is. I have researched but unable to find the solution.
Reply

Shipra says:
March 7, 2012 at 3:39 pm

Hello,
I am using SQlite Browser to create data and insert data manually. now i want to retrive data from my table. I got error again
and again. i am new in android. can u help me please.
Reply

anujarosha says:
March 7, 2012 at 7:21 pm

Hi Shipra,
Post your Error or more detials about your error. We will try to solve that. You said that you have insert data to the
database using SQLite browser. Hope you have push that file back to the device/emulator before you run your
code in Android.
Reply

Dee says:
March 13, 2012 at 9:49 pm

Awesome tutorial. Good job!!!


Reply

anujarosha says:
March 14, 2012 at 10:39 am

Thank you Dee


Reply

anisha fernandes says:


March 26, 2012 at 4:21 pm

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

8 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

hi anujarosha
nice tutorial. but i hav a prob.. when i tried the code it gave me errors. as is the activity terminates on starting..
can u help mi please.
package com.pollyroid;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
public class display_quest extends Activity implements OnClickListener {
private ListView questlist;
private Button Button1;
// We need some kind of Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter ListAdapter;
// We need this while we read the query using Cursor and pass data
private ArrayList pojoArrayList;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_quest);
Button1 = (Button) findViewById(R.id.button1);
Button1.setOnClickListener(this);
pojoArrayList = new ArrayList();
// For the third argument, we need a List that contains Strings.
//We decided to display undergraduates names on the ListView.
//Therefore we need to create List that contains undergraduates names
ListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());
questlist.setAdapter(ListAdapter);
}
@Override
public void onClick(View v) {
Intent inte2 = new Intent(this, Create_poll.class);
startActivity(inte2);
}
// To create a List that contains questions, we have to read the SQLite database
//We are going to do it in the separate method
public List populateList(){
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

9 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

// We have to return a List which contains only String values. Lets create a List first
List questlist = new ArrayList();
// First we need to make contact with the database we have created using the DbHelper class
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
// Then we need to get a readable database
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME, null, null, null, null, null, null);
// Above given query, read all the columns and fields of the table
startManagingCursor(cursor);
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while (cursor.moveToNext()) {
// In one loop, cursor read one quest all details
// Assume, we also need to see all the details of each and every quest
// What we have to do is in each loop, read all the values, pass them to the POJO class
//and create a ArrayList of quest
String quest = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_QUEST));
String option1 = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_OPTION1));
String option2 = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_NAME_OPTION2));
// Finish reading one raw, now we have to pass them to the POJO
DetailsPojo PojoClass = new DetailsPojo();
PojoClass.setquest(quest);
PojoClass.setoption1(option1);
PojoClass.setoption2(option2);
// Lets pass that POJO to our ArrayList which contains quest as type
pojoArrayList.add(PojoClass);
// But we need a List of String to display in the ListView also.
//That is why we create questlist
questlist.add(quest);
}
// If you dont close the database, you will get an error
sqliteDatabase.close();
return questlist;
}
// If you dont write the following code, you wont be able to see what you have just insert to the database
@Override
protected void onResume() {
super.onResume();
pojoArrayList = new ArrayList();
ListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());
questlist.setAdapter(ListAdapter);
}
@Override
protected void onStart() {
super.onStart();
pojoArrayList = new ArrayList();
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

10 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

ListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());


questlist.setAdapter(ListAdapter);
}
}
Reply

anujarosha says:
March 26, 2012 at 9:27 pm

Hello Anisha,
Submit your error in LogCat. It will help me to identify the error line.
Furthermore please concentrate the JAVA conventions even though they are not producing errors.
Reply

anisha fernandes says:


March 27, 2012 at 7:38 am

03-27 07:37:15.559: D/AndroidRuntime(282): Shutting down VM


03-27 07:37:15.559: W/dalvikvm(282): threadid=1: thread exiting with uncaught exception
(group=0x4001d800)
03-27 07:37:15.579: E/AndroidRuntime(282): FATAL EXCEPTION: main
03-27 07:37:15.579: E/AndroidRuntime(282): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.pollyroid/com.pollyroid.display_quest}: java.lang.NullPointerException
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-27 07:37:15.579: E/AndroidRuntime(282): at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 07:37:15.579: E/AndroidRuntime(282): at android.os.Looper.loop(Looper.java:123)
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.ActivityThread.main(ActivityThread.java:4627)
03-27 07:37:15.579: E/AndroidRuntime(282): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 07:37:15.579: E/AndroidRuntime(282): at java.lang.reflect.Method.invoke(Method.java:521)
03-27 07:37:15.579: E/AndroidRuntime(282): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-27 07:37:15.579: E/AndroidRuntime(282): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-27 07:37:15.579: E/AndroidRuntime(282): at dalvik.system.NativeStart.main(Native Method)
03-27 07:37:15.579: E/AndroidRuntime(282): Caused by: java.lang.NullPointerException
03-27 07:37:15.579: E/AndroidRuntime(282): at
com.pollyroid.display_quest.onCreate(display_quest.java:39)
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-27 07:37:15.579: E/AndroidRuntime(282): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-27 07:37:15.579: E/AndroidRuntime(282): 11 more

anujarosha says:
March 27, 2012 at 9:13 am

Hey Anisha,
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

11 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Look at the following lines in LogCat out-put.

03-27 07:37:15.579: E/AndroidRuntime(282): Caused by: java.lang.NullPointerException


03-27 07:37:15.579: E/AndroidRuntime(282): at
com.pollyroid.display_quest.onCreate(display_quest.java:39)

When you click on the last line of the above two mentioned lines, you will be redirect to the line where you
get the NullPointerException. Another way is, go to the mentioned code line. In this scenario it is line 39.
But when I copy your code in the IDE and check what is in the line 39, it shows me the comments which is
something that wont make errors.
Things I have noticed are, you have to check whether you get the result from the SQLite database.
ListAdapter is a default Android class and you have made a variable from that exact name. Please
replace first letter with simple l. You will get NullPointerException when your ArrayList is empty. So
check whether your Array is filled with data.
Good luck!!!

AndroidDev says:
April 10, 2013 at 10:56 am

Hey Anisha, I am just following code for an error I am getting. Where are you creating DetailsPojo in your code?
Reply

Mike says:
March 29, 2012 at 5:30 am

Is it possible for you to upload the xml for the listview? Im unsure of some your initialize ui elements
Reply

anisha fernandes says:


March 30, 2012 at 10:27 am

hey thanks a lot. it finaallly worked!:)


Reply

anujarosha says:
March 30, 2012 at 7:28 pm

Hey Anisha,
You are welcome
Reply

Diwakar DS says:
April 9, 2012 at 9:58 am

Hi m also getting the same error bt i cant debug it. plsssssssssss send me the full source code including xml
and manifest file to dis mail id diwakar.ds13@yahoo.com.. pls pls pls
Thnx a lot
Reply

chhavi says:
April 5, 2012 at 8:30 pm

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

12 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

unable to retreive the datainsertion is working fine..bt unable to retreiveNothing is bein displayed in the emmulatorcn u
help??
Reply

chhavi says:
April 5, 2012 at 11:25 pm

Hey i gt it rghtthr ws prob wth manifest file..


Reply

Diwakar DS says:
April 9, 2012 at 9:53 am

Hey send me the full code please to dis mail id.. Diwakar.ds13@yahoo.com.
Thnx.

aki says:
May 6, 2012 at 8:31 pm

Can you please send me the full codes too??.. I need it badly .. Thanks in a million..
akiville23@gmail.com
Reply

avital says:
May 8, 2012 at 8:40 pm

Can you pls also send me the full source code? Thanks.
deanslaw@hotmail.com
Reply

Yasmin says:
May 11, 2012 at 7:14 pm

Would you please post the link of the source code at GitHub for everyone to use?
Would be very grateful. Thanks
Reply

Priyanka says:
May 20, 2012 at 10:12 pm

All right, Good one, but what to do if we want to show multiple TextViews inside the Listview using Sqlite, How can we
achieve that?
Reply

Rahul G says:
June 4, 2012 at 1:46 pm

Thanks a lot .. It was really helpful


Reply

Anu says:
June 10, 2012 at 4:33 pm

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

13 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Hi Anujarosha,Ur blog had helped me a lot. Thanks a lotBut I had one question.
Instead of using the sqlite database, can we use a remote or a server database..? If yes, how can we do the same insertions,
updations and deletions with such a remote database. And the searching has to be done from the android mobile..Please help
me
Reply

zubi says:
June 15, 2012 at 5:01 pm

i cant retrive values from my database as i used array adapter to insert values
Reply

Girish says:
August 16, 2012 at 11:39 am

Awesome blogThanks anuja..!!


Reply

Girish says:
August 16, 2012 at 1:28 pm

In this line:
arrivalListAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1,populateList());
This line is perfect, but what if I have to introduce my custom adapter with my own layout (I donot want default layout) in
this step, how will it be written?? Please help.
Reply

anujarosha says:
August 16, 2012 at 7:27 pm

Hi Girish,
Ill just give you some hints because Im writing this reply in a rush. You can create your own Adapter class. But
that class may extends appropriate ***Adapter class. As an example, if you are having an ExpandableList, you
have to extends ExpandableListAdapter.
You can have your own layout. Just check LayoutInflater class, View class and inflate() method.
Good luck
Reply

vijay says:
December 5, 2013 at 12:13 pm

fine nice
Reply

Sneha says:
August 28, 2012 at 4:19 pm

E/Database(526): Error inserting undergraduate_name_column=SNEHA undergraduate_uni_id_column=ptwmjg


E/Database(526): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
E/Database(526): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

14 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

E/Database(526): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
E/Database(526): at
android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)E/Database(526): at
android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
E/Database(526): at
com.sneha.addnewnumber.AddNewUndergraduateActivity.insertUndergraduate(AddNewUndergraduateActivity.java:88)
E/Database(526): at
com.sneha.addnewnumber.AddNewUndergraduateActivity.onClick(AddNewUndergraduateActivity.java:65)
E/Database(526): at android.view.View.performClick(View.java:2485)
E/Database(526): at android.view.View$PerformClick.run(View.java:9080)
E/Database(526): at android.os.Handler.handleCallback(Handler.java:587)
E/Database(526): at android.os.Handler.dispatchMessage(Handler.java:92)
E/Database(526): at android.os.Looper.loop(Looper.java:123)
E/Database(526): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/Database(526): at java.lang.reflect.Method.invokeNative(Native Method)
E/Database(526): at java.lang.reflect.Method.invoke(Method.java:507)
E/Database(526): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/Database(526): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/Database(526): at dalvik.system.NativeStart.main(Native Method)
I justuse ur code as it is..stil dis error
plz solve dis..
Reply

Sneha says:
August 28, 2012 at 4:23 pm

plz send me whole combined code of inserting and retreiving data wid xml file..m unsure if m doin rite or not??
Reply

Heer Sharma says:


October 3, 2012 at 1:37 am

Hi m also getting the same error bt i cant debug it. plsssssssssss send me the full source code including xml and
manifest file to dis mail id heer.sharma21@gmail.com.. pls pls pls
Thnx a lot
Reply

anujarosha says:
October 3, 2012 at 9:09 pm

For everybody who are asking for XML,


It is not a big deal for me to upload the XML files to GitHub. But what I think is, a good programmer is NOT a person who
just copy and paste others code without understanding the concept. I have posted the UI and also all the logic codes that
important to this application which is more than enough for the people who wants to learn something
Good luck
Reply

Sneha says:
October 4, 2012 at 11:15 am

thank u for ur rply.. bt i hv completed d code a month ago..


bt again thanx

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

15 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Reply

vaishnavi says:
October 5, 2012 at 12:15 am

Hi. nice tutorial. it helped me a lot


pls tell me how to retrieve data from database using a particular field for example if i wnt to view only ece students detail
using spinner r search box. and the details of ece students should be view on listview . pls help me .
pls send source code to my mail id vaishu.sylph@gmail.com . im waiting for ur reply
thanks in advance.
Reply

rekha says:
October 9, 2012 at 12:11 pm

please help me to get values of field that is in database declared as string but set method of that field accept list
Reply

anujarosha says:
October 9, 2012 at 11:19 pm

Hi Rekha,
Not clear about your question. Please explain more.
Reply

mona says:
October 25, 2012 at 12:48 pm

hi!!
i am working on a project regarding feedback of students..
i need to create a database insert values and display a few fields when needed in listview. I have defined a class dbhelper in
which database is created n my main activity have tried to retrieve the data.
the code doesnt show any error but when i tried running the app..its giving an error an force closing..
pls help me!!
Reply

Sheila says:
October 28, 2012 at 9:53 am

Hi, i want to put more than uGraduateName in the listview?


for example the GPA also must be in the listview.. in the sub item.
Reply

Namita Tare. says:


December 3, 2012 at 11:17 am

Hi anujarosha , i wanted to retrieve the particular values from my database after matching name column parameter. But am
unable to retrieve it.could you please help me.My code is,
ClientInfoAct.java
package com.me.android.placefinder;
import java.util.ArrayList;
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

16 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class ClientInfoAct extends Activity {
Intent i;
EditText et,et1,et2,et3;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_info);
}
public void enter(View v){
et=(EditText)findViewById(R.id.name1);
et1=(EditText)findViewById(R.id.n1);
et2=(EditText)findViewById(R.id.c1);
et3=(EditText)findViewById(R.id.a1);
DBConn helper=new DBConn(getApplicationContext(),MyPFDB,null,1);
ArrayListmyNames=helper.getNames();
for(String s:myNames){
if(s.equals(et.getText().toString())){
et1.setText(s);
//PLEASE HELP ME OVER HERE HOW TO RETRIEVE NUMBER AND ADDRESS VALUES OF MATCHING NAME.
}
}
}
public void deleteCon(View v){
et=(EditText)findViewById(R.id.name1);
DBConn helper=new DBConn(getApplicationContext(),MyPFDB,null,1);
helper.deleteContact(et.getText().toString());
ArrayListmyNames=helper.getNames();
for(String a:myNames){
Toast.makeText(getApplicationContext(), a, Toast.LENGTH_LONG).show();
}
}
}
//i want to display retrieved values in edit texts after entering name.
activity_client_info.xml
Reply

jiji says:
December 30, 2012 at 10:00 pm

hai..thanks for the tutorial..but i have face a problem when i want to add the details..first when im still not put this retrieved
code..ive no problem with adding..but when i used retrieved code..i cant add any info..please help me!
Reply

jiji says:
December 31, 2012 at 2:20 pm

Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

17 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

hey anuja..i have used your tutorial but the problem is the database is not there..means the database is not created..can u
please help me
Reply

Ali says:
March 28, 2013 at 1:20 pm

Hi Anujarosha,Your blog is very helpful, Thanks a lot can u please help me how to retrieve images from SQLite database?
If yes, how can we do the same insertions, updations and deletions with such database. And the searching has to be done
from the android mobile..Please help me
Reply

Abhijit Ghosh says:


May 25, 2013 at 6:36 am

Thanks for your valuable job man..Thanks once again


Reply

udhayabanu says:
October 4, 2013 at 3:39 pm

anu,
I am new to android.
Please help me in the following code wherein i am extracting name column which has more than 1 record from mysql using
user input and on click of name it should display other columns including this column in another activity in android.
package com.example.pharmacy;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import com.example.pharmacy.R;
import com.example.pharmacy.SinglePlace;
import com.example.pharmacy.CustomHttpClient;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
//import android.widget.AdapterView.OnClickListener;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
EditText byear; // To take birthyear as input from user
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

18 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Button submit;
TextView tv;
// ListView tv;
// TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding JSON
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or
network access on the applications main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
byear = (EditText) findViewById(R.id.editText1);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// tv = (ListView) findViewById(R.id.list);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the name birthyear and its value submitted by user
ArrayList postParameters = new ArrayList();
// define the parameter
postParameters.add(new BasicNameValuePair(search,
byear.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
//http://129.107.187.135/CSE5324/jsonscript.php, // your ip address if using localhost server
http://www.sablabs.com/Calendar/pharmacy1.php, // in case of a remote server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
// String[] result = response;
//parse json data
try{
returnString = ;
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","search: "+json_data.getString("search")+
",name: "+json_data.getString("name")+
",address1: "+json_data.getString("address1")+
",address2: "+json_data.getString("address2")+
",address3: "+json_data.getString("address3")+
",telephone: "+json_data.getString("telephone")
);
//Get an output to the screen
returnString += "\n" + json_data.getString("name") ;
}
}
catch(JSONException e){
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

19 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

Log.e("log_tag", "Error parsing data "+e.toString());


}
try{
//((TextView) tv).setText(returnString);
tv.setText(returnString);
}
catch(Exception e){
Log.e("log_tag","Error in Display!" + e.toString());;
}
}
catch (Exception e) {
Log.e("log_tag","Error in http connection!!" + e.toString());
}
}
});
// tv.setAdapter(adapter);
//tv.setOnClickListener(new View.OnClickListener(){
tv.setOnClickListener(new OnClickListener() {
//@Override
//public void onItemClick(AdapterView parent, View view,
// int position, long id) {
@Override
public void onClick( View view) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.showresult)).getText().toString();
Bundle b = new Bundle();
//b.putString(result.name, reference);
b.putString(result, reference);
// b.putString(result.address2, reference);
//b.putString(result.address3, reference);
//b.putString(result.telephone, reference);
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlace.class);
in.putExtras(b);
// Sending place refrence id to single place activity
// place refrence id used to get Place full details
startActivity(in);
}
});
}
}
Reply

jalu says:
January 20, 2014 at 11:54 am

hello
i create sqlite database and also insert data into database but i cant fetch the value from databasethis is my DBAdapter.java
if any one know plz help me..
public class DBAdapter extends SQLiteOpenHelper {
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

20 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

private static final int DATABASE_VERSION = 1;


private static final String DATABASE_NAME = BalesUtaro.db;
public static final String TABLE_NAME=BaleTable;
public static final String COLUMN_ID=Id;
public static final String COLUMN_LOOSERUE=LooseRue;
public static final String COLUMN_KAPASIYAUTARO=KapasiyaUtaro;
public static final String COLUMN_EXPENSE=Expense;
public static final String COLUMN_KAPASRATEFROM=KapasRateFrom;
public static final String COLUMN_KAPASRATETO=KapasRateTo;
public static final String COLUMN_KAPASIYARATEFROM=KapasiyaRateFrom;
public static final String COLUMN_KAPASIYARATETO=KapasiyaRateTo;
@SuppressLint(SdCardPath)
private static String DB_PATH = /data/data/com.bales_utaro/databases/;
private final Context myContext;
private SQLiteDatabase myDB;
private SQLiteStatement insertStmt;
/**
* Check db.If it exists,open it else create db.
*
* @param context
*/
public DBAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
boolean dbexist = checkdatabase();
if (dbexist) {
Log.d(DataBase, Database exists);
openDataBase();
} else {
Log.d(DataBase, Database doesnt exist);
try {
createdatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DataBase, Upgrading database from version + oldVersion
+ to + newVersion + , which will destroy all old data.);
onCreate(db);
}
/**
* Database creation
* @throws IOException
*/
public void createdatabase() throws IOException {
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

21 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

boolean dbexist = checkdatabase();


myDB = this.getReadableDatabase();
if (dbexist) {
//Log.d(DataBase, Database exists);
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error(Error copying database);
}
}
}
/**
* Check Database whether it exists or not
* @return
*/
private boolean checkdatabase() {
boolean checkdb = false;
try {
String myPath = DB_PATH + DATABASE_NAME;
File dbfile = new File(myPath);
checkdb = dbfile.exists();
} catch (SQLiteException e) {
e.printStackTrace();
//Log.d(DataBase, Database doesnt exist);
}
return checkdb;
}
/**
* Copy Database from www folder to phone memory
*
* @throws IOException
*/
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets()
.open( + DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
/**
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

22 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

* Open Database
*
* @return
* @throws SQLException
*/
public SQLiteDatabase openDataBase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
try {
myDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (Exception e) {
e.printStackTrace();
}
return myDB;
}
public void insertIntoDatabase(String[] columns, Object[] values){
myDB.beginTransaction();
this.insertRow(TABLE_NAME, columns, values);
myDB.setTransactionSuccessful();
myDB.endTransaction();
close();
}
/**
* Insert row in DB.
*
* @param table
* @param columns
* @param values
*/
public void insertRow(String table, String[] columns, Object[] values) {
String columnName = ;
String valueColumn = ;
if (columns != null && columns.length > 0) {
for (int i = 0; i < columns.length; i++) {
if (i == 0) {
columnName = columnName + "(";
valueColumn = valueColumn + "(";
}
columnName = columnName + columns[i];
valueColumn = valueColumn + values[i];
if (i != columns.length 1) {
columnName = columnName + ",";
valueColumn = valueColumn + ",";
} else {
columnName = columnName + ")";
valueColumn = valueColumn + ")";
}
}
String sql = "INSERT INTO " + table + columnName + " VALUES "
+ valueColumn;
//Log.d("Query", "Query is " + sql);
this.insertStmt = this.myDB.compileStatement(sql);
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

23 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

this.insertStmt.executeInsert();
this.insertStmt.close();
}
}
/**
* Select query for DB.
*
*/
public JSONArray selectFromDB() {
JSONArray returnData = new JSONArray();
try {
//prepare query as per your need
Cursor results = myDB.query(TABLE_NAME, null, null,
null, null, null, null);
if (results.moveToFirst()) {
while (!results.isAfterLast()) {
JSONObject row = new JSONObject();
for (int c = 0; c < results.getColumnCount(); c++) {
row.put(results.getColumnName(c), results.getString(c));
}
returnData.put(row);
results.moveToNext();
}
}
results.close();
} catch (Exception e) {
e.printStackTrace();
}
return returnData;
}
/**
* Close DB.
*/
@Override
public synchronized void close() {
if (myDB != null)
myDB.close();
super.close();
}
}
thanks in advance!!!!
Reply

madhankumar says:
January 21, 2014 at 4:53 pm

how to store data in android program , and how to connect the data with main activity.
Reply

surya says:
February 14, 2014 at 6:08 pm

plz help me how to retrive the data in listview by clicking button


package com.example.chandardt;
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

24 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
SQLiteDatabase db1 = null;
private static String DBNAME = surya.db;
Button b1,btn3;
EditText e,y;
Editable g;
TextView t;
LinearLayout Linear;
String s=chandra;
TextView tvw;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e = (EditText) findViewById(R.id.editText1);
b1 = (Button) findViewById(R.id.button1);
btn3 = (Button)findViewById(R.id.button3);
db1 = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
db1.execSQL(CREATE TABLE IF NOT EXISTS+ s +(NAME unique VARCHAR); );
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
g=e.getText();
try{
db1.execSQL(INSERT INTO chandra(NAME) VALUES (+g+));
}
catch(Exception e){
System.out.println(e);
}
}
});
btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Follow

06/05/2014 15:53

How to retrieve data from a SQLite database in Android | Anu's crazy ...

25 sur 25

http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

tvw = (TextView) findViewById(R.id.tvw3);


tvw.setText(g);
String s = (String) tvw.getText();
System.out.print(s);
}
});
}
}
Reply

ashwini says:
February 27, 2014 at 4:41 pm

Can u tell me the code for how to populate spinner data from sqlite database and
where can i get my dtabase files when i run app on mobile?
plz reply asap!!!
ashwini.dhamankar08@gmail.com
Reply

Aditi Gupta says:


March 7, 2014 at 6:38 pm

Hi,
i used ur code but nothing is happening coz i m not able to retrieve data in the form of list view. I have button on my one
activity when i click on dat i need to add the data and when i click on save button to save the data it is not doing anything and
when i return back to the previous activity then according to your code it should show the added name to the previous
activity but it is not showing anything and log cat is showing that I am trying to requery a closed cursor. Please help i tried
manier times to rebuild the project. Thanks
Reply

Anu's crazy world


The Twenty Ten Theme.

Create a free website or blog at WordPress.com.

Follow

06/05/2014 15:53

You might also like