Android Search RecyclerView

 

Android Search Recyclerview :

Android Search Recyclerview, Generally data is displayed in the form of listviews in apps, so that data can be dynamically loaded also sometimes the list has to be searched.

Android Recyclerview is mostly used now a days rather than the android listview so that the views get recycled and consumes less storage compared to the listview

Searching a android listview is most common feature used in almost every app so in this android tutorial on recyclerview search we will see how to search the list and show the updated list.

In my previous tutorial Fetching Contacts i had shown you how to fetch contacts and now in this tutorial i will show you how to add search functionality to that recyclerview.

We will be using Android Search Recyclerview just as like textview and edittext but this one comes up with a search functionality.

Based in this example i have also created a app may have a look in play store.

Android Search Recyclerview Video Tutorial :

Follow through this vlog for more in detail implementation of search functionality in android recyclerview.

 

Easily implement customized search functionality to your recycerview, for more follow this tutorial on Android Search Recyclerview.

Android Search Recyclerview

 

 

Initialization of search view, and adding a hint to be appeared in the searchview

 

SearchView search;

search = (SearchView) findViewById(R.id.searchView);
search.setQueryHint("Search by Name");
search.setBackgroundColor(Color.parseColor("#ffffff"));
search.setIconified(false);
search.clearFocus();

 

activity_main

Add a search view to the view above the recyclerview as

 <SearchView
 android:id="@+id/searchView"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="right"
 android:drawable="@drawable/search_store_icon"
 android:gravity="center"
 android:hint="Search by name"
 android:padding="2dp"
 android:singleLine="true"
 android:textColorHint="#000000"></SearchView>

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="location.android.com.searchrecyclerview.MainActivity">

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:drawable="@drawable/search_store_icon"
        android:gravity="center"
        android:hint="Search by name"
        android:padding="2dp"
        android:singleLine="true"
        android:textColorHint="#000000"></SearchView>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/contacts_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/frag"
        android:clickable="true" />


</LinearLayout>

 

MainActivity :

Complete implementation of this tutorial is provided below.Initially we are fetching contacts and then populating them once we finish fetching through a recylerview.

We have also added necessary permissions to fetch contacts that are required based on android versions.

You can also choose the required fields i.e., phone number, name, email-id, image if exist’s and so on depending upon requirement.

 

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Contacts> selectUsers;
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    RecyclerAdapter adapter;
    SearchView search;
    Cursor phones;
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    ImageView mSearchCloseButton;


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

        recyclerView = (RecyclerView) findViewById(R.id.contacts_list);
        recyclerView.setHasFixedSize(true);

        recyclerView.setLayoutManager(layoutManager);

        search = (SearchView) findViewById(R.id.searchView);
        search.setQueryHint("Search by Name");
        search.setBackgroundColor(Color.parseColor("#ffffff"));
        search.clearFocus();

        selectUsers = new ArrayList<Contacts>();
        showContacts();

        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO Auto-generated method stub

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // TODO Auto-generated method stub

                adapter.filter(newText);

                return false;
            }
        });


    }

    private void showContacts() {
        // Check the SDK version and whether the permission is already granted or not.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
            //After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
        } else {
            // Android version is lesser than 6.0 or the permission is already granted.
            phones = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
            LoadContact loadContact = new LoadContact();
            loadContact.execute();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission is granted
                phones = getApplicationContext().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
                LoadContact loadContact = new LoadContact();
                loadContact.execute();
            } else {
                Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
            }
        }
    }


    class LoadContact extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... voids) {
            // Get Contact list from Phone

            if (phones != null) {
                Log.e("count", "" + phones.getCount());
                if (phones.getCount() == 0) {

                }

                while (phones.moveToNext()) {
                    Bitmap bit_thumb = null;
                    String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


                    Contacts selectUser = new Contacts();
                    selectUser.setName(name);
                    selectUser.setPhone(phoneNumber);
                    selectUsers.add(selectUser);


                }
            } else {
                Log.e("Cursor close 1", "----------------");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // sortContacts();
            int count=selectUsers.size();
            ArrayList<Contacts> removed=new ArrayList<>();
            ArrayList<Contacts> contacts=new ArrayList<>();
            for(int i=0;i<selectUsers.size();i++){
                Contacts inviteFriendsProjo = selectUsers.get(i);

                if(inviteFriendsProjo.getName().matches("\\d+(?:\\.\\d+)?")||inviteFriendsProjo.getName().trim().length()==0){
                    removed.add(inviteFriendsProjo);
                    Log.d("Removed Contact",new Gson().toJson(inviteFriendsProjo));
                }else{
                    contacts.add(inviteFriendsProjo);
                }
            }
            contacts.addAll(removed);
            selectUsers=contacts;
            adapter = new RecyclerAdapter(inflater, selectUsers);
            recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            recyclerView.setAdapter(adapter);

        }
    }
}

 

If you have any queries regarding tutorial on Android Search Recyclerview please comment below.

Share and like this tutorial to make it reach more users.

Show Buttons
Hide Buttons
Read previous post:
Google Pay App

  Google Pay App : It's been a month Google Pay app launched and mostly every 7 out of 10...

Close