Hi Android friends… In my blogging history, I have already written two blog posts related to database handling. One is MySQL with PHP and the next is MySQL with Java. In this blog post I am going to show you, how we can insert data to a table in a SQLite database when we are developing Android applications. This is going to be a starting point for a series of SQLite database related articles, because I am expecting to write Retrieve, Update and Delete in separate posts. 😀
First I will explain the scenario we are going to implement. It is a place where we can store undergraduate name, University ID and GPA (Grade Point Average) value. The first interface shows the current undergraduates, that already registered with this system. But in this blog post you will not able to see the undergraduates names in the first interface, because I am not going to show you how to retrieve data from the database. :O
By pressing the “Add New undergraduate” button, you can go to the second UI (User Interface) where we can provide undergraduate details. If you press the “Cancel” button, you will redirect to the first UI again. You can fill the EditText fields as in Figure 2
When you press the “Save” button, you will be able to see a Toast message with the affected raw ID of the table. At the end of the post I will tell you a way to explore your Android phone emulator database.
I think now you have a clear picture about what we are going to implement. Before looking at the source code directly, let’s think the scenario logically. After user filling the EditText, he/she will press the “Save” button. So we need to take what the user has enter in the provided EditText fields. After that what I am going to do is, pass those values to a POJO (Plain Old Java Object) class. Then I am pass that POJO class instance to an ArrayList with it’s data. I am repeating this action for every entrance. After finishing all that only, I think to insert those data in to the SQLite database. Following is the source code for the second interface of the Figure 1
package com.anuja.sqlite; import java.util.ArrayList; import android.app.Activity; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class AddNewUndergraduateActivity extends Activity implements OnClickListener { private EditText uGraduateNameEditText; private EditText uGraduateUniIdEditText; private EditText uGraduateGpaEditText; private Button cancelButton; private Button saveButton; private ArrayList undergraduateDetailsPojoObjArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.insert_new_ugraduate); uGraduateNameEditText = (EditText) findViewById(R.id.insertNewUgraduate_name_editText); uGraduateUniIdEditText = (EditText) findViewById(R.id.insertNewUgraduate_uniId_editText); uGraduateGpaEditText = (EditText) findViewById(R.id.insertNewUgraduate_gpa_editText); cancelButton = (Button) findViewById(R.id.insertNewUgraduate_cancel_button); cancelButton.setOnClickListener(this); saveButton = (Button) findViewById(R.id.insertNewUgraduate_save_button); saveButton.setOnClickListener(this); undergraduateDetailsPojoObjArrayList = new ArrayList(); } @Override public void onClick(View v) { if(v.getId() == R.id.insertNewUgraduate_cancel_button){ finish(); }else if(v.getId() == R.id.insertNewUgraduate_save_button){ // Get the values provided by the user via the UI String providedUgraduateName = uGraduateNameEditText.getText().toString(); String providedUgraduateUniId = uGraduateUniIdEditText.getText().toString(); Double providedUgraduateGpa = Double.parseDouble(uGraduateGpaEditText.getText().toString()); // Pass above values to the setter methods in POJO class UndergraduateDetailsPojo undergraduateDetailsPojoObj = new UndergraduateDetailsPojo(); undergraduateDetailsPojoObj.setuGraduateName(providedUgraduateName); undergraduateDetailsPojoObj.setuGraduateUniId(providedUgraduateUniId); undergraduateDetailsPojoObj.setuGraduateGpa(providedUgraduateGpa); // Add an undergraduate with his all details to a ArrayList undergraduateDetailsPojoObjArrayList.add(undergraduateDetailsPojoObj); // Inserting undergraduate details to the database is doing in a separate method insertUndergraduate(undergraduateDetailsPojoObj); // Release from the existing UI and go back to the previous UI finish(); } } public void insertUndergraduate(UndergraduateDetailsPojo paraUndergraduateDetailsPojoObj){ // First we have to open our DbHelper class by creating a new object of that AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(this); // Then we need to get a writable SQLite database, because we are going to insert some values // SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks. SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase(); // ContentValues class is used to store a set of values that the ContentResolver can process. ContentValues contentValues = new ContentValues(); // Get values from the POJO class and passing them to the ContentValues class contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME, paraUndergraduateDetailsPojoObj.getuGraduateName()); contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_UNI_ID, paraUndergraduateDetailsPojoObj.getuGraduateUniId()); contentValues.put(AndroidOpenDbHelper.COLLUMN_NAME_UNDERGRADUATE_GPA, paraUndergraduateDetailsPojoObj.getuGraduateGpa()); // Now we can insert the data in to relevant table // I am going pass the id value, which is going to change because of our insert method, to a long variable to show in Toast long affectedColumnId = sqliteDatabase.insert(AndroidOpenDbHelper.TABLE_NAME_GPA, null, contentValues); // It is a good practice to close the database connections after you have done with it sqliteDatabase.close(); // I am not going to do the retrieve part in this post. So this is just a notification for satisfaction ;-) Toast.makeText(this, "Values inserted column ID is :" + affectedColumnId, Toast.LENGTH_SHORT).show(); } }
Here comes the most important part. Where is our database and tables? :O Don’t worry. We are on the way to create that. To accomplish that target, I am using a separate Java class and I name it AndroidOpenDbHelper. In that class, we are going to create a database and handling version with the help of SQLiteOpenHelper class. You can see the code follow. The comments will explain the whole story to you. Copy it 😉
package com.anuja.sqlite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; // A helper class to manage database creation and version management. public class AndroidOpenDbHelper extends SQLiteOpenHelper { // Database attributes public static final String DB_NAME = "undergraduate_gpa_db"; public static final int DB_VERSION = 1; // Table attributes public static final String TABLE_NAME_GPA = "undergraduate_details_table"; public static final String COLUMN_NAME_UNDERGRADUATE_NAME = "undergraduate_name_column"; public static final String COLUMN_NAME_UNDERGRADUATE_UNI_ID = "undergraduate_uni_id_column"; public static final String COLLUMN_NAME_UNDERGRADUATE_GPA = "undergraduate_gpa_column"; public AndroidOpenDbHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } // Called when the database is created for the first time. //This is where the creation of tables and the initial population of the tables should happen. @Override public void onCreate(SQLiteDatabase db) { // We need to check whether table that we are going to create is already exists. //Because this method get executed every time we created an object of this class. //"create table if not exists TABLE_NAME ( BaseColumns._ID integer primary key autoincrement, FIRST_COLUMN_NAME text not null, SECOND_COLUMN_NAME integer not null);" String sqlQueryToCreateUndergraduateDetailsTable = "create table if not exists " + TABLE_NAME_GPA + " ( " + BaseColumns._ID + " integer primary key autoincrement, " + COLUMN_NAME_UNDERGRADUATE_NAME + " text not null, " + COLUMN_NAME_UNDERGRADUATE_UNI_ID + " text not null, " + COLLUMN_NAME_UNDERGRADUATE_GPA + " real not null);"; // Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data. db.execSQL(sqlQueryToCreateUndergraduateDetailsTable); } // onUpgrade method is use when we need to upgrade the database in to a new version //As an example, the first release of the app contains DB_VERSION = 1 //Then with the second release of the same app contains DB_VERSION = 2 //where you may have add some new tables or alter the existing ones //Then we need check and do relevant action to keep our pass data and move with the next structure @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion == 1 && newVersion == 2){ // Upgrade the database } } }
That is all guys. You did it. You have inserted your first data set to a SQLite table in Android application. Don’t you sure about it? I will prove it to you. Go to;
- Window -> Open Perspective -> DDMS
- open File Explorer window
- explore “data” directory
- inside that you will find another “data” directory. Explore it too
- Then you will be able to find your package name of this application (Ex: com.anuja.sqlite)
- Go inside that
- Now you can see the “database” directory
- Bingo… inside that you have your database with the name you have provided (Ex: undergraduate_gpa_db)
Ooops… how you gonna open that file? Already tried double click, right click etc… 😉 Those don’t work. Look carefully, then you can find an icon with an arrow. The tool-tip given to that icon is “Pull a file from the device“. When you click that icon by selecting the database file, it will ask a place to save that file in your PC. Complete that step also.
Now what? Tried to open with different kinds of text editors? Don’t be hurry, wait till I tell you about a fantastic tool to browse a SQLite databse file. It is call “SQLite Database Browser“. It is a small size of file where you can download freely from the Internet. Don’t need to install or any administration privileges to run it. Just double click it. You have to import the database (saved file) to this application. Follow the steps as here;
- Databases -> Add database
- Then a pop up window will appear
- Browse the file where you have saved it
- click OK
- double click on the database name (Ex: undergraduate_gpa_db) or click on the + mark
- Under the Tables, you can see your table (Ex: undergraduate_details_table)
- Double click in that and go to the Data tab
THE END 🙂 I am not going to upload the source code to GitHub for this post. I will do it after completing Retrieve, Update and Delete as well. Till then have a nice day/s 😉
Hi, thanks for the post. but I have a question, where is the implementation for the class UndergraduateDetailsPojo?
I did not put that class in to this blog post, because the post getting lengthy. I will upload whole source code to GitHub when I completed Update and Delete functions also. For your information, POJO class is a simple JAVA class which has private variables and public getters and setters for those variables.
what to do if i want to save the in database statically and retrieve it in multiple checkboxes??
can u suggest something??
so how will i impliment this in my project
anujarosha can you help me to set date,name to list activity which is retrived from database…plz
Hi, thanks for the post. But i also have a question, can you show us the XML code because i don’t know the ID of the editText
Thanks for the answer, I hope the source code.
Hey Gabriel,
You are welcome. If you need a model for the POJO, go through this link. (https://anujarosha.wordpress.com/2011/11/22/how-to-use-pojo-to-fill-arraylist-in-android/) The “Film” class that I have written in that post is an example for a POJO.
Thanks again, I see the example. This blog is really good.
Hi Gabriel,
You are welcome 🙂
Hi..this is really a good post..I have one doubt in that is, as i run my project as android application i am getting error saying ur project has error..
but there is no error in any file of my project…
plz help me..
Hi Rachana,
If you are 100% sure that you have no error in your JAVA files as well as XML and the Android Manifest file, the only thing you have to do is Clean and Run your project.
Project -> Clean
If that not works, please see your Error Log and post the error here. Then I can give you a more clear answer. You can get Error Log view :
Window -> Show View -> Error Log
Good luck
Thanks for reply…
this is what m getting in error log..
org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.IllegalStateException)
at org.eclipse.swt.SWT.error(SWT.java:4083)
at org.eclipse.swt.SWT.error(SWT.java:3998)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:137)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4041)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3660)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2640)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2604)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2438)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:671)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:664)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:115)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:620)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:575)
at org.eclipse.equinox.launcher.Main.run(Main.java:1408)
Caused by: java.lang.IllegalStateException
at org.eclipse.jface.text.projection.ProjectionMapping.toImageLine(ProjectionMapping.java:480)
at org.eclipse.jface.text.TextViewer.modelLine2WidgetLine(TextViewer.java:5264)
at org.eclipse.wst.sse.ui.internal.StructuredTextViewer.modelLine2WidgetLine(StructuredTextViewer.java:751)
at org.eclipse.jface.text.JFaceTextUtil.modelLineToWidgetLine(JFaceTextUtil.java:224)
at org.eclipse.jface.internal.text.source.DiffPainter.paintLine(DiffPainter.java:220)
at org.eclipse.jface.internal.text.source.DiffPainter.paint(DiffPainter.java:158)
at org.eclipse.jface.text.source.LineNumberChangeRulerColumn.doPaint(LineNumberChangeRulerColumn.java:190)
at org.eclipse.jface.text.source.LineNumberRulerColumn.doubleBufferPaint(LineNumberRulerColumn.java:703)
at org.eclipse.jface.text.source.LineNumberRulerColumn.redraw(LineNumberRulerColumn.java:859)
at org.eclipse.jface.text.source.LineNumberRulerColumn$1.run(LineNumberRulerColumn.java:422)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:134)
and currently am trying to get data from only two editText(Name and Id)and two buttons(Save and Cancel). And want to see these data in database…
bt its not working…
one thing i forgot to tell you that ,am using Helios version of Eclipse..
that is supported J2EE feature also…
is eclipse version matters in this case??
Hi Rachana,
Your error is not relate with the code sample I have written. Therefore the help I can give you is very little. I have searched it and things that I like to highlighted are;
* SWTError (http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/SWTError.html)
* IllegalStateException (http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/IllegalStateException.html)
Seems to me, this is an Eclipse bug
* IllegalStateException in ProjectionMapping toImageLine (https://bugs.eclipse.org/bugs/show_bug.cgi?id=279676)
I use that source code in both Helios as well as Indigo. Sorry… this is all I can tell at this moment 😦
Thanks..I wil try to find those errors using your links…
I have one more doubt in Sqlite browser…I have download 1.3 version of it..and m nt able to find “database” option as per your steps mentioned above…what should i do??
Hi Rachana,
Sorry for the late reply.
In 1.3 version, you click on the first option in the Menu bar. That means;
File -> Open Database
Next steps are same as previous.
Hi Anujarosha,
I did that step …but m nt getting 3rd step as u mentioned previously i.e.(Browse the file where you have saved it)..
which file should i add there?boz there is no database file saved on my folder…
Plz Help..
Rachana,
Have you read the previous bullet points starting from;
Window -> Open Perspective -> DDMS…
And please read the next paragraph also. There I have mentioned how to store your database file. You have to browse that saved database file.
I think you haven’t read the article clearly 😉
oh yes…I just read article very fast…
Thanks for replying me…
🙂
Hi,
I have to design a user friendly GUI (rich GUI) in android….I just develop an application using Textbox,spinner,buttons etc…m nt able to think beyond this…
can you plz suggest me your ideas or which links should i refer to make GUI more interactive??
Hello Rachana,
I think you better first go through the Android developer’s site for interface designing. (http://developer.android.com/guide/topics/ui/index.html) Here you will find a sub topic call “Styles and Themes”. Read it. What I feel is we can create smooth and attractive GUI using those styles.xml files.
Good luck…
Thanks for replying me..i will definatly try it..
can you post UndergraduateDetailsPojo
actually i’m desing an app of registration so i need to insert content into database your code was so help full but i’m in bit trouble
i tried to implement your code but the user shoud not get the details of other users
my fied contails (EDIT TEXT)
userid
password
firstname
lastname
monthlyincome
and that should just store in DB and used in loginpage and inside the app
so can you help me out
my actual code was like this
Button sub=(Button)findViewById(R.id.submit);
sub.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
SQLiteDatabase db1;
db1 = openOrCreateDatabase(“Userdetails.db”, SQLiteDatabase.CREATE_IF_NECESSARY, null);
db1.setVersion(3);
db1.setLocale(Locale.getDefault());
db1.setLockingEnabled(true);
try{
Cursor c1=db1.rawQuery(“select Username from details1 where Username='”+User+”‘”,null);
if(c1.moveToNext())
{showDialog(4);}
else
{
ContentValues values1 = new ContentValues();
values1.put(“Firstname”, First);
values1.put(“Lastname”, Last);
values1.put(“Username”, User);
values1.put(“Password”, Pass);
values1.put(“Monthlyincome”, monthincome);
db1.insert(“details1”, null, values1);
showDialog(5);
}
catch(Exception e){ }
}
});
but table is not getting created so i tried your code but i’m unable to get it right
Hi Shaik,
From following link you can download “UndergraduateDetailsPojo” as well as other source codes regard to this project.
(https://github.com/AnujAroshA/Android-SQLite)
I think it has all the answers for your question. If you still unable to figure it out, don’t hesitate to ping me again.
Good luck…!!!
plz upload xml and android manifest file also……..
Hey Arya,
There is nothing big. That’s why I have uploaded the images of the interfaces. You can drag and drop those widgets and the XML will auto generate. Only you have to consider about the IDs.
plz anuja i reeli want dis project i cudn’t able to do it due to lack of xml and manifest file please upload it if u can !! 10x a lot!!!
Hi,
How to enable the tabs on Button click which are set up in one activity and now i want to access it from another activity….plz give me a way to solve this…
Hi Rachana,
What do you mean by “enable the tabs” ? Sorry I couldn’t understand your question. Can you please explain it. Are you saying that you have a TAB window and when you click on a Button in one Activity, then you want to go to another Activity in the same TAB window.
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
Hi.
can u plz help in my following task , I have to scan a text using camera and compare it with the database and once it is matched it should provide the details of that text for eg: consider i have to scan a mob.no then it should compare it withe the database and provide details such as user_name etc… plz do help me
Hi..
Can u plz tel me how to set size of dynamically added buttons?
I have tried this one..bt its nt working..
ViewGroup.LayoutParams params = Button1.getLayoutParams();
params.width = 100;
params.height=50;
Button1.setLayoutParams(params);
hi thanks for your app
my db not working.if i insert the value click the save button my app force close
Hey there! I am new to android programming and I’m using you example (which is great by the way) and I didn’t use the undergraduateDetailsPojoObjArrayList.add(undergraduateDetailsPojoObj);
and it worked perfectly. Let me just tell you that I’m doing this with multiple tables and a different Pojo Class for each one. Using that line of code gets me a nullpointer and the app crashes, but if I don’t use it, it works fine. Is there any reason as to why you use that array?
thanks alot for help. its great
hey, iam from indonesia, your tutorial is soo good..keep posting.
Its a good one.But my project don’t run inspite of having no error.Please guide me.
i’m getting an error that says—-msg = table Customer_details_table has no column named CardNumber please help
Hi! I urgently need help from you. is there an email that I can contact you?
hey send me the full code of how to insert database in sql server or mysql ijn android to my mail please..
chiru510@yahoo.com
i really needed now. i will wait for ur response,.
thank u.
hi anujarosha i want the code for changing password in android using sqlite can u help me out pls
this is my mail id manjunath.c59@gmail.com
i’m using android 4.0.3
Hi
I have seen your example,in the code StartmanagingCursor i sbeing depreceated nay ideas how to overcome this
Hi Nani,
Yes, according to the Android documentation it is deprecated and also according to the same source you can use LoaderManager instead, available via getLoaderManager().
Hi,
I saw ur code…it is nice. Do you have whole project with you since…in github I could find only activity files but I didn’t find any manifest file and other xml files. Without those files I am getting some errors when I try to use your activity java files….It would be helpful if you provide ur whole project info….
Thanks,
Mahesh
Hi,
My email id: maheshsep9@gmail.com
That would be great if you provide me the information.
Thank you,
Mahesh
hi
What is UndergraduateDetailsPojo class and why we are using this class. i am not understanding the propose of this class .and how to create this class.
thank you
Hello Naveen,
UndergraduateDetailsPojo class is a simple JAVA POJO class. There, I have declared all the database fields as variables. The use of that class is, when we need to retrieve all data from database, we could use an instance of this class instead by accessing field by field. If you see retrieving data from the database post, you will get a simple idea.
Good luck 🙂
hi anu! do you have samples for downloading files from pc to sdcard??
That is really great it helped me alot.but, i came across your other postings also. why are you not uploading XML layouts?……
how can i attach two database?
admin can i get the info about how to show the data we inserted in an app in pages
Hi Anu,
I know you haven’t replied to a few people but would you mind uploading the whole project or sending me the project. I’d greatly appreciate it. My email is shakeatron@gmail.com
Thanks,
Jake
Hi,
I am making a project on Locationbased Alarm system. will you please help me to complete my project. now adays m getting problem to show user info into the database. also kindly send me your whole project ASAP over fahad0847@gmail.com
I will be very thankfull to you.
Regards :
Fahad
hi good blogg
where is the coding of AndroidOpenDbHelper class???????????kindly help meee
Hi Malik,
Haven’t you seen the second coding part in the same blog post ? Because it contains the coding of the “AndroidOpenDbHelper” class
Hi Anujarosha,
Great tutorial for those who have no knowledge on how to set a database for a certain application. But I have one question, it sounds like your has this name package com.anuja.sqlite;
Is it necessary to write sqlite in the package or we can use any package?
It’s not necessary to have “sqlite” in the package name. It is just a name I’ve used.
Also I have one more inquiry. I got an error here UndergraduateDetailsPojo. What shall I do?
This is what POJO class contains.
Ok, I got everything but are you sure that this code works perfectly?
Yes, Hope anything got messed during updating to the blog. Otherwise I have tested it with real device too.
But when I run it and go to File Explorer > data > data > package name, I didn’t find any database file !!
good day sir… i have a problem about my android ebook application on sqlite.. honestly i really dont know how to put some info on the sqlite. i am beginner on this… hehehe..
Hello …..i have a problem related to data base that i want to insert more data in sqlite or in my aaps like recards of 400000 people how can i insert it????? i have already used a method which is inserting External XML file in SQLite but problem is that my projects take more time and it does not run on whole types of mobile it runs only on selected mobile,,,,,,please help me……
wow useful basic stuffs can u share me the source to teach my students please..
rakesh.sait@gmail.com
how to retrieve and display that list from SqliteDB in listview?
You can simply use SipmpleCursorAdapter for showing data in listView from your data base with the help of Cursor…..by the u can use this code…..
ListView listView=(ListView)findViewById(R.id.mylists);
String[] from=new String[] {“Fullname”};
adapterf = new SimpleCursorAdapter(NameSearchResult.this,R.layout.employee_list_items, cursor, from, new int[] {R.id.textname});
listView.setAdapter(adapterf);……
It is impartent to know that here values comming from Cursor which is used for quering from data base……SQLite…….
SQLiteDatabase db = (new DatabaseHelper27(this)).getWritableDatabase();
Cursor cursor=db.query(“SELECT * FROM TABLE NAME”,NULL,NULL);
one thing more ther is two xml layout is used one for listview(“@+id/mylists”) second for textviev in list view(employee_list_items)………
Hi dear Anuja..thanks fo sharing dis gud blog:)..but i got stuck wid pojo array list class(undergraduateDetailsPojoObjArrayList)…need a class file fo it..can u help me to come up wid dis..o jus email me to azranmohammed@gmail.com if u can..thanks again,,,chao..
hi anuja.. can i ask u some question about sqlite database?
I want to create a CRUD application using J2ME. the data will be put into myql. If you could help me?
Good tutorial, great jobs!
hi anuja..i have used your tutorial..it success but i have a problem with the toast..supposed the toast show at first interface right?but in my case the toast showed at second interface which is addnewundegraduate interface..do you know why?
Hello! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this write-up to him. Pretty sure he will have a good read. Thank you for sharing!
Heey thanx for the post but i have an error in the undergraduatedetailspojo section… Help me understand the use of undergraduatedetailspojo
Literally ultimate tutorial. I want a favor from you, i want to store the image in the database and i want to store in particular dimension. can guide me on this please. thank you in advance and ya very nyc work keep it up.:)
hey nyc tutorial and ya i tried modifying your code to read name,age,email but its not working yaar below pasted is my code so please check it and reply me please and ya ignore the image picker code.
package com.vizon.dezndemo;
import java.io.File;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class Add_Rec_Form extends Activity implements OnClickListener {
private Uri mImageCaptureUri;
private ImageView mImageView;
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 2;
private EditText NameEditText;
private EditText AgeEditText;
private EditText EmailEditText;
private Button cancelButton;
private Button saveButton;
private ArrayList PersonDetailsVizonObjArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.insert_new_ugraduate);
NameEditText = (EditText) findViewById(R.id.name);
AgeEditText = (EditText) findViewById(R.id.age);
EmailEditText = (EditText) findViewById(R.id.email);
cancelButton = (Button) findViewById(R.id.cancel);
cancelButton.setOnClickListener(this);
saveButton = (Button) findViewById(R.id.Savedb);
saveButton.setOnClickListener(this);
PersonDetailsVizonObjArrayList = new ArrayList();
final String [] items = new String [] {“From Camera”, “From SD Card”};
ArrayAdapter adapter = new ArrayAdapter (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(“Select Image”);
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
“tmp_avatar_” + String.valueOf(System.currentTimeMillis()) + “.jpg”);
mImageCaptureUri = Uri.fromFile(file);
try {
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra(“return-data”, true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (Exception e) {
e.printStackTrace();
}
dialog.cancel();
} else {
Intent intent = new Intent();
intent.setType(“image/*”);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, “Complete action using”), PICK_FROM_FILE);
}
}
} );
final AlertDialog dialog = builder.create();
mImageView = (ImageView) findViewById(R.id.iv_pic);
((Button) findViewById(R.id.Imgcap)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
Bitmap bitmap = null;
String path = “”;
if (requestCode == PICK_FROM_FILE) {
mImageCaptureUri = data.getData();
path = getRealPathFromURI(mImageCaptureUri); //from Gallery
if (path == null)
path = mImageCaptureUri.getPath(); //from File Manager
if (path != null)
bitmap = BitmapFactory.decodeFile(path);
} else {
path = mImageCaptureUri.getPath();
bitmap = BitmapFactory.decodeFile(path);
}
mImageView.setImageBitmap(bitmap);
}
public String getRealPathFromURI(Uri contentUri) {
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri, proj, null, null,null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.cancel){
finish();
}else if(v.getId() == R.id.Savedb){
// Get the values provided by the user via the UI
String providedPersonname = NameEditText.getText().toString();
int providedPersonage = Integer.parseInt(AgeEditText.getText().toString());
String providedPersonemail = EmailEditText.getText().toString();
// Pass above values to the setter methods in POJO class
PersonDetailsvizon personDetailsVizonObj = new PersonDetailsvizon();
personDetailsVizonObj.setPersonName(providedPersonname);
personDetailsVizonObj.setPersonAge(providedPersonage);
personDetailsVizonObj.setPersonEmail(providedPersonemail);
// Add an undergraduate with his all details to a ArrayList
PersonDetailsVizonObjArrayList.add(personDetailsVizonObj);
// Inserting undergraduate details to the database is doing in a separate method
insertUndergraduate(personDetailsVizonObj);
// Release from the existing UI and go back to the previous UI
finish();
}
}
public void insertUndergraduate(PersonDetailsvizon parapersonDetailsVizonObj){
// First we have to open our DbHelper class by creating a new object of that
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(this);
// Then we need to get a writable SQLite database, because we are going to insert some values
// SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj.getWritableDatabase();
// ContentValues class is used to store a set of values that the ContentResolver can process.
ContentValues contentValues = new ContentValues();
// Get values from the POJO class and passing them to the ContentValues class
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_PERSON_EMAIL, parapersonDetailsVizonObj.getPersonName());
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_PERSON_AGE, parapersonDetailsVizonObj.getPersonAge());
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_PERSON_EMAIL, parapersonDetailsVizonObj.getPersonEmail());
// Now we can insert the data in to relevant table
// I am going pass the id value, which is going to change because of our insert method, to a long variable to show in Toast
long affectedColumnId = sqliteDatabase.insert(AndroidOpenDbHelper.TABLE_NAME_VIZON, null, contentValues);
// It is a good practice to close the database connections after you have done with it
sqliteDatabase.close();
// I am not going to do the retrieve part in this post. So this is just a notification for satisfaction 😉
Toast.makeText(this, “Values inserted column ID is :” + affectedColumnId, Toast.LENGTH_SHORT).show();
}
}
here is my log cat data
02-17 11:57:23.830: W/ProcessStats(894): Skipping unknown process pid 13201
02-17 11:57:23.840: W/ProcessStats(894): Skipping unknown process pid 13203
02-17 11:57:24.820: D/dalvikvm(13125): GC_CONCURRENT freed 162K, 4% free 6699K/6919K, paused 8ms+5ms
02-17 11:57:24.850: W/IInputConnectionWrapper(13125): finishComposingText on inactive InputConnection
02-17 11:57:25.910: E/SQLiteDatabase(13125): Error inserting person_age_column=12 person_email_column=dasfd
02-17 11:57:25.910: E/SQLiteDatabase(13125): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:113)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1718)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1591)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at com.vizon.dezndemo.Add_Rec_Form.insertUndergraduate(Add_Rec_Form.java:184)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at com.vizon.dezndemo.Add_Rec_Form.onClick(Add_Rec_Form.java:158)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.view.View.performClick(View.java:3511)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.view.View$PerformClick.run(View.java:14105)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.os.Handler.handleCallback(Handler.java:605)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.os.Handler.dispatchMessage(Handler.java:92)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.os.Looper.loop(Looper.java:137)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at android.app.ActivityThread.main(ActivityThread.java:4424)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at java.lang.reflect.Method.invokeNative(Native Method)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at java.lang.reflect.Method.invoke(Method.java:511)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-17 11:57:25.910: E/SQLiteDatabase(13125): at dalvik.system.NativeStart.main(Native Method)
02-17 11:57:25.930: W/WindowManager(894): Failure taking screenshot for (120×180) to layer 21020
02-17 11:57:46.120: W/ProcessStats(894): Skipping unknown process pid 13480
02-17 11:58:37.041: W/ThrottleService(894): unable to find stats for iface rmnet0
02-17 11:58:42.102: W/ProcessStats(894): Skipping unknown process pid 14267
02-17 11:58:42.112: W/ProcessStats(894): Skipping unknown process pid 14269
Hi,,,thanks for help in posting data,,and i need a small information,”WHAT ABOUT THE CLASS FILE MISSED IN THE PROJECT NAME “UndergraduateDetailsPojo”, IF I NEED TO CREATE THAT CLASS MEANS THEN WHAT FUNCTION NEED TO DO.IF YOU HAVE CODE FOR THAT CLASS FILE PLEASE DO SHARE ME FOR INSERTING DATA IF WANT TO POST ME PERSONALLY YOU CAN MAIL ME @ kalyan.pilla01@gmail.com “
hey can you send it to me ikhlas.goodasahib@gmail.com
very interesting
You have made some good points there. I checked on the internet to learn more about the issue and found most people will go along with your views on this website.
It’s hard to find well-informed people in this particular topic, but you sound like you know what you’re talking about! Thanks
This is the perfect blog for anybody who wants to find out about this topic. You realize a whole lot its almost hard to argue with you (not that I personally will need to…HaHa). You definitely put a fresh spin on a subject which has been written about for years. Great stuff, just great!
I was excited to find this web site. I need to to thank you for your time just for this wonderful read!! I definitely savored every part of it and i also have you book marked to check out new things on your blog.
I can’t definitely enable but admire your blog, your blog is so adorable and great “
HI..
i m downloading a .txt from server that contains bullets how can i keep track of these bullets in my sqlite database or is there any way to show bullets from database to text view please replay me on this mail id..shivkant.t@gmail.com..thanks..
Hi…this post is really very helpful i done it but when i am checking db i complete with all those steps like…..i click on window>open perspective >ddms>file explorer window but im nt getting that data directory to explor….while clicking on file explorer it is blank
i want to do all the insertions(add dept details,add employee details-adding student details,teacher details etc),deletions,selections in my database using separate classes insertion,deletion,selection..how do i do so…
Excellent. You have made my day. Quodos!
There no database created in DDMS?? anujarosha i will be pleased if you reply me
Tell me what to do??
Pls send me the names of XML files!!!!!!
plz tell me the code for how to insert data from sqlite database into spinner in android
pooja.chankeshwara30@gmail.com
hey can we insert captured image in database
Normally what we do is, store images in SD card and insert image location in database.
THANK YOU! I cried for days thinking my codes didn’t work. Apparently it works with your soothing guide. All I need to do is check it with the sqlite database storage. You’re an angel.
great blog bro… 🙂 i want to know how to get the database not stored in the assets folder, but db file on the cloud, maybe you know how to do it bro, please help me i have been parse json to get db file but it’s fail 😥 hahahh, oke dude i will waiting you…
This blog was… how do I say it? Relevant!! Finally I have found something that helped
me. Cheers!
Thank u very much dear…
Thank u very much yarr for this post
Hi Anujarosha,
I want to store 1000 records in(sqlite) my android app.
How do I store this kind of data.
I want to store 5 table and 1000 records approx.
plz reply.
In ubuntu 14.04.. And i am using eclipse.
When i get the toast defined in InsertUndergraduate, it always says the affected column is -1. is this normal?
i wants to insert database in sqlite for student details its not working which u shown please help me….
Thnx for this post, How to add Paragraph in database and retrive it as a paragraph???
Good article. I absolutely love this website.
Continue the good work!
Nice I like it.
I want to make admin panel using sqlite database Without php. Can I do this?
hi… i want full code of this project.
murariramshyam@gmail.com
Please send me code or link of a code