NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.

Search This Blog


Friday, 18 February 2011

ListView of Data from SQLiteDatabase - Android

This is a next level tutorial where I am mixing two concepts – The ListView concept that is explicitly explained in the ListView Tutorial and the SQLiteDB concept in into own tutorial.

Here I am intending to query a database using a SQLiteDatabase API. The results I obtain are in a Cursor object that I iterate and create an ArrayList that is passed to the ListView. Let us see the steps involved in this exercise:

In the onCreate(…) method I have 2 methods corresponding to the two steps described above:


Let us see what each of them does:

Here is the first step:

private void openAndQueryDatabase() {
            try {
                  DBHelper dbHelper = new DBHelper(this.getApplicationContext());
                  newDB = dbHelper.getWritableDatabase();
                  Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
                        tableName +
                        " where Age > 10 LIMIT 4", null);

            if (c != null ) {
                  if  (c.moveToFirst()) {
                        do {
                              String firstName = c.getString(c.getColumnIndex("FirstName"));
                              int age = c.getInt(c.getColumnIndex("Age"));
                              results.add("Name: " + firstName + ",Age: " + age);
                        }while (c.moveToNext());
            } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (newDB != null)
                  newDB.execSQL("DELETE FROM " + tableName);


Now, DBHelper is a class I have written extending the SQLiteOpenHelper class. All that it does is create a database by name “sample”, create a table within it and insert values into the table. It does this if the database does not already exist.  The table name is “Resource” and the columns in the table are Lastname, Firstname, Country, Age.

The code for this example can be downloaded here and you can look into the DBHelper code as well (which I do not want to elaborate here)

So, from the DBHelper class we get an open database which we call the newDB. Using this handle, we query the table for values. To keep it simple, while retrieving values I have hard-coded the column names which need not be the case. So I run a rawQuery and get the results into a Cursor.

Next I iterate through the Cursorand populate the results into an ArrayList of Strings “result”.  In the finally block, I not only close the database but before that I delete all the entries inserted into the database by the DBHelper class just to clean up.

Next how do I display the results in a ListView. If you know ListView– how it works it is rather simple. Else you could look at the ListViewTutorial. Here is the method:

      private void displayResultList() {
            TextView tView = new TextView(this);
        tView.setText("This data is retrieved from the database and only 4 " +
                  "of the results are displayed");
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, results));

The only additional bit I have done here is to add a HeaderView (which is using the concept of programming UI explained in another tutorial).

I have written this tutorial based on some of the requests in my blog. Hope this helps.


  1. Hi sai geetha,

    This article helped me alot. If u dont mind, I have one suggestion, in this article provide one more functionality that the user can be able to delete the values from database and list.

  2. hi sai geetha,can u post the code for voice (or)Audio recorder.Is the possible to record audio in Emulato?

  3. hi sai geetha garu, Thanks for posting examples and i need some buttonimages in grid view. can u post the example now. and my mail is

    Thanks & Regards,

  4. Hi Sai,
    I have One question regarding this listview and Database.
    If I have 10000 entries in a Database Tables. Now I want to set these entries to ListView.
    My Approach:
    For this I take a simple custom Adapter class(Base Adapter/SimpleCursorTreeAdapter) and set the result to ListView.But initially loading it takes more time to display in ListView.So,is there any good way to solve this issue.
    Thanks in advance..

    1. You can do that using recycle view. Recycle view is same as that of List-View but the major advantage is that it won't load all the entries in the list view at once. As you start scrolling, it will keep loading those lists at the same time.

  5. Hi Sai Geetha,
    Thanks for sharing a nice articles.
    My android app is a standalone and requires 7MB preloaded database,but Android application not accepting reading more than 1 MB of SQLite DB,please help me how to overcome this MAXSIZE limitation?I appreciate any of your inputs
    reply to

  6. hai
    i am sree i need some help for consructing dynamic expandandable list will u pls provide the informaiton

  7. Hi,
    I ma getting Source Not Found Error.How to get rid of it..Please Help..

  8. can this work for retrieving data from mySql database?

  9. hi can u plz help me to do retriving back data from database to current listview in android

  10. hi ,
    i am not able to display the result in listview .can you please tell , i can display it in toast

  11. i retrieve data from database and put it into listview.
    now i want to add edit and delete option to it.
    how i can delete or edit specific record.
    plz help me

  12. Hi Sai Geetha, Can you share your knowledge about creating offline map views in android?

  13. Hi sai.. I have few images which are retrieved from my web service.
    I wanna display these images in grid view in android and wanna create grid view dynamically without using xml page.
    How can i do this??

    Thanks in advance..

  14. Thank u mam. Could u please post how to delete and edit from list and DB.

  15. dis post very well hepled me can you please post how to populate spinner from database it's been a week and ive been stucked a long on ma project

  16. Hai Mam,

    the artical is very helpfull but if u don't mind,please help me to list the values in inth custumlist formate by using sqlite3


    2. cannot, because ListView need extends ListActivity

  17. Hai Mam ,
    I am working on one App Iwant your help in it,
    I want to list the list or playlist of our youtude account in the android application I am fresher,Please help me

  18. Hello sister,

    today i need to work on android database and searched net a lot for quick sample, but i failed.
    got your post and sample and got so happy, so nice sample

    i pray for your success in future.

  19. hello madam
    my problem in httpget method in android application?

    my code below:

    public static ArrayList getvideoList(String q) {

    ArrayList fetchchildvideo_Type = new ArrayList();

    String result = "";
    InputStream is = null;
    Log.v("log_tag", "DataQ :::"+q);
    try {
    HttpClient client = new DefaultHttpClient();
    // String getURL = "";

    String url = "";
    String data=url+q;
    Log.v("log_tag", "DataQuestion :::"+data);
    HttpGet get = new HttpGet(data);
    HttpResponse responseGet = client.execute(get);
    HttpEntity resEntityGet = responseGet.getEntity();
    is = resEntityGet.getContent();
    if (resEntityGet != null) {
    // do something with the response
    Log.i("GET RESPONSE", EntityUtils.toString(resEntityGet));

    } catch (Exception e) {

    // convert response to string
    try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");

    result = sb.toString();
    Log.v("log_tag", "REsultvideolink:::" + result);

    } catch (Exception e) {
    Log.e("log_tag", "Error converting result " + e.toString());
    Log.v("log_tag", " videolink " + result);

    // parse json data
    try {
    JSONObject json_obj = new JSONObject(result);
    JSONObject j_Array = json_obj.getJSONObject("data");
    JSONArray jv_arry=j_Array.getJSONArray("items");
    for (int i = 0; i < jv_arry.length(); i++) {
    All_quiz_list_dto question_dto = new All_quiz_list_dto();
    JSONObject js = jv_arry.getJSONObject(i);
    JSONObject js_thumbnails=js.getJSONObject("thumbnail");
    JSONObject js_player=js.getJSONObject("player");
    JSONObject js_content=js.getJSONObject("content");
    question_dto.quiz_js_id = js.getString("id");


    } catch (JSONException e) {
    // TODO Auto-generated catch block

    //Log.v("logtag", " database::: " + result);
    return fetchchildvideo_Type;



    09-15 13:06:31.493: ERROR/log_tag(574): Error converting result java.lang.NullPointerException


  20. This comment has been removed by the author.

  21. hey!!
    your example is very good...i just have one doubt..there is another java file also in which the actual class is presents which extends activity??

  22. > SQLiteDB concept in into own tutorial.

    What is "concept in into own" mean? (And many other non-sense phrases here.)

  23. Hai Sai geetha,

    I saved the datas from a form design for my android tablet. Now i am getting the output. but i want to see the data.

    How to see the data whther it is saved or not in TABLET.. Kindly help me...

  24. hi Geetha,

    Thanks for Your great contribution.

  25. Hi Geetha,

    I created a pop up window with the list view on a edittext click,
    now i am storing the values in default as a string. i need to fetch the data from the database and view it in the listview i need your help.


  26. Thanks for .. But how can i use more then one test from list view

  27. how can i delete item from this listview i hav tried a lot but my code has stucked. please help i m new in android thanks in advance

  28. hiii..This is ATISH KUMAR i am new in android i have one problem in creating database....

    my question is: how to save the form value(edittext/textview,checkbox ,radio button) values to database while clicking submit button .

    and how to see the save values from database into view...and also one Edit button is there if i click edit button it should display the whole form with saved values and again if i edit something and press submit its value should be updated to the database.
    please help me.......
    thank you.

  29. Thanks a lot Ma'm.

  30. Hi please always insert image on your post or a demo video

  31. what is 'results' in setListAdapter()

  32. while execute this query i get syntax error

    curser1=DB.rawQuery("SELECT "+ CurrentTime+" FROM "+TbllocationName+" ORDERBY "+CurrentTime,null);