Android Sqlite Tutorial

Android Sqlite Tutorial



Source Code:
https://www.dropbox.com/s/63vufkq32zp5g07/Sqlite.zip?dl=0

Step 1:
We need to create database

package com.example.slide;

import java.util.ArrayList;
import java.util.List;

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

public class DatabaseHandler extends SQLiteOpenHelper {

//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "Test";
//Table Name
private static final String TABLE_TEST = "TestTable";
//Column Name
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_AGE = "age";

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

//Create Table
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_AGE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEST);
onCreate(db);
}

//Insert Value
public void adddata(Context context,String movieId,String songId) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, movieId);
values.put(KEY_AGE, songId);
db.insert(TABLE_TEST, null, values);
db.close();
}

//Get Row Count
public int getCount() {
String countQuery = "SELECT  * FROM " + TABLE_TEST;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}

//Delete Query
public void removeFav(int id) {
String countQuery = "DELETE FROM " + TABLE_TEST + " where " + KEY_ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(countQuery);
}

//Get FavList
public List<FavoriteList> getFavList(){
String selectQuery = "SELECT  * FROM " + TABLE_TEST;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<FavoriteList> FavList = new ArrayList<FavoriteList>();
if (cursor.moveToFirst()) {
do {
FavoriteList list = new FavoriteList();
list.setId(Integer.parseInt(cursor.getString(0)));
list.setName(cursor.getString(1));
list.setAge(cursor.getString(2));
FavList.add(list);
} while (cursor.moveToNext());
}
return FavList;
}

}

Step 2:
We need to create Activity with listview using Base Adapter
package com.example.slide;

import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
FavoriteList favList = new FavoriteList();
Button add,checkcount,list;
Context context = this;
DatabaseHandler db;
ListView listView;
List<FavoriteList> favoriteList;
LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

add = (Button)findViewById(R.id.add);
add.setOnClickListener(addOnClick);
checkcount = (Button)findViewById(R.id.checkcount);
checkcount.setOnClickListener(checkcountOnClick);
list = (Button)findViewById(R.id.list);
list.setOnClickListener(listOnClick);
layout = (LinearLayout)findViewById(R.id.layout);
listView = (ListView)findViewById(R.id.listView);
db = new DatabaseHandler(this);

//db.removeFav();

/*favList = db.getFavList();
Toast.makeText(getApplicationContext(), ""+favList.getSongname(), Toast.LENGTH_LONG).show();*/
}

View.OnClickListener addOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.row);
dialog.setTitle("Add Data to Database");
final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText age = (EditText) dialog.findViewById(R.id.age);
Button Add = (Button) dialog.findViewById(R.id.Add);
Add.setText("Add");
Add.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(name.getText().toString() != null && name.getText().toString().length() >0 ){
if(age.getText().toString() != null && age.getText().toString().length() >0 ){
db.adddata(context, name.getText().toString(), age.getText().toString());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
dialog.dismiss();
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Age", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Please Enter the Name", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
};

View.OnClickListener checkcountOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
int uyu = db.getCount();
Toast.makeText(getApplicationContext(), ""+uyu, Toast.LENGTH_LONG).show();
}
};

View.OnClickListener listOnClick = new OnClickListener() {
@Override
public void onClick(View v) {
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
};

public class ViewAdapter extends BaseAdapter {

LayoutInflater mInflater;

public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
return favoriteList.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem,null);
}

final TextView nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText("Name : "+favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView.findViewById(R.id.ageText);
ageText.setText("Age : "+favoriteList.get(position).getAge());

final Button delete = (Button) convertView.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
notifyDataSetChanged();
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
return convertView;
}
}
}


XML files

We need to create activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:text="Add Data to Database"
            android:textColor="#228B22"
            android:textSize="16dp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:text="Add"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:text="Show List of Data"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/checkcount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:text="Check value Count"
            android:textColor="#FFFFFF" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="5dp"
        android:layout_weight="1" >

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>
</LinearLayout>


BaseAdapter listview XML is listitem.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/nameText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#228B22" />

            <TextView
                android:id="@+id/ageText"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#228B22" />
        </LinearLayout>

        <Button
            android:id="@+id/edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:text="Edit"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="2dp"
            android:background="@drawable/buttoncolor"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:text="Delete"
            android:textColor="#FFFFFF" />
    </LinearLayout>


