SQLITE Database in Android Application with Recyclerview and cardview.

What is SQLite database?


SQLite is not a client-server database engine.Rather,it is embedded into the end program.SQLite is
an in-process library that implements a self-contained, serverless, zero-configuration, transactional
 SQL database engine. SQLite a popular database engine choice on memory constrained gadgets such as cellphones, PDAs, and MP3 players. SQLite requires of minimum  space (4KiB).

SQLite in Android: 

  • SQLite is embedded into every Android device. Using an SQLite database in Android does not require a setup procedure or administration of the database.
  • You have to take care of SQL query for creating and updating database.After that android platform automatically create the database and  table.
  • Access to an SQLite database involves accessing the file system. This can be slow. Therefore it is recommended to perform database operations asynchronously.
  • If your application creates a database, this database is by default saved in the directory DATA/data/APP_NAME/databases/FILENAME.


SQLite architecture:

SQLite Package - In Android, android database contains all the necessary class related to database. The android.database.sqlite contains sqlite specific class.

To create sqlite database in android, You have to extends SQLiteOpenHelper class. 
You have to override two methods  :-
1)  onCreate() :  This method called when the database is created first time. This method is use for                                  crating tables .



2) onUpgrade() : It is called when the the database needs to be upgraded. you should use this method                               to drop tables,add table or do anything else it needs to upgrade to the new schema                                 version.

                             If you add new columns you can use ALTER TABLE to insert them into a live                                    table.If you rename or remove columns you can use ALTER TABLE to rename                                  the old table,then create the new table and then populate the new table with the                                    contents of the old table.

Both methods receive an SqliteDatabase object as parameter which is the java representation of the database. 
The SqliteOpenHelpher class provides the getReadleDatabase()  and getWritableDatabase() methods to get access to an SqliteDatabase object  either in read or write mode.


Helping classes in SqliteDatabase

Content Values:
The object ContentValues allows to define key/values. The key represents the table column name and the Value represents the content for the table record in this column.Content Values can be used for insert and updates of database entries. 

Cursor:
When a query fires in sqlite database it returns  a Cursor object. A cursor represents the result of a query and basically points to one row of the query result. This way Android retrieve the result of query. It does not have to load all data into memory.

Cursor class has many methods: Here is some of that

getCount() - It gives the number of rows resultant query.

moveToFirst() -To move cursor  first rows .

moveToLast() - To move the cursor to last row.

moveToNext() - To move the cursor in next row.





Now I have implemented database by programming.


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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter Name"/>
        <EditText
            android:id="@+id/etName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter Roll"/>
        <EditText
            android:id="@+id/etRoll"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter Address"/>
        <EditText
            android:id="@+id/etAddress"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter Branch"/>
        <EditText
            android:id="@+id/etBranch"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter Email"/>
        <EditText
            android:id="@+id/etEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btnSubmit"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Submit"
            android:textColor="#ffffff"
            android:background="@color/colorPrimary"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btngetdata"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Get Data"
            android:textColor="#ffffff"
            android:background="@color/colorPrimary"/>

    </LinearLayout>
</LinearLayout>


MainActivity.java

package com.example.prabhu.databasedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    EditText etName,etRoll,etAddress,etBranch,etEmail;
    Button btnSubmit,btngetdata;
    DatabaseHelpher helpher;
    List<DatabaseModel> dbList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        dbList= new ArrayList<DatabaseModel>();
        etName = (EditText)findViewById(R.id.etName);
        etRoll = (EditText)findViewById(R.id.etRoll);
        etAddress =(EditText)findViewById(R.id.etAddress);
        etBranch = (EditText)findViewById(R.id.etBranch);
        etEmail = (EditText)findViewById(R.id.etEmail);
        btnSubmit  =(Button)findViewById(R.id.btnSubmit);
btngetdata =(Button)findViewById(R.id.btngetdata);
        btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, SecondActivity.class));

               // startActivity(new Intent(MainActivity.this, DetailsActivity.class));

            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String name=etName.getText().toString();
                String email=etEmail.getText().toString();
                String roll=etRoll.getText().toString();
                String address=etAddress.getText().toString();
                String branch=etBranch.getText().toString();

            if(name.equals("") || email.equals("") || roll.equals("") ||address.equals("")||branch.equals("")){
                Toast.makeText(MainActivity.this,"Please fill all the fields",Toast.LENGTH_LONG).show();
            }else {
                helpher = new DatabaseHelpher(MainActivity.this);
                helpher.insertIntoDB(name, email, roll, address, branch);
            }
                etName.setText("");
                etRoll.setText("");
                etAddress.setText("");
                etBranch.setText("");
                etEmail.setText("");

                Toast.makeText(MainActivity.this, "insert value", Toast.LENGTH_LONG);

            }
        });

    }



}

DatabaseHelpher.java

package com.example.prabhu.databasedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

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

/**
 * Created by PRABHU on 11/12/2015.
 */
public class DatabaseHelpher extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="student";
    private static final int DATABASE_VERSION = 1;
    private static final String STUDENT_TABLE = "stureg";
    private static final String STU_TABLE = "create table "+STUDENT_TABLE +"(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT)";

Context context;

    public DatabaseHelpher(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(STU_TABLE);
    }

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

        db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);

        // Create tables again
        onCreate(db);
    }
/* Insert into database*/
    public void insertIntoDB(String name,String email,String roll,String address,String branch){
        Log.d("insert", "before insert");

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("email", email);
        values.put("roll", roll);
         values.put("address", address);
        values.put("branch", branch);

        // 3. insert
        db.insert(STUDENT_TABLE, null, values);
        // 4. close
        db.close();
        Toast.makeText(context, "insert value", Toast.LENGTH_LONG);
        Log.i("insert into DB", "After insert");
    }
/* Retrive  data from database */
    public List<DatabaseModel> getDataFromDB(){
        List<DatabaseModel> modelList = new ArrayList<DatabaseModel>();
        String query = "select * from "+STUDENT_TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);

        if (cursor.moveToFirst()){
            do {
                DatabaseModel model = new DatabaseModel();
                model.setName(cursor.getString(0));
                model.setEmail(cursor.getString(1));
                model.setRoll(cursor.getString(2));
                model.setAddress(cursor.getString(3));
                model.setBranch(cursor.getString(4));

                modelList.add(model);
            }while (cursor.moveToNext());
        }


        Log.d("student data", modelList.toString());


        return modelList;
    }


    /*delete a row from database*/

    public void deleteARow(String email){
        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
        db.close();
    }


}

OUTPUT











You can find the complete project on GitHub 

SHARE

About Abhsihek Chaubey

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment