Android ActionBar SearchView Autocomplete for JSON listview - android

So,i am trying to make a searchview on my actionBar so when i type,autocompltes or shows the Json listview in a list format in that searchview ,and so that i can click on those i just searched. But i find it hard to implement.Everything else is working fine.I can display the list of json parsed elemnts and geet serializable content.Now i just need the searchbar to function
Here is my java class for the ListAdapter and JSON parsing.
public class Collegelist extends ActionBarActivity {
HTTPConnection http;
List<Colleges> college = new ArrayList<Colleges>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.college_list);
http = new HTTPConnection(getApplicationContext());
if (http.isNetworkConnection()) {
//String data = http.HTTPGetData("http://localhost/minorproject/show.php");
//Toast.makeText(getApplicationContext(),data ,Toast.LENGTH_LONG).show();
task.execute();
}
else {
Toast.makeText(getApplicationContext(), "check your connection",
Toast.LENGTH_LONG).show();
}
}
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String data = http.HTTPGetData("http://my-ip-address/minorproject/show.php");
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
populateList(result);
displayList();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
};
protected void populateList(String result) {
try {
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
JSONObject jobj = new JSONObject(result);
String res = jobj.getString("success");
if (!res.equals("true")) {
Toast.makeText(getApplicationContext(), "JSON Error",
Toast.LENGTH_LONG).show();
return;
}
else
{
JSONArray data = jobj.getJSONArray("msg");
// Toast.makeText(getApplicationContext(),"successss",Toast.LENGTH_SHORT).show();
for (int i = 0; i < data.length(); i++) {
JSONObject col = data.getJSONObject(i);
Colleges cg = new Colleges(col.getString("cname"),
col.getString("caddress"),
col.getString("ccontact_a"),
col.getString("ccontact_b"),
col.getString("cwebsites"));
college.add(cg);
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
protected void displayList() {
ArrayAdapter<Colleges> adapter = new ArrayAdapter<Colleges>(this, R.layout.list_item,college){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.list_item,null);
//set values
Colleges c = college.get(position);
((TextView)view.findViewById(R.id.name)).setText(c.getName());
/*((TextView)view.findViewById(R.id.address)).setText(c.getAddress());*/
return view;
}
};
final ListView collegelistnew = (ListView) findViewById(R.id.listView);
collegelistnew.setAdapter(adapter);
collegelistnew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
/*Toast.makeText(
getApplicationContext(),
"You clicked position" + position + "with item name"
+ college.get(position).getName(),
Toast.LENGTH_LONG).show();*/
Intent newIntent =new Intent(getApplicationContext(),CollegeDetails.class);
newIntent.putExtra("college", college.get(position));
startActivity(newIntent);
}
});
}
and my getter and setter class
public class Colleges implements Serializable{
String cname,caddress,ccontact,cwebsites,ccontactb;
public Colleges( String cname, String cwebsites,String caddress, String ccontact, String ccontactb) {
this.cname = cname;
this.caddress = caddress;
this.ccontact = ccontact;
this.ccontact = ccontactb;
this.cwebsites = cwebsites;
}
public String getName() {
return cname;
}
public void setName(String cname) {
this.cname = cname;
}
public String getAddress() {
return caddress;
}
public void setAddress(String caddress) {
this.caddress = caddress;
}
public String getContact() {
return ccontact;
}
public void setContact(String ccontact) {
this.ccontact = ccontact;
}
public String getContactb() {
return ccontactb;
}
public void setContactb(String ccontactb) {
this.ccontactb = ccontactb;
}
public String getWebsites(){
return cwebsites;
}
public void setWebsites(String cwebsites){
this.cwebsites = cwebsites;
}
Here is menu_main xml file
<menu 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" tools:context=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item android:id="#+id/action_search"
android:icon="#drawable/search"
android:title="#string/search_title"
app:showAsAction="always|collapseActionView"
android:actionViewClass="android.widget.SearchView"
app:actionViewClass="android.support.v7.widget.SearchView"/>

Assuming that your list is ready and adapter is also ready to be shown.
From SearchView what you can get is the current text that the user has typed or typing. What you have to do now is pass this text into a method that would create new filtered list.
On onCreateOptionsMenu
SearchManager searchManager = (SearchManager) SearchActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
setSearchAdapter(s);
return false;
}
#Override
public boolean onQueryTextChange(String s) {
setSearchAdapter(s);
return false;
}
});
}
}
You will do your listing tasks in method setSearchAdapter(s), on the basis of the String 's' you will have to recreate a list on every text change that will be populated using the adapter.
This is how your method should look like
private void setSearchAdapter(String s) {
// filter list codes
// ....
searchAdapter =new SearchAdapter(SearchActivity.this,
filteredList);
listView.setAdapter(searchAdapter);
}
There are many ways to create a filtered list.
If you want to save your data in database then you can create Virtual Table and query for search as follows
Cursor cursor = myDataProvider.query(VirtualTable.CONTENT_URI, null, VirtualTable.NAME + " MATCH ? ", new String[]{s + "*"}, null, null);
Note: For simplicity, you can use raw Match query.
Then populate it using suitable adapter class.
We can use Filter class for asynchronous filter as follows:
private class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
for (int i = 0; i < collegeList.size(); i++) {
String name = collegeList.get(i);
if (name.toUpperCase().startsWith(constraint.toString().toUpperCase())) {
nFilteredList.add(name);
}
}
results.values = nFilteredList;
results.count = nFilteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredList = (ArrayList<String>) results.values;
}
}
You need to call searchAdapter.getFilter().filter(s); on text change and override getFilter() method in your adapter.
I hope this solves your query.

