SQLite DataBase Simple Example In Android

SQLite DataBase Simple Example In Android

SQLite is an opensource SQL database in android which stores data in an Android device. SQLite is a build in database which comes in android OS.

Example:
In this tutorial we will save in one activity and retrieve the data in another activity from database with a simple example.
  • Create a new project as DataBase.
  • Design the main layout file as follows.
File: activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hss_24.database.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:gravity="center"
        android:text="Android Lovers"
        android:textColor="@color/colorPrimary"
        android:textSize="25sp"
        android:textStyle="bold" />


    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:hint="Enter Name" />

    <EditText
        android:id="@+id/edit2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:hint="Enter Roll No" />

    <EditText
        android:id="@+id/edit3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:hint="Enter College" />

    <EditText
        android:id="@+id/edit4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:hint="Enter Course" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/colorAccent"
        android:text="Save"
        android:textColor="#FFFFFF"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:text="Retrieve"
        android:textColor="#FFFFFF"
        android:textStyle="bold" />

</LinearLayout>

  • Design the main2 layout file as follows.
File: activity_main2.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hss_24.database.Main2Activity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="20dp"
        android:textColor="@color/colorAccent"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:textColor="@color/colorAccent"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/text3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:textColor="@color/colorAccent"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/text4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        android:textSize="18sp" />

</LinearLayout>

  • Create a new java class as DataBaseHelper which is used to handle all the database functions.
File: DataBaseHelper.java:

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

public class DatabaseHelper extends SQLiteOpenHelper {

    //    database name and version
    public static String DATABASE_NAME = "sample.db";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    //    create database table and columns
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create TABLE IF NOT EXISTS College" + "(id integer primary key,name text,roll_no text,college text,course text)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    //    insert the data into database columns
    public void insertRow(String name, String roll_no, String college, String course) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cn = new ContentValues();

        cn.put("name", name);
        cn.put("roll_no", roll_no);
        cn.put("college", college);
        cn.put("course", course);
        db.insert("College", null, cn);
    }

    //    get the data from database
    public Cursor get() {
        SQLiteDatabase db = this.getReadableDatabase();

        String str = "select * from College";
        Cursor cursor = db.rawQuery(str, null);
        cursor.moveToFirst();
        return cursor;
    }
}

  • Do the following code in main java file to save data into database.
File: MainActivity.java:
import android.content.Intent;
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 name, rool_number, college, course;
    Button save, retrive;
    String name_str, roolNo_str, college_str, course_str;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final DatabaseHelper db = new DatabaseHelper(this);

        name = (EditText) findViewById(R.id.edit);
        rool_number = (EditText) findViewById(R.id.edit2);
        college = (EditText) findViewById(R.id.edit3);
        course = (EditText) findViewById(R.id.edit4);

        save = (Button) findViewById(R.id.btn);
        retrive = (Button) findViewById(R.id.btn2);

        // get the data from edittext store into strings and then save into database
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                name_str = name.getText().toString();
                roolNo_str = rool_number.getText().toString();
                college_str = college.getText().toString();
                course_str = course.getText().toString();

                db.insertRow(name_str, roolNo_str, college_str, course_str);
                Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
                name.setText("");
                rool_number.setText("");
                college.setText("");
                course.setText("");
                db.close();

            }
        });

        retrive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                startActivity(intent);
            }
        });


    }
}

  • Do the following code in main2 java file to retrieve data from database and show it in textview's.
File: Main2Activity.java:
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {
    TextView name, rool_no, college, course;
    String name_str, roll_str, college_str, course_str;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        name = (TextView) findViewById(R.id.text);
        rool_no = (TextView) findViewById(R.id.text2);
        college = (TextView) findViewById(R.id.text3);
        course = (TextView) findViewById(R.id.text4);


        //  retrieve data from database and show in textview's
        DatabaseHelper db = new DatabaseHelper(this);
        Cursor values = db.get();
        values.moveToFirst();
        while (values.isAfterLast() == false) {
            name_str = values.getString(1);
            roll_str = values.getString(2);
            college_str = values.getString(3);
            course_str = values.getString(4);

            values.moveToNext();
        }


        name.setText("" + name_str);
        rool_no.setText("" + roll_str);
        college.setText("" + college_str);
        course.setText("" + course_str);

    }
}

  • Run the app and enjoy the database.
Output:



Download project
Please like and share...



Comments