In this Project we will use sqlite database to store contact and show all contacts in recyclerview
and if you click on contact you will move to new Activity that is Dispaly Contact.
Step1:- MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step2:-
displayContact.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".displayContact">
<TextView
android:id="@+id/displayName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="160dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/displayPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="356dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step3:- Item for recycler view
row.xml:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="85dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iconbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.461"
app:srcCompat="@android:drawable/sym_def_app_icon" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="@+id/phone_number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/iconbutton"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/phone_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/iconbutton" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Step4:-
MainActivity.java
package guru.happylife.dbdemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import guru.happylife.dbdemo.adapter.RecyclerViewAdapter;
import guru.happylife.dbdemo.data.MyDbHandler;
import guru.happylife.dbdemo.model.Contact;
public class MainActivity extends AppCompatActivity {
// ListView listView;
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerViewAdapter;
private ArrayList<Contact> contactArrayList;
private ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//recycler view initialization
recyclerView =findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyDbHandler db= new MyDbHandler(MainActivity.this);
// adding a contact
Contact amit=new Contact();
amit.setId(1);
amit.setPhoneNumber("9987548789");
amit.setName("amit");
db.addContact(amit);
Gson gson = new Gson();
String modelrespose=""+new Gson().toJson(amit).toString();
Log.d("chekamit","amit is" +modelrespose);
// for(int i=0;i<44;i++) {
// db.deleteContactById(i);
// }
db.deleteContactById(1);
// ArrayList<String> contacts1 =new ArrayList<>();
contactArrayList =new ArrayList<>();
// listView =findViewById(R.id.listView);
// Get all contacts
List<Contact> contactList = db.getAllContacts();
for(Contact contact: contactList) {
Log.d("dbtesting", "\nId: " + contact.getId() + "\n" +
"Name: " + contact.getName() + "\n" +
"Phone Number: " + contact.getPhoneNumber() + "\n");
//contacts1.add(contact.getName()+"("+contact.getPhoneNumber()+")");
contactArrayList.add(contact);
}
// ArrayAdapter<String> arrayAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,contacts1);
// listView.setAdapter(arrayAdapter);
//use your recyler view
recyclerViewAdapter = new RecyclerViewAdapter(this,contactArrayList);
recyclerView.setAdapter(recyclerViewAdapter);
Log.d("dbtest","you have "+db.getCount()+ "records in your database");
}
}
Step5:-
displayContact.java
package guru.happylife.dbdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import guru.happylife.dbdemo.R;
public class displayContact extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
Intent intent = getIntent();
String name = intent.getStringExtra("Rname");
String phone = intent.getStringExtra("Rphone");
TextView nameTextView = findViewById(R.id.displayName);
nameTextView.setText(name);
TextView phoneTextView = findViewById(R.id.displayPhone);
phoneTextView.setText(phone);
}
}
Step6:-
create params.java
package guru.happylife.dbdemo.params;
public class params {
public static final int DB_VERSION=1;
public static final String DB_NAME ="contacts_db";
public static final String TABLE_NAME="contacts_table";
public static final String KEY_ID="id";
public static final String KEY_NAME="name";
public static final String KEY_PHONE="phone_number";
}
Step7:-
Create model class for contacts
Contact.java
package guru.happylife.dbdemo.model;
public class Contact {
private int id;
private String name;
private String phoneNumber;
public Contact( String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
public Contact(int id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
public Contact() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Step8:-
MyDbHandler.java
package guru.happylife.dbdemo.data;
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 guru.happylife.dbdemo.model.Contact;
import guru.happylife.dbdemo.params.params;
import java.util.ArrayList;
import java.util.List;
public class MyDbHandler extends SQLiteOpenHelper {
public MyDbHandler(Context context) {
super(context, params.DB_NAME, null, params.DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String create = "CREATE TABLE " + params.TABLE_NAME + "("
+ params.KEY_ID + " INTEGER PRIMARY KEY," + params.KEY_NAME
+ " TEXT, " + params.KEY_PHONE + " TEXT" + ")";
Log.d("dbtestdata", "Query being run is : "+ create);
db.execSQL(create);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addContact(Contact contact){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(params.KEY_NAME, contact.getName());
values.put(params.KEY_PHONE, contact.getPhoneNumber());
db.insert(params.TABLE_NAME, null, values);
Log.d("dbtest", "Successfully inserted");
db.close();
}
public List<Contact> getAllContacts(){
List<Contact> contactList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
// Generate the query to read from the database
String select = "SELECT * FROM " + params.TABLE_NAME;
Cursor cursor = db.rawQuery(select, null);
//Loop through now
if(cursor.moveToFirst()){
do{
Contact contact = new Contact();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
}while(cursor.moveToNext());
}
return contactList;
}
public int updateContact(Contact contact){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(params.KEY_NAME, contact.getName());
values.put(params.KEY_PHONE, contact.getPhoneNumber());
//Lets update now
return db.update(params.TABLE_NAME, values, params.KEY_ID + "=?",
new String[]{String.valueOf(contact.getId())});
}
public void deleteContactById(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(params.TABLE_NAME, params.KEY_ID +"=?", new String[]{String.valueOf(id)});
db.close();
}
public void deleteContact(Contact contact){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(params.TABLE_NAME, params.KEY_ID +"=?", new String[]{String.valueOf(contact.getId())});
db.close();
}
public int getCount(){
String query = "SELECT * FROM " + params.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
return cursor.getCount();
}
}
Step9:-
RecyclerViewAdapter.java
package guru.happylife.dbdemo.adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import guru.happylife.dbdemo.R;
import guru.happylife.dbdemo.displayContact;
import guru.happylife.dbdemo.model.Contact;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.viewHolder> {
private Context context;
private List<Contact> contactList;
public RecyclerViewAdapter(Context context, List<Contact> contactList) {
this.context = context;
this.contactList = contactList;
}
@NonNull
@Override
public RecyclerViewAdapter.viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,parent,false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerViewAdapter.viewHolder holder, int position) {
Contact contact = contactList.get(position);
holder.contactName.setText(contact.getName());
holder.phoneNumber.setText(contact.getPhoneNumber());
}
@Override
public int getItemCount() {
return contactList.size();
}
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView contactName;
public TextView phoneNumber;
public ImageView iconButton;
public viewHolder(@NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
contactName= itemView.findViewById(R.id.name);
phoneNumber= itemView.findViewById(R.id.phone_number);
iconButton= itemView.findViewById(R.id.iconbutton);
iconButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Log.d("ClickFromViewHolder","clicked");
int position = this.getAdapterPosition();
Contact contact = contactList.get(position);
String name= contact.getName();
String phone = contact.getPhoneNumber();
Toast.makeText(context, "The position is"+String.valueOf(position)+"Name:"+name+"Phone"+phone, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, displayContact.class);
intent.putExtra("Rname", name);
intent.putExtra("Rphone", phone);
context.startActivity(intent);
// Intent intent = new Intent(context,displayContact.class);
// intent.putExtra("Rname",name);
// intent.putExtra("Rphone",phone);
// context.startActivity(intent);
}
}
}