How to retrieve data from a SQLite database in Android

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.

Retrieve data from a SQLite database in Android
Figure 1

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

Retrieve data from a SQLite database in Android.png
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.

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 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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import 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);
	}

	// 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, String having, String orderBy)
		Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME_GPA, 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 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 class
			//and create a ArrayList of undergraduates

			String ugName = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME));
			String ugUniId = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_UNI_ID));
			double ugGpa = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_NAME_UNDERGRADUATE_GPA));

			// 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 database
	@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 where
	//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();

		// 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 clicked object details to the next activity
		// What we are going to do is, get the ID of the clicked item and get the values from the ArrayList which has
		//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 don’t ask me to repeat it here 😛

I think this is more than enough for today’s 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 AnujAroshA

Working as a Technical Lead. Specialized in iOS application development. A simple person :)
This entry was posted in Android Examples and tagged , , , , . Bookmark the permalink.

68 Responses to How to retrieve data from a SQLite database in Android

  1. kalpataru Nayak says:

    i want to know about your UpdateDeleteUndergraduateActivity.

    help me !

  2. kalpataru Nayak says:

    Hi & Thank’s 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……

    • anujarosha says:

      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. I’ll 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…!!!

  3. kirti says:

    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

    • anujarosha says:

      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?

  4. kirti says:

    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.

    • anujarosha says:

      hi Kirti,

      As far as I know, you no need to do any kind of settings. We retrieve data using our own application. You can’t 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.

      • kirti says:

        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.

  5. Aqeela says:

    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.

  6. Shipra says:

    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.

    • anujarosha says:

      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.

  7. Dee says:

    Awesome tutorial. Good job!!!

  8. anisha fernandes says:

    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(){

    // 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 don’t close the database, you will get an error
    sqliteDatabase.close();

    return questlist;
    }

    // If you don’t 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();
    ListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());
    questlist.setAdapter(ListAdapter);
    }

    }

    • anujarosha says:

      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.

      • anisha fernandes says:

        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:

        Hey Anisha,

        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:

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

  9. Mike says:

    Is it possible for you to upload the xml for the listview? I’m unsure of some your “initialize ui elements”

  10. anisha fernandes says:

    hey thanks a lot…. it finaallly worked…!:)

  11. chhavi says:

    unable to retreive the data…insertion is working fine..bt unable to retreive…Nothing is bein displayed in the emmulator…cn u help??

  12. aki says:

    Can you please send me the full codes too??.. I need it badly .. Thanks in a million..

    akiville23@gmail.com

  13. Yasmin says:

    Would you please post the link of the source code at GitHub for everyone to use?

    Would be very grateful. Thanks 🙂

  14. Priyanka says:

    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?

  15. Rahul G says:

    Thanks a lot .. It was really helpful

  16. Anu says:

    Hi Anujarosha,Ur blog had helped me a lot. Thanks a lot…But 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…

  17. zubi says:

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

  18. Girish says:

    Awesome blog…Thanks anuja..!!

  19. Girish says:

    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.

    • anujarosha says:

      Hi Girish,

      I’ll just give you some hints because I’m 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 🙂

    • vijay says:

      fine nice

  20. Sneha says:

    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)
    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..

  21. Sneha says:

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

  22. Heer Sharma says:

    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

  23. anujarosha says:

    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…

  24. Sneha says:

    thank u for ur rply.. bt i hv completed d code a month ago..
    bt again thanx… 🙂

  25. vaishnavi says:

    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….

  26. rekha says:

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

  27. mona says:

    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!!

  28. Sheila says:

    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.

  29. Namita Tare. says:

    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;

    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

  30. jiji says:

    hai..thanks for the tutorial..but i have face a problem when i want to add the details..first when i’m still not put this retrieved code..i’ve no problem with adding..but when i used retrieved code..i can’t add any info..please help me!

  31. jiji says:

    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

  32. Ali says:

    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…

  33. Abhijit Ghosh says:

    Thanks for your valuable job man……………..Thanks once again

  34. udhayabanu says:

    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
    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 application’s 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){
    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);
    }

    });
    }
    }

  35. jalu says:

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

    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 doesn’t 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 {
    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 doesn’t 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();
    }

    /**
    * 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);

    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!!!!

  36. madhankumar says:

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

  37. surya says:

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

    package com.example.chandardt;

    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) {

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

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

    }

    }

  38. ashwini says:

    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

  39. Aditi Gupta says:

    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

  40. Thx for ds tutorial, but plz can you help make the project source downloadable by providing us a link. It will help more programmers searching for similar stuff like ds. thx again.

  41. Merlin jones says:

    We are using cursor to have access with the database. Here the cursor acts as interface.
    I am new to java programming. What i saw is we have to implement interface in class but we are not writing anything like “implements” here in this code. Please explain how it acts as interface here.

  42. anurag says:

    i have used cursor to obtain the data from the database. I am comparing the string with the string obtained from the database and returning a true value if a match occurs but the thing is nit working..! can u help??

  43. manju says:

    hi i am facing some problem in database coding,please send me complete source code this one.
    ,

  44. lalitha says:

    When I used emulator, I am able to retrieve data from database using SQLite browser. But the data is not retrieved when I used my mobile.

  45. chidambaresh says:

    Sir can you ple solve the problem of how to view the database in one layout to other layout
    i can complete insert,delete,update,view in single activity its run but one more activity how to retrieve the same data

  46. Sourav4U says:

    hello,
    Anuj arosha ,

    I am following this tutorial. I want to add 2 buttons on each list item . Can you please provide me the code for the same?

    Please reply.

  47. Radhika says:

    What if i am running the app from my android mobile rather than the emulator,Doing so the database values are not getting affected ,even if i am inserting new values using my app.What to do to view the database values.Please Help !

Leave a comment