Related

Android search view won't work in fragment

When I try to search for members in the search view nothing shows up. Everything just vanishes.
all_members
public class all_members extends Fragment {
ProgressDialog pg;
RecyclerView recyclerView;
AllMembersCustomAdapter myAdapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<AllMembersRecyclerRepresent> members;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
FragmentTransaction fr = getActivity().getSupportFragmentManager().beginTransaction();
fr.replace(R.id.fragment_container,new Home());
fr.commit();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(callback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this line is very important the bwlo line will set the search view
setHasOptionsMenu(true);
return inflater.inflate(R.layout.all_member, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
pg=new ProgressDialog(getContext());
pg.setTitle("Please wait...");
pg.setMessage("Loading all members");
pg.setCanceledOnTouchOutside(false);
pg.show();
setHasOptionsMenu(true);
super.onViewCreated(view, savedInstanceState);
recyclerView=getActivity().findViewById(R.id.r_view_member);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
members = new ArrayList<>();
getvolley();
Log.d("mem",members.toString());
recyclerView.setLayoutManager(layoutManager);
myAdapter = new AllMembersCustomAdapter(members);
recyclerView.setAdapter(myAdapter);
}
public void getvolley(){
//volley and get all members list
String url="";
RequestQueue queue = Volley.newRequestQueue(getActivity());
JsonArrayRequest requestUrl=new JsonArrayRequest(Request.Method.POST, url, null,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i=0;i< response.length();i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
AllMembersRecyclerRepresent ar= new AllMembersRecyclerRepresent();
ar.setName( jsonObject.getString("name"));
ar.setSurname( jsonObject.getString("surname"));
ar.setPh_no( jsonObject.getString("ph_no"));
String id=( jsonObject.getString("member_id"));
String email=( jsonObject.getString("email"));
String is_active=( jsonObject.getString("is_active"));
String dob=( jsonObject.getString("date_of_birth"));
String medical_history=( jsonObject.getString("medical_history"));
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(dob, formatter);
ar.setDOB(String.valueOf(date));
Log.d("date:",String.valueOf(date));
ar.setId(id);
ar.setDOB(String.valueOf(date));
ar.setEmail(email);
ar.setIs_active(is_active);
ar.setMedical_history(medical_history);
ar.setIs_active(is_active);
members.add(ar);
} catch (JSONException e) {
e.printStackTrace();
}
myAdapter.notifyDataSetChanged();
}
pg.cancel();
Toast.makeText(getContext(), "Total Members: "+myAdapter.getItemCount(), Toast.LENGTH_LONG).show();
Toast.makeText(getContext(), "Total Members: "+myAdapter.getItemCount(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error+"Something went wrong.\nPlease check your internet connection", Toast.LENGTH_LONG).show();
pg.cancel();
}
});
MySingleton.getInstance(getActivity()).addRequestQueue(requestUrl);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.menuu,menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
myAdapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
AdapterCode
public class AllMembersCustomAdapter extends RecyclerView.Adapter<AllMembersCustomAdapter.ViewHolder> implements Filterable {
private final ArrayList<AllMembersRecyclerRepresent> members;
//member's list without being filtered
private final ArrayList<AllMembersRecyclerRepresent>allMembers;
public AllMembersCustomAdapter(ArrayList<AllMembersRecyclerRepresent> list){
members=list;
allMembers=new ArrayList<>(list);
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView name,surname,ph_no,dob;
ImageView status;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.nameR);
surname=itemView.findViewById(R.id.surnameR);
ph_no=itemView.findViewById(R.id.ph_noR);
dob=itemView.findViewById(R.id.dob_r);
status=itemView.findViewById(R.id.statusR);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//this returns the position of the item clicked
int position= getAdapterPosition();
//members.get(position).getName() this return the data in the array list
// Toast.makeText(view.getContext(), "position clicked is "+String.valueOf(
// members.get(position).getName()), Toast.LENGTH_SHORT).show();
String name= members.get(position).getName();
String surname = members.get(position).getSurname();
String ph_no = members.get(position).getPh_no();
String id = members.get(position).getId();
String email = members.get(position).getEmail();
String is_active = members.get(position).getIs_active();
String dob = members.get(position).getDOB();
String medical_history = members.get(position).getMedical_history();
Intent i = new Intent(view.getContext(), memberInfo.class);
i.putExtra("name",name);
i.putExtra("surname",surname);
i.putExtra("ph_no",ph_no);
i.putExtra("id",id);
i.putExtra("email",email);
i.putExtra("is_active",is_active);
i.putExtra("dob",dob);
i.putExtra("medical",medical_history);
view.getContext().startActivity(i);
}
});
}
}
#NonNull
#Override
public AllMembersCustomAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_members_recycler,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull AllMembersCustomAdapter.ViewHolder holder, int position) {
holder.itemView.setTag(members.get(position));
holder.name.setText(members.get(position).getName());
holder.ph_no.setText(members.get(position).getPh_no());
holder.surname.setText(members.get(position).getSurname());
holder.dob.setText(members.get(position).getId());
//setting image
//volley to see if the member is Active or not
if(members.get(position).getIs_active()=="true"){
holder.status.setImageResource(R.drawable.active);
}else{
holder.status.setImageResource(R.drawable.inactive);
}
}
#Override
public int getItemCount() {
return members.size();
}
#Override
public Filter getFilter() {
return filter;
}
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
ArrayList<AllMembersRecyclerRepresent> filteredList = new ArrayList<>();
if(charSequence==null || charSequence.length()==0){
//if empty show all movies
filteredList.addAll(allMembers);
}else{
String filterPattern = charSequence.toString().toLowerCase().trim();
for(AllMembersRecyclerRepresent mem:allMembers){
if(mem.getName().toLowerCase().contains(filterPattern)){
filteredList.add(mem);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values=filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
members.clear();
members.addAll((ArrayList) filterResults.values);
notifyDataSetChanged();
}
};
}
When I click on search the list just becomes blank.
menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/action_search"
android:title="SEARCH"
android:icon="#drawable/search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
/>
</menu>
I even tried the same on another activity but still it doesn't work. What am I doing wrong here. The data in the recycler view is being fetched by the server but it won't filter out when clicked on search.

