How to Retrieve Data From a SQLite Database in Android _ Anu's Crazy World

25

Click here to load reader

description

How to Retrieve Data From a SQLite Database in Android _ Anu's Crazy World

Transcript of How to Retrieve Data From a SQLite Database in Android _ Anu's Crazy World

  • How to retrieve data from a SQLite database in AndroidPosted 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.

    Anu's crazy world

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    1 sur 25 06/05/2014 15:53

  • 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 dataprivate ArrayList 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();

    // 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(this, android.R.layout.simple_list_item_1, populateList());

    uGraduateNamesListView.setAdapter(uGraduateListAdapter);

    }

    @Overridepublic void onClick(View v) {

    Intent addNewUndergraduateIntent = new Intent(this, AddNewUndergraduateActivity.class);startActivity(addNewUndergraduateIntent);

    }FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    2 sur 25 06/05/2014 15:53

  • // To create a List that contains undergraduate names, we have to read the SQLite database//We are going to do it in the separate methodpublic List populateList(){

    // We have to return a List which contains only String values. Lets create a List firstList uGraduateNamesList = new ArrayList();

    // First we need to make contact with the database we have created using the DbHelper classAndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

    // Then we need to get a readable databaseSQLiteDatabase 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 havCursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME_GPA, 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 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_NAMString ugUniId = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAdouble ugGpa = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_NAM

    // Finish reading one raw, now we have to pass them to the POJOUndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();ugPojoClass.setuGraduateName(ugName);ugPojoClass.setuGraduateUniId(ugUniId);ugPojoClass.setuGraduateGpa(ugGpa);

    // Lets pass that POJO to our ArrayList which contains undergraduates as typepojoArrayList.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 errorsqliteDatabase.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@Overrideprotected 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@Overridepublic void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {

    Toast.makeText(getApplicationContext(), "Clicked on :" + arg2, Toast.LENGTH_SHORT).show();

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    3 sur 25 06/05/2014 15:53

  • 17 Votes

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

    // We have to identify what object, does the user clicked, because we are going to pass only clicked ob// What we are going to do is, get the ID of the clicked item and get the values from the ArrayList whi//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 activityBundle dataBundle = new Bundle();dataBundle.putString("clickedUgraduateName", clickedObject.getuGraduateName());dataBundle.putString("clickedUgraduateUniId", clickedObject.getuGraduateUniId());dataBundle.putDouble("clickedUgraduateGpa", clickedObject.getuGraduateGpa());

    // Attach the bundled data to the intentupdateDeleteUgraduateIntent.putExtras(dataBundle);

    // Start the ActivitystartActivity(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!!!

    Rate this:

    Share this:

    You May Like

    1.

    About these ads

    4 1 1

    Be the first to like this.

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    4 sur 25 06/05/2014 15:53

  • About anujaroshaAn 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

    Related

    How to insert data in to a SQLite database inAndroid

    How to Update and Delete data from SQLitedatabase in Android

    How to retrieve data from a SQL table inPHP

    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 thatlayout. What I have done in the background is getting the Bundle content and set the values of the EditText fieldsaccordingly. 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-one-activity-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 rowupdation means rows without any gap of blank row .how we could do that .

    help me !thanks in advance

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    5 sur 25 06/05/2014 15:53

  • 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 thesource 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 A500Android 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 myandroid 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 seethe raw database just like we can see in phpMyAdmin in your REAL device. But you can see in the emulator withthe help of SQLite browser. FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    6 sur 25 06/05/2014 15:53

  • 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 insertthe values by using the edit text & because of that the the value was that shown. actually i want to used thestaic 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 youprovide your email address so that I can attach the database file, I would be grateful if you can look at it and see what theissues 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 againand 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 thedatabase using SQLite browser. Hope you have push that file back to the device/emulator before you run yourcode 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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    7 sur 25 06/05/2014 15:53

  • hi anujaroshanice 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 dataprivate ArrayList pojoArrayList;

    /** Called when the activity is first created. */@Overridepublic 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 namesListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());

    questlist.setAdapter(ListAdapter);

    }

    @Overridepublic 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 methodpublic List populateList(){

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    8 sur 25 06/05/2014 15:53

  • // We have to return a List which contains only String values. Lets create a List firstList questlist = new ArrayList();

    // First we need to make contact with the database we have created using the DbHelper classAndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);

    // Then we need to get a readable databaseSQLiteDatabase 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 loopwhile (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 POJODetailsPojo PojoClass = new DetailsPojo();PojoClass.setquest(quest);PojoClass.setoption1(option1);PojoClass.setoption2(option2);

    // Lets pass that POJO to our ArrayList which contains quest as typepojoArrayList.add(PojoClass);

    // But we need a List of String to display in the ListView also.//That is why we create questlistquestlist.add(quest);}

    // If you dont close the database, you will get an errorsqliteDatabase.close();

    return questlist;}

    // If you dont write the following code, you wont be able to see what you have just insert to the database@Overrideprotected void onResume() {super.onResume();pojoArrayList = new ArrayList();ListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, populateList());questlist.setAdapter(ListAdapter);}

    @Overrideprotected void onStart() {super.onStart();pojoArrayList = new ArrayList();

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    9 sur 25 06/05/2014 15:53

  • 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 VM03-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: main03-27 07:37:15.579: E/AndroidRuntime(282): java.lang.RuntimeException: Unable to start activityComponentInfo{com.pollyroid/com.pollyroid.display_quest}: java.lang.NullPointerException03-27 07:37:15.579: E/AndroidRuntime(282): atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)03-27 07:37:15.579: E/AndroidRuntime(282): atandroid.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)03-27 07:37:15.579: E/AndroidRuntime(282): atandroid.app.ActivityThread.access$2300(ActivityThread.java:125)03-27 07:37:15.579: E/AndroidRuntime(282): atandroid.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): atandroid.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): atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)03-27 07:37:15.579: E/AndroidRuntime(282): atcom.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.NullPointerException03-27 07:37:15.579: E/AndroidRuntime(282): atcom.pollyroid.display_quest.onCreate(display_quest.java:39)03-27 07:37:15.579: E/AndroidRuntime(282): atandroid.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)03-27 07:37:15.579: E/AndroidRuntime(282): atandroid.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,

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    10 sur 25 06/05/2014 15:53

  • Look at the following lines in LogCat out-put.03-27 07:37:15.579: E/AndroidRuntime(282): Caused by: java.lang.NullPointerException03-27 07:37:15.579: E/AndroidRuntime(282): atcom.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 youget 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 issomething 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. Pleasereplace first letter with simple l. You will get NullPointerException when your ArrayList is empty. Socheck 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 xmland manifest file to dis mail id [email protected].. pls pls plsThnx a lot

    Reply

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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    11 sur 25 06/05/2014 15:53

  • unable to retreive the datainsertion is working fine..bt unable to retreiveNothing is bein displayed in the emmulatorcn uhelp??

    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.. [email protected].

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

    [email protected]

    Reply

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

    Can you pls also send me the full source code? [email protected]

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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    12 sur 25 06/05/2014 15:53

  • 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 helpme

    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) inthis 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. Butthat class may extends appropriate ***Adapter class. As an example, if you are having an ExpandableList, youhave 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=ptwmjgE/Database(526): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failedE/Database(526): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    13 sur 25 06/05/2014 15:53

  • E/Database(526): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)E/Database(526): atandroid.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)E/Database(526): atandroid.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)E/Database(526): atcom.sneha.addnewnumber.AddNewUndergraduateActivity.insertUndergraduate(AddNewUndergraduateActivity.java:88)E/Database(526): atcom.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 errorplz 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 andmanifest file to dis mail id [email protected].. pls pls plsThnx 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 whojust copy and paste others code without understanding the concept. I have posted the UI and also all the logic codes thatimportant 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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    14 sur 25 06/05/2014 15:53

  • 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 detailusing 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 [email protected] . 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 inwhich 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 amunable to retrieve it.could you please help me.My code is,ClientInfoAct.java

    package com.me.android.placefinder;import java.util.ArrayList;

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    15 sur 25 06/05/2014 15:53

  • 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;@Overridepublic 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 retrievedcode..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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    16 sur 25 06/05/2014 15:53

  • hey anuja..i have used your tutorial but the problem is the database is not there..means the database is not created..can uplease 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 donefrom 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 usinguser 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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    17 sur 25 06/05/2014 15:53

  • 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. */@Overridepublic void onCreate(Bundle savedInstanceState) {StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk ornetwork 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 buttonsubmit.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 userArrayList postParameters = new ArrayList();

    // define the parameterpostParameters.add(new BasicNameValuePair(search,byear.getText().toString()));String response = null;

    // call executeHttpPost method passing necessary parameterstry {response = CustomHttpClient.executeHttpPost(//http://129.107.187.135/CSE5324/jsonscript.php, // your ip address if using localhost serverhttp://www.sablabs.com/Calendar/pharmacy1.php, // in case of a remote serverpostParameters);

    // store the result returned by PHP script that runs MySQL queryString result = response.toString();// String[] result = response;//parse json datatry{returnString = ;JSONArray jArray = new JSONArray(result);for(int i=0;i

  • 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) {@Overridepublic void onClick( View view) {

    // getting values from selected ListItemString 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 intentIntent 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 detailsstartActivity(in);}

    });}}

    Reply

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

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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    19 sur 25 06/05/2014 15:53

  • 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();}}

    }

    @Overridepublic void onCreate(SQLiteDatabase db) {

    }

    @Overridepublic 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 {

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    20 sur 25 06/05/2014 15:53

  • 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();}

    /**FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    21 sur 25 06/05/2014 15:53

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

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    22 sur 25 06/05/2014 15:53

  • this.insertStmt.executeInsert();this.insertStmt.close();}}

    /*** Select query for DB.**/public JSONArray selectFromDB() {JSONArray returnData = new JSONArray();try {//prepare query as per your needCursor 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.*/@Overridepublic 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;FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    23 sur 25 06/05/2014 15:53

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

    @Overridepublic void onClick(View v) {// TODO Auto-generated method stubg=e.getText();

    try{

    db1.execSQL(INSERT INTO chandra(NAME) VALUES (+g+));

    }catch(Exception e){System.out.println(e);}

    }});

    btn3.setOnClickListener(new OnClickListener() {

    @Overridepublic void onClick(View view) {

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    24 sur 25 06/05/2014 15:53

  • Anu's crazy world

    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 andwhere can i get my dtabase files when i run app on mobile?plz reply [email protected]

    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 oneactivity 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 andwhen i return back to the previous activity then according to your code it should show the added name to the previousactivity but it is not showing anything and log cat is showing that I am trying to requery a closed cursor. Please help i triedmanier times to rebuild the project. Thanks

    Reply

    The Twenty Ten Theme. Create a free website or blog at WordPress.com.

    FollowFollow

    How to retrieve data from a SQLite database in Android | Anu's crazy ... http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from...

    25 sur 25 06/05/2014 15:53