Wednesday, June 20, 2012

Insert Data in SQLite Database using Android Application

Hello user, today i am going to show how to create database in SQLite and Learn to insert data in database.
Here two field i have taken no and name.
To set watermark on field take <editText android:hint="No" />


<linearlayout android:baselinealigned="false" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android=
"http://schemas.android.com/apk/res/android">
<textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="@string/hello">
<edittext android:hint="No" android:id="@+id/txtNo" android:layout_height="wrap_content" android:layout_width="match_parent">
<requestfocus></requestfocus>
</edittext>
<edittext android:hint="Name" android:id="@+id/txtName" android:layout_height="wrap_content" android:layout_width="match_parent"></edittext>
<button android:id="@+id/Save" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Save"></button>
</textview></linearlayout>
Now Let start with coding.
DatabaseDemo.java

package com.databasedemo.db;


import android.app.Activity;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class DatabaseDemo1Activity extends Activity implements OnClickListener 
{
    /** Called when the activity is first created. */
    EditText etno,etname;
    Button btnSave;
    DatabaseAdapter dbAdapter;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        dbAdapter=new DatabaseAdapter(getApplicationContext());
        
        etno=(EditText)findViewById(R.id.txtNo);
        etname=(EditText)findViewById(R.id.txtName);
        btnSave=(Button)findViewById(R.id.Save);
        btnSave.setOnClickListener(this);
    }
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.Save)
{
//Toast.makeText(getApplicationContext(), "save",Toast.LENGTH_LONG).show();
String no=etno.getText().toString();
String name=etname.getText().toString();
dbAdapter.open();
long inserted=dbAdapter.insertTest(no,name);
if(inserted>=0)
{
Toast.makeText(getApplicationContext(), "data saved",Toast.LENGTH_LONG).show();

etno.setText("");
etname.setText("");
}
else
{
Toast.makeText(getApplicationContext(), "data not saved",Toast.LENGTH_LONG).show();

}
dbAdapter.close();
}
}
}

Here i marked some text in red color, use it after creating DatabaseAdapter Class.
Now Take DatabaseOpenHelper class.


In DatabaseOpenHelper.java
In this class we will create database test_database.db and Table= test.
Make sure there must be space between create table and TABLE_NAME

package com.databasedemo.db;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseOpenHelper extends SQLiteOpenHelper {


public static final String DBName = "test_database.db";
public static final String TABLE_NAME = "test";
public static final String TABLE_SQL = "Create Table "+ TABLE_NAME 
+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"no TEXT, "
+"name TEXT);";

public DatabaseOpenHelper(Context context) {
super(context, DBName, null, 1);
// TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
          database.execSQL(TABLE_SQL);
}


@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub


}


}

To check whether Database is created or not check.
1. click on DDMS TAB.
2. click File Explorer tab.
3. click "data" to expand 
4. again click on "data" to expand
5. see the package name that we create."com.databasedemo.db"
6. in package you will see the "database" click on it
7. after clicking you will see the database name that we named.
do all this when you run application.
Now create DatabaseAdapter class.


In DatabaseAdapter.java

package com.databasedemo.db;


import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;


public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;

public DatabaseAdapter(Context context)
{
       dbHelper=new DatabaseOpenHelper(context);
       
}
public void open()
{
database=dbHelper.getWritableDatabase();
}
public void close()
{
database.close();
}
public long insertTest(String no,String name)
{
ContentValues values=new ContentValues();
values.put("no", no);
values.put("name", name);

return database.insert("test",null, values);
}
}
In next session we will see how to retrieve data
OUTPUT

32 comments:

  1. clear wording. keep it up

    ReplyDelete
  2. Hi, Thanks a thousand times.. This really saved my day

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. i have done with this code but there are shown error regarding database..please tell me detail steps and how can i do this...they are shown me error at red marked statements...

      Delete
  4. can i have the code of it that display in the listview or it can view

    ReplyDelete
  5. can anyone provide the .zip file of code?

    ReplyDelete
  6. I am getting App has stopped working. I think the error is due to the XML file.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. pls give me source code bcz it not working...so pls give me source code

    ReplyDelete
    Replies
    1. i think you did some mistake while doing code or missed some step

      Delete
  9. and also give the retrieve data code..pls

    ReplyDelete
    Replies
    1. I have done with same code but its done day long i need to search if i get i will give you

      Delete
  10. u can refer this link to view in listview
    http://androidsolution4u.blogspot.in/2013/09/android-populate-listview-from-sqlite.html

    ReplyDelete
  11. I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article.
    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune
    Data science training in kalyan nagar

    ReplyDelete
  12. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read  about their market situation nowadays.
    java training in annanagar | java training in chennai

    java training in marathahalli | java training in btm layout

    java training in rajaji nagar | java training in jayanagar

    java training in chennai

    ReplyDelete
  13. I am so proud of you and your efforts and work make me realize that anything can be done with patience and sincerity. Well I am here to say that your work has inspired me without a doubt.
    Python training in marathahalli
    Python training institute in pune

    ReplyDelete
  14. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    apple service center chennai | ipod service center in chennai | apple iphone service center in chennai | apple service center chennai

    ReplyDelete
  15. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
    Data Science Training in Chennai
    Robotic Process Automation Training in Chennai
    Cloud Computing Training in Chennai
    Data Warehousing Training in Chennai
    Dev Ops Training in Chennai

    ReplyDelete
  16. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    AWS training in chennai | AWS training in anna nagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

    ReplyDelete
  17. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.Well somehow I got to read lots of articles on your blog. It’s amazing how interesting it is for me to visit you very often.
    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training


    ReplyDelete
  18. Very useful and information content has been shared out here, Thanks for sharing it. oracle training in chennai

    ReplyDelete
  19. Such a very useful Blog. Very interesting to read this article. I have learn some new information.thanks for sharing. data science courses

    ReplyDelete
  20. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.data scientist training in hyderabad

    ReplyDelete
  21. I think about it is most required for making more on this get engaged
    data scientist training and placement

    ReplyDelete
  22. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Selenium course in Chennai for tech professionals, freshers, and students at the best offers. In addition to the Selenium, other in-demand courses such as Python, Big Data, Oracle, Java, Python, Power BI, Digital Marketing, Cyber Security also will be trained with hands-on practical classes. After the completion of training, the trainees will be sent for placement interviews in the top companies. Call 7504633633 to get more info and a free demo.

    ReplyDelete