Problem with search Filter in my Database

I have a search bar that search in all of my database.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
psList = ps_da.searchBox(s);
adapterPS = new AdapterPS(ActivityPS.this,psList);
recyclerView.setLayoutManager(new LinearLayoutManager(ActivityPS.this));
recyclerView.setAdapter(adapterPS);
return false;
}
and i have a Alert dialog that filter my result that show in my recyclerview.
imgFilter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog dialog = new Dialog(ActivityPS.this);
dialog.setContentView(R.layout.dialog_filter_layout);
Button btnfliter =dialog.findViewById(R.id.btncheckFilter);
CheckBox chkActive = dialog.findViewById(R.id.chkActiveDirectory);
CheckBox chkDNS = dialog.findViewById(R.id.chkDND);
CheckBox chkDHCP = dialog.findViewById(R.id.chkDHCP);
CheckBox chkVPN = dialog.findViewById(R.id.chkVPN);
CheckBox IP = dialog.findViewById(R.id.IP);
RadioGroup radioGroup = dialog.findViewById(R.id.radiogroupk);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rd = group.findViewById(checkedId);
if (rd.isChecked()){
if (rd.getText().equals("Client")){
chkActive.setEnabled(false);
chkDHCP.setEnabled(false);
chkVPN.setEnabled(false);
chkDNS.setEnabled(false);
}else if (rd.getText().equals("All")){
chkActive.setEnabled(true);
chkDHCP.setEnabled(true);
chkVPN.setEnabled(true);
chkDNS.setEnabled(true);
}else if (rd.getText().equals("Server")){
chkActive.setEnabled(true);
chkDHCP.setEnabled(true);
chkVPN.setEnabled(true);
chkDNS.setEnabled(true);
}
}
}
});
btnfliter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!IP.isChecked()){
if (chkActive.isChecked()){
acvtiveDirectory = chkActive.getText().toString();
}if (chkDHCP.isChecked()){
DHCP =chkDHCP.getText().toString();
}if (chkDNS.isChecked()){
DNS = chkDNS.getText().toString();
}if (chkVPN.isChecked()){
VPN = chkVPN.getText().toString();
} psList =ps_da.searchByFilter(acvtiveDirectory,DNS,DHCP,VPN);
adapterPS = new AdapterPS(ActivityPS.this,psList);
recyclerView.setAdapter(adapterPS);
adapterPS.notifyDataSetChanged();
dialog.dismiss();
}else {
psList = ps_da.findAll();
adapterPS = new AdapterPS(ActivityPS.this,psList);
recyclerView.setAdapter(adapterPS);
dialog.dismiss();
}
}
});
dialog.show();
}
});
}
but I when I add my filter it correctly show on my recyclerview but when I wanna search between filtred result in the search bar it search in whole database.I want to search in the filtred range. Any Idea?
And thats my realm DA class for my PS object:
public RealmResults<PS> findAll(){
pslist = myrealm.where(PS.class).findAll();
return pslist;
}
public RealmResults<PS> searchBox(String s){
pslist = myrealm.where(PS.class).contains("commandName",s, Case.INSENSITIVE).findAll();
return pslist;
}
public RealmResults<PS> searchByFilter(String Active,String DNS,String DHCP,String VPN){
pslist = myrealm.where(PS.class).beginGroup().equalTo("commandName",Active)
.or()
.equalTo("commandName",DHCP)
.or()
.equalTo("commandName",DNS)
.or()
.equalTo("commandName",VPN)
.endGroup().findAll();
return pslist;
}
In onQueryTextChange you create a new adapter each time.
You need to instantiate the adapter once and keep its reference in your activity, so you can set data to it and call getFilter().filter("") on it to filter data you did set.
To use filter in your adapter you can implement Filterable, but return your results in performFiltering method (Filtering Realm object in android).
Here is an example (didn't test it)
public class MyAdapter extends BaseAdapter<ArticleEntity> implements Filterable{
private RealmResults<ArticleEntity> items;
private RealmResults<ArticleEntity> filteredItems;
private ArticleFilter filter;
public MyAdapter(RealmResults<ArticleEntity> items) {
this.items = items;
filter = new ArticleFilter();
filter.filter("");
}
public void setItems(RealmResults<ArticleEntity> items) {
this.items = items;
filter.filter("");
}
#Override
public int getCount() {
return filteredItems.size();
}
#Override
public ArticleEntity getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Filter getFilter() {
return filter;
}
private class ArticleFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
return new FilterResults();
}
#Override
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = items.where()
.equalTo("your_field", "value")
.sort("name")
.findAll();
notifyDataSetChanged();
}
}
}
So your filtering based on your checkboxes should be done in the filter publishResults method.

