SQLite in Android Example

Here we'll create a simple Android Application to store user data into SQLite database.

Dependencies

To use RecyclerView in Android you need to add dependency:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1' 
    compile 'com.android.support:recyclerview-v7:+'
}

In this example we need to create:

    Activity

         MainActivity: contains java file and xml layout file
            MainActivity.java
            activity_main.xml

    Adapter

        MainAdapter.java
        Create a constructor to receive List of Users passed by the Activity Class
       
        Create a class MyViewHolder that will extends RecyclerView.ViewHolder
       
        Implement RecyclerView.Adapter and override three methods:
            onCreateViewHolder(…)
            onBindViewHolder (…)
            getItemCount(…)

Fragment

        AddFragment.java

        fragment_add.xml


    Other Layout

        single_view.xml
        for single record View inside RecyclerView

        content_main.xml

    Other Java files

        DatabaseHelper.java
        extends SQLiteOpenHelper to support database operations

        MainVO.xml
        POJO class for getters and setters


Source Code

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlDisplayArea"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.sushil.myapplication.MainActivity"
    android:background="@android:color/holo_blue_bright"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="false">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.sushil.myapplication.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <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/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_input_add" />

</android.support.design.widget.CoordinatorLayout>


single_view.xml
<?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="wrap_content"
    android:padding="16dp"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="4dp">

        <TextView
            android:id="@+id/tvTextName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name: "/>

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/tvTextName"
            android:text="Sushil"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="4dp">

        <TextView
            android:id="@+id/tvTextAge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Age: "/>

        <TextView
            android:id="@+id/tvAge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tvTextAge"
            android:text="99"/>

        <TextView
            android:id="@+id/tvTextPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Phone: "
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/tvAge"
            android:layout_toEndOf="@+id/tvAge"
            android:layout_marginLeft="67dp"
            android:layout_marginStart="67dp" />

        <TextView
            android:id="@+id/tvPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="89999999"
            android:layout_alignParentTop="true"
            android:layout_toRightOf="@+id/tvTextPhone"/>

    </RelativeLayout>

</LinearLayout>

fragment_add.xml
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#F0F0F0"
    android:layout_height="match_parent">

    <RelativeLayout 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"
        tools:context="com.example.sushil.myapplication.AddFragment">

        <TextView
            android:id="@+id/tvName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:textSize="22sp"
            android:layout_margin="12dp"
            android:text="@string/name"/>

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_margin="12dp"
            android:layout_below="@+id/tvName"/>

        <TextView
            android:id="@+id/tvAge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:layout_below="@id/etName"
            android:textSize="22sp"
            android:layout_margin="12dp"
            android:text="@string/age"/>

        <EditText
            android:id="@+id/etAge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:layout_margin="12dp"
            android:layout_below="@+id/tvAge"/>

        <TextView
            android:id="@+id/tvPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:textSize="22sp"
            android:text="@string/phone"
            android:layout_below="@+id/etAge"
            android:layout_margin="12dp" />

        <EditText
            android:id="@+id/etPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="phone"
            android:layout_margin="12dp"
            android:layout_below="@+id/tvPhone"/>

        <Button
            android:id="@+id/btnSave"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/etPhone"
            android:layout_margin="12dp"
            android:text="Save"/>

    </RelativeLayout>
</ScrollView>


ActivityMain.java
package com.example.sushil.myapplication;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fragmentManager = getFragmentManager();

                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                AddFragment addFragment = new AddFragment();

                Bundle args = new Bundle();
                args.putInt("number", 5);
                addFragment.setArguments(args);

                fragmentTransaction.replace(R.id.rlDisplayArea, addFragment);
                fragmentTransaction.commit();
            }
        });

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvMain);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        DatabaseHelper db = new DatabaseHelper(this);
        List<MainVO> myData= db.readRecord();

        MainAdapter adapter = new MainAdapter(this, myData);
        for(int i = 0; i < myData.size(); i++){
            Log.i("sss Name",myData.get(i).getName());
            Log.i("sss Age",myData.get(i).getAge()+"");
            Log.i("sss Phone",myData.get(i).getPhone());
        }
        recyclerView.setAdapter(adapter);
    }

    public FloatingActionButton getFloatingActionButton() {
        return fab;
    }
}

AddFragment.java
package com.example.sushil.myapplication;