</LinearLayout>

We need to create Model for storing the data
FavoriteList .java

package com.example.slide;

public class FavoriteList {

//private variables
int id;
String name;
String age;

// Empty constructor
public FavoriteList(){

}
// constructor
public FavoriteList(int id, String name, String age){
this.id = id;
this.name = name;
this.age = age;
}

// getting id
public int getId(){
return this.id;
}

// setting id
public void setId(int id){
this.id = id;
}

// getting name
public String getName(){
return this.name;
}

// setting name
public void setName(String name){
this.name = name;
}

// getting Moviename
public String getAge(){
return this.age;
}

// setting Moviename
public void setAge(String age){
this.age = age;
}

}

I have used buttoncolor.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
 
    <padding android:top="7dp"
        android:bottom="7dp"/>
 
    <corners android:radius="7dp"/>

    <solid android:color="#228B22"/>
 

</shape>

Another one is shape.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
 
    <padding android:top="7dp"
        android:bottom="7dp"/>
 
    <stroke android:color="#228B22" android:width="2dp"/>
 
    <corners android:radius="7dp"/>

    <solid android:color="#FFFFFF"/>
 

</shape>


70 comments

Thanks, nice tutorial!

You only have forgot to post the code for the "Add" dialog. The button "Edit" does not work, there is no code for it, but nevermind

Reply

i will update shortly

Reply

I"m missing something; can't get this to work. Class ViewAdapter has no reference to db or favorite list.

Reply

Can you send your mail id?
I will send the updated source code.

Reply

Where is the EditText name and age in your xml file

Reply

also the layout row in the addOnClick

Reply

Hi Refer the below source code : https://www.dropbox.com/s/63vufkq32zp5g07/Sqlite.zip?dl=0

Reply

The add and edit just need to be coded on the DatabaseHandler right?

Reply

I tried to to implement this code in my app but am getting an null point exception at the set adapter, the app does not crash but no listview is also not getting populated.

Reply

Edit button is not working :( How can I get the updated source code???

Reply

sorry ,can u help me how to combine simple code application with database code

Reply
This comment has been removed by the author.

can i have the updated code?

Reply


Very very disorganized. Did you know that there are scripts to leave the source codes organized visually. Visitors thank you! I appreciate it!

Reply

One more thing: split your code into MVC, you could put create a class only to create the bank and another with the methods that will register, select, update ... If this your application has a serious error will be difficult to do a maintenance in him.

Reply


There are lots of information about a have spread around the web, but this is a unique contact one according to me. The strategy you have updated here will make me get to the next level in Android. Thanks for sharing this.
Selenium Training in Chennai
Android Training in Chennai

Reply

Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.Best Android Training in chennai|Android Training in chennai with placement | Android Training in velachery

Reply

Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more .Android Training in chennai with placement | Android Training in velachery

Reply

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.
QlikView Training in Chennai
Informatica Training in Chennai
Python Training in Chennai
AngularJS Training in Chennai
Best AngularJS Training in Chennai

Reply

Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
python training in chennai | python training in bangalore

python online training | python training in pune

python training in chennai | python training in bangalore

python training in tambaram |

Reply

Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.


Hadoop Training in Chennai

Aws Training in Chennai

Selenium Training in Chennai

Reply

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.
Devops Training in pune|Devops training in tambaram|Devops training in velachery|Devops training in annanagar
DevOps online Training

Reply

Wonderful article, very useful and well explanation. Your post is extremely incredible. I will refer this to my candidates...
python training in Bangalore
python training in pune

Reply

I really like your blog. You make it interesting to read and entertaining at the same time. I cant wait to read more from you.
python online training
python training in OMR
python training in tambaram
python training in annanagar

Reply
This comment has been removed by the author.

After reading your post I understood that last week was with full of surprises and happiness for you. Congratz! Even though the website is work related, you can update small events in your life and share your happiness with us too.


angularjs Training in chennai
angularjs Training in chennai

angularjs-Training in tambaram

angularjs-Training in sholinganallur

angularjs-Training in velachery

Reply

I would assume that we use more than the eyes to gauge a person's feelings. Mouth. Body language. Even voice. You could at least have given us a face in this test.

Data science course in tambaram | Data Science course in anna nagar
Data Science course in chennai | Data science course in Bangalore
Data Science course in marathahalli | Data Science course in btm

Reply

Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that
safety course in chennai

Reply

Wow!! Really a nice Article. Thank you so much for your efforts. Definitely, it will be helpful for others. I would like to follow your blog. Share more like this. Thanks Again.
iot training in Chennai | Best iot Training Institute in Chennai

Reply

Right now, DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

devops course fees in chennai | devops training in chennai with placement | devops training in chennai omr | best devops training in chennai quora | devops foundation certification chennai

Reply


Nice blog..! I really loved reading through this article. Thanks for sharing such a
amazing post with us and keep blogging... best angularjs training institute in chennai | angularjs training in omr | angularjs best training center in chennai | angularjs training in velachery

Reply

After reading your post I understood that last week was with full of surprises and happiness for you. Congratz! Even though the website is work related, you can update small events in your life and share your happiness with us too.

Microsoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training


Reply

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.

angularjs online training

apache spark online training

informatica mdm online training

devops online training

aws online training

Reply

https://designhap.blogspot.com/2016/06/web-designing-made-simple-free-tools.html?showComment=1553755894200#c717848682621945331

Reply
This comment has been removed by the author.

Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
python training in bangalore

Reply

very useful and Informative article thank you so much for sharing this information
Selenium training in chennai | Selenium training in velachery

Reply

Thanks for this post. It proves very informative for me. Great post to read. Keep blogging.

If you are looking for the top security companies in London that provide its customer with remarkable security services. Check out this site for security services and close protection security companies

Reply

Very nice post here and thanks for it .I always like and such a super contents of these post. oracle training in chennai

Reply

best indian seo buy tools 2021, use from mobile device and pc.

Reply

Excellent Blog!!! The blog which you have shared here is more informative, This is really too useful and have more ideas and keep sharing many techniques about DevOps. Thanks for giving a such a wonderful blog.
DevOps Training in Chennai

DevOps Course in Chennai

Reply

Dream your career towards Big Data? Then come to Infycle Technologies, the best software training center in Chennai, which gives the combined and best Big Data Hadoop Training in Chennai, in a 100% hands-on training guided by professional teachers in the field. In addition to this, the interviews for the placement will be guided to the candidates, so that, they can face the interviews without struggles. Apart from all, the candidates will be placed in the top MNC's with a bet salary package. Call 7502633633 and make this happen for your happy life.

Reply

If Big Data is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best Hadoop Training in Chennai, with various levels of highly demanded software courses such as Oracle, Java, Python, Big Data, etc., in 100% hands-on practical training with specialized tutors in the field. Along with that, the pre-interviews will be given for the candidates, so that, they can face the interviews with complete knowledge. To know more, dial 7502633633 for more.Big Data Training in Chennai

Reply

Worth reading! Our experts also have given detailed inputs about these trainings & courses! Presenting here for your reference. Do checkout oracle sql training in chennai & enjoy learning more about it.

Reply

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

Reply

Reach to the best Python Training institute in Chennai. for skyrocketing your career, Infycle Technologies. It is the best Software Training & Placement institute in and around Chennai, that also gives the best placement training for personality tests, interview preparation, and mock interviews for leveling up the candidate's grades to a professional level.

Reply

Grab the Digital Marketing Training in Chennai from Infycle Technologies, the best software training institute, and Placement center in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Cyber Security, Big Data, Java, Hadoop, Selenium, Android, and iOS Development, DevOps, Oracle etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

Reply

Infycle Technologies, the top software training institute and placement center in Chennai offers the Digital Marketing course in Chennai for freshers, students, and tech professionals at the best offers. In addition to the Oracle training, other in-demand courses such as DevOps, Data Science, Python, Selenium, Big Data, Java, Power BI, Oracle will also be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

Reply

This post is so interactive and informative.keep update more information...
Spoken English Classes in Tambaram
Spoken English Classes in Chennai

Reply

Very well explained.Thanks for sharing. It was very useful.
SQL Course in Pune

Reply

Post a Comment