SearchView for RecyclerView not working

I have implemented searchview filter for recyclerview in fragment like below but when I am entering the query in searchview nothing happens .
My Fragment class: DiscussionForum.java
public class DiscussionForum extends Fragment implements ForumAdapter.ForumAdapterListener {
private TextView socname;
private EditText messageinput;
private SearchView search;
// SearchView searchView;
private FloatingActionButton messagesend;
ProgressDialog progressDialog;
private static final String TAG = "Discussion Forum";
private RecyclerView recyclerView;
private List<ForumData> forumlist;
private ForumAdapter mAdapter;
private OnFragmentInteractionListener mListener;
private LinearLayout list;
private String sendurl, geturl;
public DiscussionForum() {
// Required empty public constructor
}
public static DiscussionForum newInstance(String param1, String param2) {
DiscussionForum fragment = new DiscussionForum();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discussion_forum, container, false);
onButtonPressed("Discussion Forum");
forumlist = new ArrayList<>();
recyclerView = view.findViewById(R.id.listviewforum);
list = view.findViewById(R.id.list);
search = view.findViewById(R.id.search);
int resId = R.anim.layout_animation_fall_down;
LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(getContext(), resId);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setLayoutAnimation(animation);
mAdapter = new ForumAdapter(getContext(), forumlist, this);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
geturl = "";
fetchforumdata(getActivity().getIntent().getStringExtra("id"));
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
return true;
}
});
return view;
}
private void fetchforumdata(final String id1) {
progressDialog.setMessage("Loading...");
showDialog();
StringRequest request = new StringRequest(Request.Method.GET,
geturl + id1,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.d("tag2","id"+id1);
Log.d(TAG, "Response Prop: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("errors");
if (!error) {
JSONObject dataobj = jObj.getJSONObject("data");
JSONArray ticketarray = dataobj.getJSONArray("result");
if (ticketarray.length() == 0) {
list.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
List<ForumData> items = new Gson().fromJson(ticketarray.toString(), new TypeToken<List<ForumData>>() {
}.getType());
forumlist.clear();
forumlist.addAll(items);
recyclerView.setAdapter(mAdapter);
}
} else {
// String errorMsg = jObj.getString("error_msg");
Toast.makeText(getContext(),
"Try again or report an issue", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
hideDialog();
}
});
MyApplication.getInstance().addToRequestQueue(request);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(String title) {
if (mListener != null) {
mListener.onFragmentInteraction(title);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public void onDocumentSelected(String id) {
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String title);
}}
My Adapter Class :ForumAdapter
public class ForumAdapter extends RecyclerView.Adapter<ForumAdapter.MyViewHolder> implements Filterable {
private Context context;
private List<ForumData> ticketlist;
private List<ForumData> filterlist;
private ForumAdapterListener listener;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView username,createdat,forummessage,flatno,category,likes,subcount;
ImageView edit;
public MyViewHolder(View view) {
super(view);
username=view.findViewById(R.id.user_name2);
createdat=view.findViewById(R.id.date2);
edit = view.findViewById(R.id.profile_icon2);
forummessage=view.findViewById(R.id.forum_message);
flatno=view.findViewById(R.id.flat_no);
category=view.findViewById(R.id.category);
likes=view.findViewById(R.id.likes_data);
subcount=view.findViewById(R.id.count_data);
}
}
public ForumAdapter(Context context, List<ForumData> ticketlist, ForumAdapterListener listener) {
this.context = context;
this.listener = listener;
this.ticketlist = ticketlist;
this.filterlist=ticketlist;
}
#Override
public ForumAdapter.MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.discussion_forum_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder( ForumAdapter.MyViewHolder holder, int position) {
final ForumData contact = ticketlist.get(position);
holder.username.setText(contact.getUsername());
holder.flatno.setText(contact.getFlattitle());
holder.forummessage.setText(contact.getMessage());
holder.createdat.setText(contact.getCreated_at());
holder.category.setText(contact.getCategory());
holder.likes.setText(contact.getLikes());
holder.subcount.setText(contact.getSubcount());
Glide.with(context)
.load(url+".jpg")
.apply(new RequestOptions().circleCrop().placeholder(R.drawable.man).error(R.drawable.man))
.into(holder.edit);
}
});
}
#Override
public int getItemCount() {
return ticketlist.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filterlist = ticketlist;
} else {
List<ForumData> filteredList = new ArrayList<>();
for (ForumData row : ticketlist) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getUsername().toLowerCase().contains(charString.toLowerCase()) || row.getCategory().contains(charSequence)) {
filteredList.add(row);
}
}
filterlist = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterlist;
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterlist = (ArrayList<ForumData>) results.values;
notifyDataSetChanged();
}
}
;
}
public interface ForumAdapterListener {
void onDocumentSelected(String contact);
}}
I have gone through many solutions like here , here ,here
But I am unable to figure out what is wrong with my code . Please help me figure out where the exact problem is.
There are multiple issues with your Adapter implementation. If I understand your code correctly you want to keep a reference to a list of unfiltered items (List<ForumData> ticketlist) and filter this list and display the filtered results (List<ForumData> filterlist) on the screen.
Firstly, you want to display filterlist on the screen so in onBindViewHolder() and getItemCount() you need to use filterlist instead of ticketlist.
Secondly, you want to ensure that ticketlist stays unchanged so that all future searches are on the same content. To do this you will have to replace all filterlist = ticketlist; with filterlist = new ArrayList<>(ticketlist); (in your contstructor and in performFiltering()) to avoid changing the contents of ticketlist.
This should make your code functional at least. I suggest you watch this video on Java and objects and references as well.
Another way to go is to filter the data and and refresh the recyclerview's adapter in the onQueryTextChange :
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList< ForumData > filteredData = new ArrayList<>();
for (ForumData forumData : data) {
if (forumData..getUsername().toLowerCase().contains(newText.toLowerCase())) {
filteredData.add(forumData);
}
}
adapter = new ForumAdapter(data, getContext() , this);
recyclerView.setAdapter(adapter);
return true ;
}
})

