Saturday 30 July 2016

SQLite Database | Example to Add,Delete,Update and Get the data from SQLite Database.

SQLite is a opensource SQL database that stores data to a text file in the device. Android comes in with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

Database - Package
The main package is android.database.sqlite that contains the classes to manage your own databases

Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below


************************************Example****************************
Step1:- Open your Android Studio.
Step2:-Click on File >New >New Project > SQLiteExample
Step3:-Click on res>activity_main.xml and take 3 EditText 4 Button

design will be like below ...image...


Step3:- the coding of  activity_main.xml willl be like following...

<?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:orientation="vertical">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:id="@+id/edtId"
        android:hint="Enter Id"
        android:layout_marginTop="30dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:id="@+id/edtName"
        android:hint="Enter Name"
        android:layout_marginTop="30dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:id="@+id/edtPhone"
        android:hint="Enter Phone"
        android:layout_marginTop="30dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Insert"
            android:id="@+id/btnInsert"
            android:background="#99C329"
            android:layout_marginLeft="10dp"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Delete"
            android:id="@+id/btnDelete"
            android:background="#99C329"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="10dp"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Update"
            android:id="@+id/btnUpdate"
            android:background="#99C329"
            android:layout_marginLeft="10dp"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Get"
            android:id="@+id/btnGet"
            android:background="#99C329"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="10dp"/>
    </LinearLayout>


</LinearLayout>


Step4:-MainActivity.java code will be following....

package androidhubb.databaseexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText edtId,edtName,edtPhone;
    Button btnInsert,btnDelete,btnGet,btnUpdate;
    SQLiteDatabase db;

    @Override    
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //id..       
 edtId=(EditText)findViewById(R.id.edtId);
        edtName=(EditText)findViewById(R.id.edtName);
        edtPhone=(EditText)findViewById(R.id.edtPhone);
        //id        
btnInsert=(Button)findViewById(R.id.btnInsert);
        btnDelete=(Button)findViewById(R.id.btnDelete);
        btnUpdate=(Button)findViewById(R.id.btnUpdate);
        btnGet=(Button)findViewById(R.id.btnGet);

        //create database..        
db=openOrCreateDatabase("MyDatabase", Context.MODE_PRIVATE,null);

        //create table inside database..        
db.execSQL("create table if not exists student(ID integer PRIMARY KEY AUTOINCREMENT NOT NULL,NAME varchar(20),PHONE varchar(11))");


        //insert..        
btnInsert.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                ContentValues cv=new ContentValues();
                cv.put("ID",Integer.parseInt(edtId.getText().toString().trim()));
                cv.put("NAME",edtName.getText().toString().trim());
                cv.put("PHONE",edtPhone.getText().toString().trim());

                long i=db.insert("student",null,cv);
                if(i>0){
                    Toast.makeText(getApplicationContext(),"Data Inserted Successfully",Toast.LENGTH_LONG).show();
                }
                edtId.setText("");
                edtName.setText("");
                edtPhone.setText("");


            }
        });

        //delete...        
btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                db.delete("student","ID=?",new String[]{edtId.getText().toString().trim()});
                edtId.setText("");
            }
        });

        //update..        
btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                ContentValues cv=new ContentValues();
                cv.put("ID",Integer.parseInt(edtId.getText().toString().trim()));
                cv.put("NAME",edtName.getText().toString().trim());
                cv.put("PHONE",edtPhone.getText().toString().trim());
                db.update("student",cv,"ID=?",new String[]{edtId.getText().toString().trim()});
                edtId.setText("");
                edtName.setText("");
                edtPhone.setText("");


            }
        });
        //get...        
btnGet.setOnClickListener(new View.OnClickListener() {
            @Override            
public void onClick(View v) {
                Cursor c=db.rawQuery("select * from student",null);
                while(c.moveToNext()){
                    Toast.makeText(getApplicationContext(),c.getInt(0)+"\n"+c.getString(1)+"\n"+c.getString(2),Toast.LENGTH_LONG).show();
                }
            }
        });




    }
}

Output Screen;---





No comments:

Post a Comment