import android.app.Fragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddFragment extends Fragment implements View.OnClickListener{

    private static final String ARG_PARAM1 = "number";
    private int mParam1;

    EditText etName;
    EditText etAge;
    EditText etPhone;
    Button btnSave;

    private OnFragmentInteractionListener mListener;

    public AddFragment() {}

    public static AddFragment newInstance(int param1) {
        AddFragment fragment = new AddFragment();
        Bundle args = new Bundle();
        args.putInt(String.valueOf(ARG_PARAM1), param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Hiding Floating Action Button
        FloatingActionButton floatingActionButton = ((MainActivity) getActivity()).getFloatingActionButton();
        if (floatingActionButton != null) {
            floatingActionButton.hide();
        }

        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
            Log.i("Params",mParam1+"");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_add, container, false);
        etName = (EditText) view.findViewById(R.id.etName);
        etAge = (EditText) view.findViewById(R.id.etAge);
        etPhone = (EditText) view.findViewById(R.id.etPhone);
        btnSave = (Button) view.findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);

        return view;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {

        if (v == btnSave) {
            if (etName.getText().toString().trim().isEmpty()) {
                Toast.makeText(getActivity(), "Please Enter Name", Toast.LENGTH_LONG).show();
            } else if (etAge.getText().toString().trim().isEmpty()) {
                Toast.makeText(getActivity(), "Please Enter Age", Toast.LENGTH_LONG).show();
            } else if (etPhone.getText().toString().trim().isEmpty()) {
                Toast.makeText(getActivity(), "Please Enter Phone", Toast.LENGTH_LONG).show();
            } else {
                MainVO main = new MainVO();
                main.setName(etName.getText().toString());
                main.setAge(Integer.parseInt((etAge.getText()).toString()));
                main.setPhone(etPhone.getText().toString());
                DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
                databaseHelper.saveRecord(main);

                Toast.makeText(getActivity(), "Saved Successfully", Toast.LENGTH_LONG).show();
                etName.setText("");
                etAge.setText("");
                etPhone.setText("");
            }
        }
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}


MainAdapter.java
package com.example.sushil.myapplication;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MyViewHolder>{

    Context context;
    List<MainVO> mainList;
    public MainAdapter(Context context, List<MainVO> mainList) {
        this.context = context;
        this.mainList = mainList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.single_view, null);
        MyViewHolder myViewHolder = new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        MainVO main = mainList.get(position);
        holder.tvName.setText(main.getName());
        holder.tvAge.setText(String.valueOf(main.getAge()));
        holder.tvPhone.setText(String.valueOf(main.getPhone()));
    }

    @Override
    public int getItemCount() {
        Log.i("sss size",mainList.size()+"");
        return mainList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView tvName;
        TextView tvAge;
        TextView tvPhone;

        public MyViewHolder(View itemView) {
            super(itemView);
            tvName = (TextView) itemView.findViewById(R.id.tvName);
            tvAge = (TextView) itemView.findViewById(R.id.tvAge);
            tvPhone = (TextView) itemView.findViewById(R.id.tvPhone);
        }
    }
}

DatabaseHelper.java
package com.example.sushil.myapplication;

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

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

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "myapp";

    private static final String TABLE_MAIN = "main_table";

    private static final String ID = "id";
    private static final String NAME = "name";
    private static final String AGE = "age";
    private static final String PHONE = "phone";

    private static final String CREATE_TABLE_MAIN = "CREATE TABLE "
            + TABLE_MAIN + "(" + ID + " INTEGER PRIMARY KEY," + NAME
            + " TEXT," + AGE + " INTEGER," + PHONE  + " TEXT" + ")";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_MAIN);
    }

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

    public long saveRecord(MainVO main) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(NAME, main.getName());
        values.put(AGE, main.getAge());
        values.put(PHONE, main.getPhone());

        long id = db.insert(TABLE_MAIN, null, values);
        return id;
    }

    List<MainVO> allRecords = new ArrayList<>();
    public List<MainVO> readRecord() {
        SQLiteDatabase db = getReadableDatabase();
        //Cursor cursor = db.query(TABLE_MAIN, new String[] { NAME, AGE, PHONE}, null, null, null, null, null);
        String selectQuery = "SELECT  * FROM " + TABLE_MAIN;

        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                MainVO main = new MainVO();
                main.setName(cursor.getString(cursor.getColumnIndex(NAME)));
                main.setAge(cursor.getInt(cursor.getColumnIndex(AGE)));
                main.setPhone(cursor.getString(cursor.getColumnIndex(PHONE)));
                allRecords.add(main);
            } while (cursor.moveToNext());
        }
        return allRecords;
    }
}


MainVO.java
package com.example.sushil.myapplication;

public class MainVO {

    private String name;
    private int age;
    private String Phone;


    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhone() {
        return Phone;
    }

    public void setPhone(String phone) {
        Phone = phone;
    }
}


Screen Preview

Saving records to SQLite Android
Saving records to SQLite Android

Displaying records from SQLite
Displaying records via RecyclerView after reading from SQLite Android



SHARE

0 comments:

Post a Comment