Autosearching option using filter method in recyclerview

In my app I have implemented a recyclerview with cardview to show the list of the employee inside a company. Now I want to implement a serch option by which user can search with the name of the employee. I have read related document in website about it. I wrote a code to implement a serch option. But unfortunately I can see the search option and I can write it but it cannot detect the name from the list. I do not know what is the problem inside my code. Here is my adapter class where I implment Filterable mehtod
public class MyColleaguesAdapter extends RecyclerView.Adapter<MyColleaguesAdapter.ColleagueHolder> implements Filterable {
private static final String TAG = "MyColleaguesAdapter";
protected List<MyColleageModel> colleagueObject;
protected List<MyColleageModel> filteredcolleague;
private Context context;
public MyColleaguesAdapter(List<MyColleageModel> colleagueObject, Context context) {
this.colleagueObject = colleagueObject;
this.filteredcolleague=colleagueObject;
this.context = context;
}
#Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext())
.inflate(R.layout.colleage_row_layout,parent,false);
return new ColleagueHolder(view);
}
#Override
public void onBindViewHolder(ColleagueHolder holder, int position) {
final MyColleageModel myColleague=colleagueObject.get(position);
holder.name.setText(myColleague.getName());
holder.company.setText(myColleague.getCompany());
holder.title.setText(myColleague.getTitle());
holder.cardView.setTag(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
openDetailActivity(myColleague.getMobile(),myColleague.getMail(), myColleague.getName(),
myColleague.getCompany(), myColleague.getDepartment(), myColleague.getTitle());
}
});
}
#Override
public int getItemCount() {
return colleagueObject.size();
}
//open activity
private void openDetailActivity(String...details)
{
Intent i=new Intent(context,DetailMyColleague.class);
i.putExtra("mail",details[1]);
........
context.startActivity(i);
}
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredcolleague = (List<MyColleageModel>) results.values;
MyColleaguesAdapter.this.notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<MyColleageModel> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = colleagueObject;
} else {
filteredResults = getFilteredResults(constraint.toString().toLowerCase());
}
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
};
}
protected List<MyColleageModel> getFilteredResults(String constraint) {
List<MyColleageModel> results = new ArrayList<>();
for (MyColleageModel item : colleagueObject) {
if (item.getName().toLowerCase().contains(constraint)) {
results.add(item);
Log.d( TAG,"value is here "+item.getName());
}
}
return results;
}
public class ColleagueHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView cardView;
public TextView name;
public TextView company;
public TextView title;
public ColleagueHolder(View itemView) {
super(itemView);
name=(TextView) itemView.findViewById(R.id.colleague_name);
company=(TextView)itemView.findViewById(R.id.company_name);
title=(TextView) itemView.findViewById(R.id.job_role);
cardView=(CardView)itemView.findViewById(R.id.cvSingleUser);
}
}
Here is my MainActivity
public class MyColleaguesPage extends AppCompatActivity implements SearchView.OnQueryTextListener{
private RecyclerView recyclerView;
private CardView cardView;
private MyColleaguesAdapter adapter;
private List<MyColleageModel> colleagueObject;
InputStream is;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
cardView=(CardView)findViewById(R.id.cvSingleUser);
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MyColleaguesPage.this);
recyclerView.setLayoutManager(layoutManager);
new JSONTask().execute();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
List<MyColleageModel> filteredModelList = filter(colleagueObject, newText);
if (filteredModelList.size() > 0) {
//myPhotosAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MyColleaguesPage.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
public class JSONTask extends AsyncTask<String, String, List<MyColleageModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<MyColleageModel> doInBackground(String... params) {
colleagueObject = new ArrayList<MyColleageModel>();
try {
//withou Gson
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("contacts");
MyColleageModel my_clg;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String val1 = jo_inside.getString("mobile");
String val2 = jo_inside.getString("mail");
String val3 = jo_inside.getString("name");
String val4 = jo_inside.optString("company");
String val5 = jo_inside.optString("department");
String val6 = jo_inside.optString("title");
my_clg = new MyColleageModel(val1, val2, val3, val4, val5, val6);
colleagueObject.add(my_clg);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final List<MyColleageModel> result) {
super.onPostExecute(result);
adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
private String loadJSONFromAsset() {
....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recyclerviewmenu, menu);
final MenuItem search = menu.findItem(R.id.search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
searchView.setOnQueryTextListener(this);
return true;
}
private List<MyColleageModel> filter(List<MyColleageModel> models, String query) {
query = query.toLowerCase();
final List<MyColleageModel> filteredModelList = new ArrayList<>();
for (MyColleageModel model : models) {
final String text = model.getName().toLowerCase().toString();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
// arraylist in your adapter
adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return filteredModelList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
And this is my recyclerviewmenu.xml
<menu 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" tools:context="myColleagues.MyColleaguesPage">
<item
android:id="#+id/search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
I am not getting the error inside my code.
follow this stpes
step 1 implements SearchView.OnQueryTextListener in youractivity
step 2 in onCreateOptionsMenu write below code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_album_search, menu);
final MenuItem item = menu.findItem(R.id.menu_search_album);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
step 3 write this in onQueryTextChange() method
#Override
public boolean onQueryTextChange(String newText) {
List<MyColleageModel> filteredModelList = filter(data_fieldses, newText);
if (filteredModelList.size() > 0) {
//myPhotosAdapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MyPhotosActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
step 4
private List<MyColleageModel> filter(List<MyColleageModel> models, String query) {
query = query.toLowerCase();
final List<MyColleageModel> filteredModelList = new ArrayList<>();
for (MyColleageModel model : models) {
final String text = model.getImagename().toLowerCase().toString();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
// arraylist in your adapter
myPhotosAdapter = new MyPhotosAdapter( MyPhotosActivity.this, (ArrayList<MyColleageModel>) filteredModelList);
recyclerViewMyPhotos.setLayoutManager(new GridLayoutManager(MyPhotosActivity.this, 2));
recyclerViewMyPhotos.setAdapter(myPhotosAdapter);
myPhotosAdapter.notifyDataSetChanged();
return filteredModelList;
}
ask me in case of any query
IMO you missed setNotifyDatachaged() in onPostExecute() try above code
public class MyColleaguesPage extends AppCompatActivity{
private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private List<MyColleageModel> colleagueObject;
InputStream is;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
// Showing and Enabling clicks on the Home/Up button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
recyclerView = (RecyclerView) findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MyColleaguesPage.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new MyColleaguesAdapter(colleagueObject, getApplicationContext());
recyclerView.setAdapter(adapter);
new JSONTask().execute();
}
public class JSONTask extends AsyncTask<String, String, List<MyColleageModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<MyColleageModel> doInBackground(String... params) {
colleagueObject = new ArrayList<MyColleageModel>();
try {
//withou Gson
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("contacts");
// ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
// HashMap<String, String> m_li;
MyColleageModel my_clg;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
//my_clg=new MyColleageModel();
String val1 = jo_inside.getString("mobile");
String val2 = jo_inside.getString("mail");
String val3 = jo_inside.getString("name");
String val4 = jo_inside.optString("company");
String val5 = jo_inside.optString("department");
String val6 = jo_inside.optString("title");
my_clg = new MyColleageModel(val1, val2, val3, val4, val5, val6);
colleagueObject.add(my_clg);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final List<MyColleageModel> result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
}
}
private String loadJSONFromAsset() {
...........
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.recyclerviewmenu, menu);
MenuItem search = menu.findItem(R.id.search);
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) {
adapter.getFilter().filter(newText);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}

Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference ( while using with adapter,fragment and activity) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am getting this error-Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
This is what i have done!
PeopleListFragment
**PeopleListFragment**
public class PeopleListFragment extends Fragment{
public static final String DISPLAY_URL = ServiceAPI.URL_CONTACTS;
private static final String TAG = "PeopleListActivity";
public static final boolean DEBUG = Constant.DEBUG;
private ProgressDialog progressDialog;
public PeopleAdapter adapter;
private GetAllPeopleTask mGetAllPeople = null;
private Intent intent;
public static ListView mContactlistView;
public PeopleListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_people_list, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mContactlistView = (ListView) view.findViewById(R.id.people_list);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<People> contactList = new ArrayList<People>();
adapter = new PeopleAdapter(getActivity().getApplicationContext(),
R.layout.people_list_item, contactList);
mContactlistView.setAdapter(adapter);
mContactlistView.setTextFilterEnabled(true);
mContactlistView.setFastScrollEnabled(true);
mContactlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String empId = String.valueOf(adapter.getItem(position).getEmployeeId());
String name = String.valueOf(adapter.getItem(position).getFirstName());
intent = new Intent(getActivity(),
PeopleDetailsActivity.class);
intent.putExtra("EmployeeId", empId);
intent.putExtra("name", name);
startActivity(intent);
}
});
startAsyncTask();
TextView textView = new TextView(getContext());
textView.setText("Empty");
mContactlistView.setEmptyView(textView);
}
public void startAsyncTask() {
mGetAllPeople = new GetAllPeopleTask();
mGetAllPeople.execute(DISPLAY_URL, "12345678");
}
public class GetAllPeopleTask extends AsyncTask<String, Void, List<People>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading");
progressDialog.show();
}
#Override
protected ArrayList<People> doInBackground(String... params) {
ArrayList<People> peopleList = new ArrayList<>();
try {
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(40000);
httpURLConnection.setConnectTimeout(50000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
JSONObject request = new JSONObject();
request.put("session", params[1]);
String bodyParams = request.toString();
if (DEBUG) {
Log.i(TAG, bodyParams);
}
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(bodyParams.getBytes().length));
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.writeBytes(bodyParams);
outputStream.flush();
outputStream.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
Log.i(TAG, "Success");
} else {
Log.i(TAG, "Error Code :" + httpURLConnection.getResponseCode());
}
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.i(TAG, "Builder String : " + builder.toString());
JSONObject jsonObject = new JSONObject(builder.toString());
Log.i(TAG, "Response JSON : " + jsonObject.toString());
if (jsonObject.has("responseData")) {
JSONArray responseDataArr = jsonObject.optJSONArray("responseData");
for (int i = 0; i < responseDataArr.length(); i++) {
JSONObject peopleJSON = responseDataArr.optJSONObject(i);
People people = new People();
people.setEmployeeId(peopleJSON.optString("employeeId"));
people.setFirstName(peopleJSON.optString("firstName"));
people.setLastName(peopleJSON.optString("lastName"));
// Log.i("hebsiba ", "People first name" + people.getFirstName() + ", last name is " + people.getLastName()) ;
if((!people.getFirstName().isEmpty()) && (!people.getLastName().isEmpty())) {
peopleList.add(people);
}
if (DEBUG) {
Log.i(TAG, "People " + people.getEmployeeId());
}
}
}
} catch (IOException | JSONException e) {
Log.e(TAG, e.toString());
}
return peopleList;
}
#Override
protected void onPostExecute(List<People> people) {
super.onPostExecute(people);
Collections.sort(people, new Comparator<People>() {
#Override
public int compare(People lhs, People rhs) {
return lhs.getFirstName().compareToIgnoreCase(rhs.getFirstName());
}
});
adapter.addAll(people);
if (DEBUG) {
Log.i(TAG, adapter.getCount() + " ");
}
Log.v(TAG, String.valueOf(people.size()));
progressDialog.dismiss();
}
}
}
This is the PeopleAdapter
**PeopleAdapter**
public class PeopleAdapter extends ArrayAdapter<People> implements Filterable {
private PeopleListActivity activity;
private PeopleFilter peopleFilter;
private List<People> peopleList;
private List<People> filteredList;
public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
super(applicationContext, people_list_item, contactList);
filteredList = contactList;
getFilter();
}
#Override
public int getCount() {
return filteredList.size();
}
#Override
public People getItem(int i) {
return filteredList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
People peopleList = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.people_list_item, null);
holder = new ViewHolder();
holder.firstName = (TextView) convertView.findViewById(R.id.firstName);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.firstName.setText(peopleList.getFirstName());
holder.lastName.setText(peopleList.getLastName());
return convertView;
}
/**
* Get custom filter
* #return filter
*/
#Override
public Filter getFilter() {
if (peopleFilter == null) {
peopleFilter = new PeopleFilter();
}
return peopleFilter;
}
static class ViewHolder {
TextView firstName;
TextView lastName;
}
private class PeopleFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint!=null && constraint.length()>0) {
ArrayList<People> tempList = new ArrayList<>();
// search content in friend list
for (People user : peopleList) {
if (user.getFirstName().toLowerCase().contains(constraint.toString().toLowerCase())) {
tempList.add(user);
}
}
filterResults.count = tempList.size();
filterResults.values = tempList;
} else {
filterResults.count = peopleList.size();
filterResults.values = peopleList;
}
return filterResults;
}
/**
* Notify about filtered list to ui
* #param constraint text
* #param results filtered result
*/
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
filteredList = (ArrayList<People>) results.values;
notifyDataSetChanged();
}
}
}
And this is PeopleListActivity
**PeopleListActivity**
public class PeopleListActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private PeopleListFragment fragment;
private FragmentManager displayFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.argb(255, 180, 110, 60));
}
setContentView(R.layout.activity_people);
Toolbar toolbar = (Toolbar) findViewById(R.id.people_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PeopleListActivity.this, NavigationActivity.class);
startActivity(intent);
}
});
displayFragment = getSupportFragmentManager();
fragment = new PeopleListFragment();
displayFragment.beginTransaction().add(R.id.people_fragment, fragment).commit();
if (savedInstanceState == null) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setIconifiedByDefault(false);
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
return true;
// return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
PeopleAdapter peopleAdapter = (PeopleAdapter) PeopleListFragment.mContactlistView.getAdapter();
peopleAdapter.getFilter().filter(newText);
return true;
}
}
Could anyone help me with this..?
Assign some value to filteredList when you create the Adapter
Example:
public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
super(applicationContext, people_list_item, contactList);
filteredList = contactList;
getFilter();
}
filteredList is null when getCount() is called. Instantiate it first or make sure filteredList has some content.

Categories

Resources