Dedicated Server

RecyclerView with sqlite database android tutorial

The following gif is an overview of what we are about to build
add, edit, delete, search contacts




First of all create a new project in android studio
now setup the following dependencies in your app level build.gradle file

implementation 'com.android.support:appcompat-v7:28.0.0' 
implementation 'com.android.support:design:28.0.0' 
implementation 'com.android.support:recyclerview-v7:28.0.0' 
implementation 'com.android.support:cardview-v7:28.0.0'

Now setup all the assets like shown below

go to res >> drawable and create brown_border.xml,pedit.png,pdelete.png

brown_border.xml

pedit.png(download)


pdelete.png(download)


Now go to res >> values >> colors.xml and add the following

Now go to res >> values >> strings.xml and add the following

Now create res >> menu >> menu_main.xml like this

Now create res >> layout and add the following

activity_main.xml add_contact_layout.xml contact_list_layout.xml
Now let us look into some java code
First of all create a helper class which extends SQLiteOpenHelper as shown below

SqliteDatabase.java
The above helper class provides methods to perform all the basic CRUD operations like add, update, delete etc.Now we should create a model class for the contacts object, it should be like

Contacts.java
Now we should create a recyclerview adapter for our recyclerview. It will include a Filter method which would be used to do search operations within our contacts list.

ContactAdapter.java

Below is the code for ContactViewHolder.java which is used in the above adapter class
Update your MainActivity.java file like shown below
With this, we have come to the end of this tutorial, now try running the app!

You may also check an advanced tutorial here >>
Android Recyclerview Tutorial with SQLite ROOM : using MVVM, Dagger 2

24 comments:

  1. Caused by: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class android.support.v7.widget.RecyclerView
    Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class android.support.v7.widget.RecyclerView
    Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.widget.RecyclerView" on path: DexPathList[[zip file "/data/app/com.chutiya.example-WyUxuvgeWlh6jQlcHfOkTQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.chutiya.example-WyUxuvgeWlh6jQlcHfOkTQ==/lib/arm64, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.view.LayoutInflater.createView(LayoutInflater.java:606)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:827)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:750)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:900)
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:861)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
    at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
    at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
    at com.chutiya.example.MainActivity.onCreate(MainActivity.java:36)

    ReplyDelete
    Replies
    1. if you are using androidx packages in your project, consider replacing "android.support.v7.widget.RecyclerView" with "androidx.recyclerview.widget.RecyclerView" in your llayout xml file

      Delete
  2. If we want to show the ID in the contact list, how to do?

    ReplyDelete
  3. If we want to show the ID in the contact list, how to do?

    ReplyDelete
    Replies
    1. first of all create a textview in contact_list_layout and then inside your ContactAdapter's OnBindViewholder, add holder.id_textview.setText(contacts.getId())

      Delete
  4. Thank you? It means nothing in exchange for your work...

    frankly you are great !!!

    ReplyDelete
  5. it gave me an error : java.lang.NumberFormatException: s == null

    on lines
    //=========================================0 SQLdatabase
    if(cursor.moveToFirst()) {
    do {
    int id = Integer.parseInt(cursor.getString(0));
    //=========================================0

    //=========================================1 Main_Activity
    if(allContacts.size() > 0) {
    contactsView.setVisibility(View.VISIBLE);
    mAdapter = new HexTextAdapt(this, allContacts);
    contactsView.setAdapter(mAdapter);
    //=========================================1

    ReplyDelete
    Replies
    1. cursor.getString(0) should not contain a letter,special characters etc. it should contain only numeric characters. If you try to convert non numeric characters to int, this exception will be thrown

      Delete
  6. W/IInputConnectionWrapper: getExtractedText on inactive InputConnection
    W/IInputConnectionWrapper: beginBatchEdit on inactive InputConnection
    endBatchEdit on inactive InputConnection


    please reply

    ReplyDelete
    Replies
    1. this is just a warning, not an error, can you please specify the issue that you are facing?

      Delete
  7. it work but maybe the flow is not smooth.

    ReplyDelete
    Replies
    1. Please check my recent recyclerview tutorial with sqlite room,mvvm and dagger2, it is having proper transitions

      Delete
  8. refreshing page after delete or update doesn't work

    ReplyDelete
    Replies
    1. Ensure the Arraylists in adapter is updated with the recent updates from your db. Then call notifyDataSetChanged().

      It worked for me in many cases

      Delete
  9. Amazing!. You're great really!. Thank you for this awesome tutorial. Everything is working fine even though I changed the code a bit to suit my need. Thanks!

    ReplyDelete
  10. Process: com.example.recycl_sqlite, PID: 15666
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
    at com.example.recycl_sqlite.MainActivity.search(MainActivity.java:129)
    at com.example.recycl_sqlite.MainActivity.onCreateOptionsMenu(MainActivity.java:122)
    at android.app.Activity.onCreatePanelMenu(Activity.java:4119)

    ReplyDelete
  11. t gave me an error

    > Task :app:compileDebugJavaWithJavac
    Note: //.....\DataAdapter.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.

    public class DataAdapter extends RecyclerView.Adapter implements Filterable{

    private Context context;
    private ArrayList listData;
    private ArrayList mArrayList;

    private SqliteDatabase mDatabase;

    public DataAdapter(Context context, ArrayList listData) {
    this.context = context;
    this.listData = listData;
    this.mArrayList = listData;
    mDatabase = new SqliteDatabase(context);
    }

    @Override
    public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_data_list_layout, parent, false);
    return new DataViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DataViewHolder holder, int position) {
    final Data data = listData.get(position);

    holder.title.setText(data.getTitle());
    holder.user.setText(data.getUser());
    holder.pass.setText(data.getPass());

    holder.editData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    editTaskDialog(data);
    }
    });

    holder.deleteData.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    //delete row from database

    deleteTaskDialog(data);
    }
    });
    }
    @Override
    public Filter getFilter() {

    return new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {

    String charString = charSequence.toString();

    if (charString.isEmpty()) {

    listData = mArrayList;
    } else {

    ArrayList filteredList = new ArrayList<>();

    for (Data data : mArrayList) {

    if (data.getTitle().toLowerCase().contains(charString)) {

    filteredList.add(data);
    }
    }

    listData = filteredList;
    }

    FilterResults filterResults = new FilterResults();
    filterResults.values = listData;
    return filterResults;
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
    listData = (ArrayList) filterResults.values;
    notifyDataSetChanged();
    }
    };
    }

    ReplyDelete
  12. 2021-05-18 13:49:31.811 24831-24913/? E/AwarenessRouterSyncMgr: Exception while syncing fences
    java.util.concurrent.ExecutionException: java.lang.IllegalStateException: Account associated with identity was null
    at zuv.a(PG:131)
    at zuv.get(PG:78)
    at zyq.a(PG:1)
    at zxc.a(PG:4)
    at fyf.run(Unknown Source:6)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at psm.run(PG:12)
    at java.lang.Thread.run(Thread.java:923)
    Caused by: java.lang.IllegalStateException: Account associated with identity was null
    at fxj.a(Unknown Source:19)
    at zux.a(Unknown Source:2)
    at zuz.run(PG:22)
    at zxu.run(PG:1)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
    at psm.run(PG:12) 
    at java.lang.Thread.run(Thread.java:923) 
    2021-05-18 13:49:32.140 24831-24911/? E/GoogleTagManager: Invalid macro: _gtm.loadEventEnabled
    2021-05-18 13:49:32.201 24831-24952/? E/GoogleTagManager: Invalid macro: _gtm.loadEventEnabled

    ReplyDelete