Sqlite Database with all CRUD functions

Sqlite database in android, crud operations in android using sqlite, sqlite demo in android
In this demo used  all basic and often used controls like :
- EditText with floating hint
- Radio buttons with RadioGroup
- Checkbox
- Spinner
- Cardview
- Recycleview

:: CREATE INSERT OPERATION :: 

STEP : 1
Create DatabaseHandler.java  class in which  we will create database related stuffs.

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    public static final String TABLE_CONTACTS = "contacts";

    private static DatabaseHandler mInstance;
    private static SQLiteDatabase sqLiteDatabase;

    // Contacts Table Columns names
    public static final String KEY_ID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_GENDER = "gender";
    public static final String KEY_INTEREST = "interest";
    public static final String KEY_COURSE = "course";

    public static DatabaseHandler getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new DatabaseHandler(context);
        }
        return mInstance;
    }

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " VARCHAR(50),"
                + KEY_EMAIL + " VARCHAR(30), "
                + KEY_GENDER + " VARCHAR(6), "
                + KEY_INTEREST + " VARCHAR(30), "
                + KEY_COURSE + " VARCHAR(50) "
                + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
        // Create tables again
        onCreate(db);
    }

    //Insert into tables
    public long insertQuery(ContentValues values, String TABLE) {

        long returnVal = 0;

        try {
            sqLiteDatabase = getDatabaseMode("write");
            // Inserting Row
            returnVal = sqLiteDatabase.insert(TABLE, null, values);
        } catch (Exception e) {
            returnVal = 0;
            e.printStackTrace();
        }
        return returnVal;
    }

    //Update into tables
    public int updateQuery(String TABLE, ContentValues values, String whereClause, 
                                                                 String[] whereArgs) {

        int returnVal = 0;

        try {
            sqLiteDatabase = getDatabaseMode("write");
            // Inserting Row
            returnVal = sqLiteDatabase.update(TABLE, values, whereClause, whereArgs);

        } catch (Exception e) {
            returnVal = 0;
            e.printStackTrace();
        }
        return returnVal;
    }

    //Get data by specific records using where clause in query
    public Cursor getDataByCustomQuery(String QUERY, String[] args) {

        Cursor cursor = null;
        try {

            sqLiteDatabase = getDatabaseMode("read");
            cursor = sqLiteDatabase.rawQuery(QUERY, args);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return cursor;
    }

    //Delete all data of table
    public void truncateTable(String TABLE) {
        try {
            sqLiteDatabase = getDatabaseMode("write");
            sqLiteDatabase.execSQL("DELETE FROM " + TABLE); //delete all rows in a table
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Delete record
    public int deleteRecord(String table, String whereClause, String[] whereArgs) {

        int returnVal = 0;
        try {
            sqLiteDatabase = getDatabaseMode("write");
            returnVal = sqLiteDatabase.delete(table, whereClause, whereArgs);
        } catch (Exception e) {
            e.printStackTrace();
            returnVal = 0;
        }

        return returnVal;
    }

    /**
     * Returns a writable database instance in order not to open and close many
     * SQLiteDatabase objects simultaneously
     *
     * @return a writable instance to SQLiteDatabase
     */
    public SQLiteDatabase getDatabaseMode(String mode) {
        if ((sqLiteDatabase == null) || (!sqLiteDatabase.isOpen())) {
            if (mode.equalsIgnoreCase("read"))
                sqLiteDatabase = this.getReadableDatabase();
            else
                sqLiteDatabase = this.getWritableDatabase();
        }

        return sqLiteDatabase;
    }

    @Override
    public void close() {
        super.close();
        if (sqLiteDatabase != null) {
            sqLiteDatabase.close();
            sqLiteDatabase = null;
        }
    }
}

STEP : 2
Create activity_main.xml for MainActivity UI


<?xml version="1.0" encoding="utf-8"?>
<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"
    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.climbachiya.databasedemo.MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Demo"
        android:gravity="center_horizontal" />

    <android.support.design.widget.TextInputLayout
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_marginBottom="5dp">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edit_name"
            android:hint="Name"/>
    </android.support.design.widget.TextInputLayout>
    <android.support.design.widget.TextInputLayout
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_marginBottom="5dp">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/edit_email"
            android:hint="Email"/>
    </android.support.design.widget.TextInputLayout>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/email"
        android:orientation="horizontal"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:id="@+id/radio_group"
        android:layout_marginBottom="5dp">
        <TextView
            android:id="@+id/title_gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Are you : "
            android:textSize="18sp" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male"
            android:id="@+id/radio_male"
            android:layout_below="@+id/email"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:checked="false"
            android:padding="5dp" />
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:id="@+id/radio_female"
            android:layout_below="@+id/email"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:checked="false"
            android:padding="5dp" />
    </RadioGroup>

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:prompt="@string/spinner_title"
        android:layout_below="@+id/radio_group"
        style="@style/Base.Widget.AppCompat.Spinner.Underlined"/>


    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinner"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:id="@+id/linearLayout"
        android:layout_marginBottom="5dp">
        <TextView
            android:id="@+id/title_course"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Course : "
            android:textSize="18sp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Android"
            android:id="@+id/check_android"
            android:padding="5dp" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="iPhone"
            android:id="@+id/check_iphone"
            android:padding="5dp" />
    </LinearLayout>

    <Button
        style="?android:attr/buttonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:id="@+id/button"
        android:onClick="saveData"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="68dp"
        android:layout_marginStart="68dp"
        android:layout_marginBottom="58dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="View"
        android:onClick="viewAllRecords"
        android:id="@+id/button2"
        android:layout_alignTop="@+id/button"
        android:layout_toRightOf="@+id/button"
        android:layout_toEndOf="@+id/button"
        android:layout_marginLeft="47dp"
        android:layout_marginStart="47dp" />
</RelativeLayout>



STEP : 3


Create MainActivity.java activity class for insert data


public class MainActivity extends AppCompatActivity {

    EditText edtName, edtEmail;
    Spinner mSpinner;
    RadioGroup rdbGroup;
    RadioButton rdbMale,rdbFemale;
    CheckBox chkAndroid, chkIphone;
    ArrayAdapter<String> dataAdapter;
    String gender = null;
    //class members
    String businessType[] = {"Automobile", "Food", "Computers", "Education",
            "Personal", "Travel"};

    DatabaseHandler dbHandler = null;
    ProgressDialog progress = null;
    String spinnerItem = null;
    ArrayList<String> arrInterest;
    boolean isEditMode = false;
    String rowId = null;

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

        initUIControls();

        initClassObjects();

        registerEvents();

        receiveIntentData();

    }

    private void receiveIntentData() {

        if(null != getIntent().getStringExtra("ROW_ID")){ //User is in Edit mode
            rowId = getIntent().getStringExtra("ROW_ID");

            if(null != rowId){
                Log.v("receiveIntentData :: ","_id : "+rowId);
                isEditMode = true;
                getSetDataFromDB(rowId);
            }
        }
    }

    /**
     * get set data based on id from DB
     * @param id - row id
     */
    private void getSetDataFromDB(String id) {
        dbHandler = DatabaseHandler.getInstance(this);
        try {
            String SQL = "SELECT * FROM "+DatabaseHandler.TABLE_CONTACTS+" WHERE "+
                                                       DatabaseHandler.KEY_ID+" = ?";
            Cursor cursor = dbHandler.getDataByCustomQuery(SQL, new String[]{id});
            if(cursor != null && cursor.getCount() > 0){

                cursor.moveToFirst();

                String _name = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_NAME));
                String _email = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_EMAIL));
                String _gender = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_GENDER));
                String _interest = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_INTEREST));
                String _course = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_COURSE));
                Log.v("_course",_course);
                Log.v("_interest",_interest);
                if(_name != null){
                    edtName.setText(_name);
                }
                if(_email != null){
                    edtEmail.setText(_email);
                }
                if(_gender != null){
                    if(_gender.equalsIgnoreCase("male")){
                        gender = "male";
                        rdbMale.setChecked(true);
                    }else if(_gender.equalsIgnoreCase("female")){
                        gender = "female";
                        rdbFemale.setChecked(true);
                    }
                }

                if(_interest != null){
                    if(_interest.contains(",")){
                        String[] choice = _interest.split(",");
                        if(choice[0].equalsIgnoreCase("Android") || 
                                              choice[1].equalsIgnoreCase("Android")){
                            chkAndroid.setChecked(true);
                        }
                        if(choice[0].equalsIgnoreCase("iPhone") || 
                                               choice[1].equalsIgnoreCase("iPhone")){
                            chkIphone.setChecked(true);
                        }

                    }else{
                        if(_interest.equalsIgnoreCase("Android")){
                            chkAndroid.setChecked(true);
                        }else if(_interest.equalsIgnoreCase("iPhone")){
                            chkIphone.setChecked(true);
                        }
                    }
                }

                if(null != _course){
                    //if(mSpinner.getCount()_course)
                    int index = Arrays.asList(businessType).indexOf(_course);
                    Log.v("index : ",""+index);
                    mSpinner.setSelection(index, true);
                    spinnerItem = _course;
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void registerEvents() {
        rdbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // find which radio button is selected
                if (checkedId == R.id.radio_male) {
                    gender = "male";
                } else if (checkedId == R.id.radio_female) {
                    gender = "female";
                }
            }

        });

        chkAndroid.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    arrInterest.add("android");
                }else{
                    if(arrInterest.contains("android")){
                        arrInterest.remove("android");
                    }
                }

            }
        });
        chkIphone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (isChecked){
                        arrInterest.add("iphone");
                    }else{
                        if(arrInterest.contains("iphone")){
                            arrInterest.remove("iphone");
                        }
                    }

            }
        });

        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, 
                                                                            long id) {
                spinnerItem = mSpinner.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    //Init custom class objects
    private void initClassObjects() {
        progress = new ProgressDialog(this);
        progress.setMessage("Saving...");
        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progress.setIndeterminate(true);


        arrInterest = new ArrayList<>();

        dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, businessType);

        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        mSpinner.setAdapter(dataAdapter);
    }

    //Init all UI controls here
    private void initUIControls() {
        edtName = (EditText) findViewById(R.id.edit_name);
        edtEmail = (EditText) findViewById(R.id.edit_email);
        mSpinner = (Spinner) findViewById(R.id.spinner);
        rdbGroup = (RadioGroup) findViewById(R.id.radio_group);
        rdbMale = (RadioButton) findViewById(R.id.radio_male);
        rdbFemale = (RadioButton) findViewById(R.id.radio_female);
        chkAndroid = (CheckBox) findViewById(R.id.check_android);
        chkIphone = (CheckBox) findViewById(R.id.check_iphone);

    }

    //View all records from DB
    public void viewAllRecords(View view) {
        startActivity(new Intent(this, ViewData.class));
    }

    //Save record in DB
    public void saveData(View view) {

        String name = edtName.getText().toString();
        String email = edtEmail.getText().toString();


        if (null == name || name.isEmpty()) {
            Toast.makeText(MainActivity.this, "Name should not be empty", 
                                                     Toast.LENGTH_SHORT).show();
        } else if (null == email || email.isEmpty()) {
            Toast.makeText(MainActivity.this, "Email should not be empty", 
                                                     Toast.LENGTH_SHORT).show();
        } else if (!isEmailValid(email)) {
            Toast.makeText(MainActivity.this, "Enter valid email", 
                                                     Toast.LENGTH_SHORT).show();
        } else if (null == gender || gender.isEmpty()) {
            Toast.makeText(MainActivity.this, "Select gender", 
                                                     Toast.LENGTH_SHORT).show();
        }else if (null == spinnerItem || spinnerItem.isEmpty()) {
            Toast.makeText(MainActivity.this, "Select course", 
                                                     Toast.LENGTH_SHORT).show();
        }else if (null == arrInterest || arrInterest.size() <= 0) {
            Toast.makeText(MainActivity.this, "Select interest", 
                                                      Toast.LENGTH_SHORT).show();
        } else {
              //call async for save data in background
            new SaveAsync(name, email, spinnerItem, gender, arrInterest).execute();
        }
    }

    /**
     * Check for valid email
     *
     * @param email - email address
     * @return true/false
     */
    public boolean isEmailValid(String email) {
        final String EMAIL_PATTERN =
   "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        final Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    //Save data asychronously in DB
    class SaveAsync extends AsyncTask<String, String, String> {

        long result = 0;

        String name;
        String email;
        String spinnerItem;
        String gender;
        ArrayList<String> arrInterest;

        public SaveAsync(String name, String email, String spinnerItem, String gender, 
                                                       ArrayList<String> arrInterest) {
            this.name = name;
            this.email = email;
            this.spinnerItem = spinnerItem;
            this.gender = gender;
            this.arrInterest = arrInterest;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progress.show();
        }

        @Override
        protected String doInBackground(String... params) {

            ContentValues cv = null;
            try {
                cv = new ContentValues();
                dbHandler = DatabaseHandler.getInstance(MainActivity.this);

                String interestString = "";

                for(int i=0; i<arrInterest.size(); i++){
                    interestString = interestString +","+arrInterest.get(i);
                }

                interestString = 
            interestString.startsWith(",") ? interestString.substring(1) : interestString;


                cv.put(DatabaseHandler.KEY_NAME, name);
                cv.put(DatabaseHandler.KEY_EMAIL, email);
                cv.put(DatabaseHandler.KEY_GENDER, gender);
                cv.put(DatabaseHandler.KEY_INTEREST, interestString);
                cv.put(DatabaseHandler.KEY_COURSE, spinnerItem);

                if(!isEditMode){ //Add Mode
                    result = dbHandler.insertQuery(cv, DatabaseHandler.TABLE_CONTACTS);
                }else{ //Edit Mode

                    String whereClause = DatabaseHandler.KEY_ID + " = ? ";
                    String[] whereArgs = new String[]{rowId};
                    result = dbHandler.updateQuery(DatabaseHandler.TABLE_CONTACTS, cv, 
                                                                whereClause, whereArgs);
                }

            } catch (Exception e) {
                result = 0;
                e.printStackTrace();
            } finally {
                if (null != dbHandler) {
                    dbHandler.close();
                }
                if (null != cv) {
                    cv.clear();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if(null != progress && progress.isShowing())progress.dismiss();

            if (result > 0) {
                refreshView();
                if(isEditMode){
                    startActivity(new Intent(MainActivity.this, ViewData.class));
                    finish();
                }
                Toast.makeText(MainActivity.this, "Saved...", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Oops!Something wrong while saving", 
                                                            Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void refreshView() {
        edtName.setText("");
        edtEmail.setText("");
        rdbMale.setChecked(false);
        rdbFemale.setChecked(false);
        chkAndroid.setChecked(false);
        chkIphone.setChecked(false);
        mSpinner.setSelection(0, true);
        edtName.setFocusable(true);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}

:: CREATE LISTING & UPDATE, DELETE OPERATION ::

STEP : 4

Create ViewData.java activity for listing data from database


public class ViewData extends AppCompatActivity {

    List<Modal> modalList;
    RecyclerView mRecyclerView;
    ProgressBar progressBar;
    DatabaseHandler dbHandler = null;

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

        initUIControls();
        new GetDataAsync().execute();
    }

    private void initUIControls() {
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    }

    class GetDataAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {

            viewAllRecords();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressBar.setVisibility(View.INVISIBLE);
            if (null != modalList && modalList.size() > 0) {
                mRecyclerView.setHasFixedSize(true);
                mRecyclerView.setAdapter(new MyRecyclerAdapter(ViewData.this, modalList));
                mRecyclerView.setLayoutManager(new LinearLayoutManager(ViewData.this));
                mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            } else {
                Toast.makeText(ViewData.this, "No records found!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //View all records from DB
    public void viewAllRecords() {
        try {
            modalList = new ArrayList<>();

            modalList.clear();
            dbHandler = DatabaseHandler.getInstance(this);
            String sql = "SELECT * FROM " + DatabaseHandler.TABLE_CONTACTS;
            Cursor cursor = dbHandler.getDataByCustomQuery(sql, null);
            if (null != cursor && cursor.getCount() > 0) {
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    String rowId = cursor.getString
                                       (cursor.getColumnIndex(DatabaseHandler.KEY_ID));
                    String name = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_NAME));
                    String email = cursor.getString
                                     (cursor.getColumnIndex(DatabaseHandler.KEY_EMAIL));
                    String gender = cursor.getString
                                    (cursor.getColumnIndex(DatabaseHandler.KEY_GENDER));
                    String interest = cursor.getString
                                   (cursor.getColumnIndex(DatabaseHandler.KEY_INTEREST));
                    String course = cursor.getString
                                    (cursor.getColumnIndex(DatabaseHandler.KEY_COURSE));

                    modalList.add(new Modal(rowId, name, email, gender, interest, course));
                    cursor.moveToNext();
                }
            }
        } catch (Exception e) {

        }
    }
}


STEP : 5


Create view_all_records.xml for UI of ViewData class for listing data 


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

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

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="invisible" />
</RelativeLayout>



STEP : 6

Create Modal.java as pojo class for storing getter-setter for listing


public class Modal {

    String id;
    String name;
    String email;
    String gender;
    String interest;
    String course;

    public Modal(String id, String name, String email, String gender, String interest, 
                                                                         String course){
        this.id = id;
        this.name = name;
        this.email = email;
        this.gender = gender;
        this.interest = interest;
        this.course = course;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getInterest() {
        return interest;
    }

    public void setInterest(String interest) {
        this.interest = interest;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }
}



STEP : 7
Create MyRecyclerAdapter.java for recycleview listing 


public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {

    private List<Modal> items;
    Context mContext;

    public MyRecyclerAdapter(Context context, List<Modal> items) {
        this.items = items;
        this.mContext = context;
    }

    @Override
    public MyRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_cell, 
                                                                    parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyRecyclerAdapter.ViewHolder holder, final int position) {
        Modal item = items.get(position);
        holder.textName.setText(item.getName());
        holder.textEmail.setText(item.getEmail());

        holder.imgBtnEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editRow(position);
            }
        });
        holder.imgBtnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
                // Setting Dialog Title
                alertDialog.setTitle("Confirm Delete...");
                // Setting Dialog Message
                alertDialog.setMessage("Are you sure you want delete this?");
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.ic_remove);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int which) {
                        //Delete item
                        removeItem(position);
                    }
                });
                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener()
 {
                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to invoke NO event
                        dialog.cancel();
                    }
                });

                // Showing Alert Message
                alertDialog.show();

            }
        });

    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView textName;
        public TextView textEmail;
        public ImageButton imgBtnDelete;
        public ImageButton imgBtnEdit;

        public ViewHolder(View itemView) {
            super(itemView);
            textName = (TextView) itemView.findViewById(R.id.text_name);
            textEmail = (TextView) itemView.findViewById(R.id.text_email);
            imgBtnDelete = (ImageButton) itemView.findViewById(R.id.image_btn_delete);
            imgBtnEdit = (ImageButton) itemView.findViewById(R.id.image_btn_edit);
        }
    }

    /**
     * Edit record in database
     * @param position - row position in array list
     */
    private void editRow(int position) {
        String rowId = items.get(position).getId();
        Intent intentEdit = new Intent(mContext, MainActivity.class);
        intentEdit.putExtra("ROW_ID", rowId);
        mContext.startActivity(intentEdit);
        ((Activity)mContext).finish();
    }

    //Remove item
    public void removeItem(int position) {
        DatabaseHandler dbHandler = DatabaseHandler.getInstance(mContext);
        try {
            String rowId = items.get(position).getId();

            String whereClause = DatabaseHandler.KEY_ID+" = ?";
            String[] whereArgs = new String[]{rowId};
            int result = dbHandler.deleteRecord(DatabaseHandler.TABLE_CONTACTS, 
                                                           whereClause, whereArgs);

            if(result > 0){
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, items.size());
                items.remove(position);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null != dbHandler){
                dbHandler.close();
            }
        }

    }
}


STEP : 8

Create single_cell.xml for RecyclerAdapter listing cell


<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="5dp">

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

        <TextView
            android:id="@+id/text_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_name"
            android:drawablePadding="5dp"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:padding="8dp"
            android:singleLine="true"
            android:text="Name" />

        <TextView
            android:id="@+id/text_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/ic_email"
            android:drawablePadding="5dp"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:padding="8dp"
            android:singleLine="true"
            android:text="Email" />

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

            <ImageButton
                android:id="@+id/image_btn_delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:background="@null"
                android:padding="3dp"
                android:src="@drawable/ic_delete" />

            <ImageButton
                android:id="@+id/image_btn_edit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_marginLeft="10dp"
                android:background="@null"
                android:padding="3dp"
                android:src="@drawable/ic_mode_edit" />
        </LinearLayout>

    </LinearLayout>
</android.support.v7.widget.CardView>


:: Final Output ::




Check out the full demo here : https://github.com/CDL24/DatabaseDemo

Just download and import full android studio project.

And if you like my efforts please share the blog and hits like Happy Coding ;)

Comments