How to add Search Filter to Recyclerview – Android Recyclerview Filterable
search_menu.xml
Then, Add the following code to the menu.
Here, In the above code, the menu is given an id, an Icon (a search icon, you need to create a vector search image in your drawable folder),
And to make it expandable I am using shows action with collapseActionView attribute, By doing this we can the menu as an icon in our android app bar when this icon is been pressed/clicked it will expand, and hence the user can input text in Android SearchView.
MainActivity.java:
package nanoakhi.rcfinternal.library.library_books_name;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.MenuItemCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sdsmdg.tastytoast.TastyToast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nanoakhi.rcfinternal.R;
import nanoakhi.rcfinternal.departmentnumbers.ConnectionDetector;
import nanoakhi.rcfinternal.library.library_books_name.RecyclerViewAdapter;
import nanoakhi.rcfinternal.incentive_pf.GetDataAdapter;
import static nanoakhi.rcfinternal.complaint.Config.libraryData;
import static nanoakhi.rcfinternal.complaint.Config.regulardoct;
public class library_books_name extends AppCompatActivity {
Bundle bundle;
Intent intent;
private JSONArray result;
//JSON array name
public static final String JSON_ARRAY = "result";
private StaggeredGridLayoutManager gaggeredGridLayoutManager;
RecyclerView.Adapter recyclerViewadaAdapter;
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
String BOOK_NAME,SUBJECT, AUTHOR_NAME,LIBRARY_NAME;
TextView f, s, t, headText;
// Connection detector
ConnectionDetector cd;
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_recyleview_toolbar);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("आरसीएफ");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
bundle = getIntent().getExtras();
assert bundle != null;
if (bundle.getString("BOOK_NAME") != null) {
BOOK_NAME = bundle.getString("BOOK_NAME");
AUTHOR_NAME = bundle.getString("AUTHOR_NAME");
SUBJECT = bundle.getString("SUBJECT");
LIBRARY_NAME = bundle.getString("LIBRARY_NAME");
Log.d("libpARAM:", "onCreate: "+BOOK_NAME+AUTHOR_NAME+SUBJECT+LIBRARY_NAME);
}
LinearLayout head = (LinearLayout) findViewById(R.id.head);
// head.setVisibility(View.GONE);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
TastyToast.makeText(getApplicationContext(), "Not Connected", TastyToast.LENGTH_LONG, TastyToast.WARNING);
// stop executing code by return
return;
}
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
//SLIDING IMAGE END
gaggeredGridLayoutManager = new StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gaggeredGridLayoutManager);
JSON_DATA_WEB_CALL(BOOK_NAME,SUBJECT, AUTHOR_NAME,LIBRARY_NAME);
}
public void JSON_DATA_WEB_CALL(String BOOK_NAME, String SUBJECT, String AUTHOR_NAME, String LIBRARY_NAME) {
final ProgressDialog loading = ProgressDialog.show(library_books_name.this, "Listing books", "Please wait...", false, true);
// Toast.makeText(this, EMP_NO, Toast.LENGTH_SHORT).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, libraryData,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Toast.makeText(hospital.this, response, Toast.LENGTH_SHORT).show();
Log.d("LIBRARYDATEA:", "onResponse: " + response);
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(JSON_ARRAY);
if (result.length() > 0) {
loading.dismiss();
JSON_PARSE_DATA_AFTER_WEBCALL(result);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(library_books_name.this);
// Setting Dialog Title
alertDialog.setTitle("No record Found");
// Setting Dialog Message
alertDialog.setMessage("Try Again!!");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_action_inbox);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Got!!!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
library_books_name.this.finish();
}
});
// Showing Alert Message
alertDialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
// stopping swipe refresh
// Toast.makeText(vendor_name.this, "Error", Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() {
//PASSING STRING VALUE TO THE TAGGING PARAMETER WITH TENDS TO GO FOR TBALE NAME
Map<String, String> params = new HashMap<String, String>();
Log.d("libpARAM1:", "onCreate: "+BOOK_NAME+" ,"+AUTHOR_NAME+" ,"+SUBJECT+" ,"+LIBRARY_NAME);
params.put("P_book_name", BOOK_NAME);
params.put("P_SUBJECT", SUBJECT);
params.put("P_author", AUTHOR_NAME);
params.put("p_library", LIBRARY_NAME);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(library_books_name.this);
requestQueue.add(stringRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
//LIBRARY,BOOK_ID,TITLE,AUTHOR,SUB_CODE,STATUS
GetDataAdapter2.setLIBRARY(json.getString("LIBRARY"));
GetDataAdapter2.setBOOK_ID(json.getString("BOOK_ID"));
GetDataAdapter2.setTITLE(json.getString("TITLE"));
GetDataAdapter2.setAUTHOR(json.getString("AUTHOR"));
GetDataAdapter2.setSUB_CODE(json.getString("SUB_CODE"));
GetDataAdapter2.setSTATUS(json.getString("STATUS"));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadaAdapter = new RecyclerViewAdapter(GetDataAdapter1, library_books_name.this);
recyclerView.setAdapter(recyclerViewadaAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_scrolling, menu);
MenuItem search = menu.findItem(R.id.action_settings);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
CharSequence query;
query = newText.toString().toLowerCase();
final List<GetDataAdapter> filteredList = new ArrayList<>();
for (int i = 0; i < GetDataAdapter1.size(); i++) {
final String text = GetDataAdapter1.get(i).getTITLE().toLowerCase();
if (text.contains(query)) {
filteredList.add(GetDataAdapter1.get(i));
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(library_books_name.this));
recyclerViewadaAdapter = new RecyclerViewAdapter(filteredList, library_books_name.this);
recyclerView.setAdapter(recyclerViewadaAdapter);
recyclerViewadaAdapter.notifyDataSetChanged(); // data set changed
return false;
}
});
}
}
Recyclerview Adapter
Then, we need a RecyclerView Adapter that will help us in creating views and show a list of data in recycleview.
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import nanoakhi.rcfinternal.R;
import nanoakhi.rcfinternal.incentive_pf.GetDataAdapter;
import static android.graphics.Color.RED;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private final static int FADE_DURATION = 1000; //FADE_DURATION in milliseconds
int SCODE;
Context context;
public List<GetDataAdapter> getDataAdapter;
private static int currentPosition = 0;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.library_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final int pos = position;
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
holder.title.setText(getDataAdapter1.getTITLE() +" ("+ getDataAdapter1.getBOOK_ID()+" )");
holder.LIBRARY.setText(getDataAdapter1.getLIBRARY());
holder.AUTHOR.setText(getDataAdapter1.getAUTHOR());
holder.STATUS.setText(getDataAdapter1.getSTATUS());
if (position % 2 == 0) {
holder.itemView.setBackgroundColor(0x80E0EEEE);
} else {
holder.itemView.setBackgroundColor(0XFFFFFF);
}
}
@Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView STATUS, title, LIBRARY, AUTHOR,
textViewCreatedBy, textViewPublisher, textViewBio, ADD, discount, FinalPrice, ActualSave;
public ImageView imageView;
LinearLayout linearLayout;
public CheckBox chkSelected;
ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
LIBRARY = (TextView) itemView.findViewById(R.id.LIBRARY);
AUTHOR = (TextView) itemView.findViewById(R.id.AUTHOR);
STATUS= (TextView) itemView.findViewById(R.id.STATUS);
}
}
}
MainActivity.java Final Wordings
Then, In our MainActivity, we are creating a List of Data and passing the data to RecyclerView Adaptor to display them,
To show a Search View Menu in our App Toolbar we are using @Override onCreateOptionsMenu where we will use MenuInflater to show Search Menu,
Then connect our SearchView with our Menu Search,using setOnQueryTextListener we are detecting onQueryTextChange where user enter Search Filter String we will pass to the string to our adapter method (adapter.getFilter().filter(newText))
Post a Comment
0Comments