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 ;
}
})
Related
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.
I am creating an app I using search view in fragment to search recycler view ArrayList data but below method not showing the result
Not show my filter result in recycler view
How to show filter result in recycle view in the fragment.
anyone tell me what changes below code to fix this problem
please help me
Fragment
import in.getagf.pickuplines.Model.dataAdapter;
import in.getagf.pickuplines.Model.dataItem;
/**
* A simple {#link Fragment} subclass.
*/
public class LatestFragment extends Fragment {
private View myView;
private DatabaseReference RootRef, AdsRef;
private AdView adView;
private RecyclerView mRecyclerView;
dataAdapter mDataAdapter;
private RecyclerView.LayoutManager mDataLayoutManager;
public LatestFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
myView = inflater.inflate(R.layout.fragment_latest, container, false);
RootRef = FirebaseDatabase.getInstance().getReference().child("App_Data");
AdsRef = FirebaseDatabase.getInstance().getReference().child("Apps Link").child("AdsUnitID");
mRecyclerView = (RecyclerView) myView.findViewById(R.id.latest_recyclerView);
mDataLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mDataLayoutManager);
mDataAdapter = new dataAdapter(getDataSetLines(), getActivity());
mRecyclerView.setAdapter(mDataAdapter);
getResult.clear();
// offlinedata();
receiverData();
return myView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.home, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
mDataAdapter.getFilter().filter(newtext);
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void receiverData()
{
RootRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
if (dataSnapshot.exists() && !dataSnapshot.child("category").getValue().toString().equals("Good Night"))
{
String Lines = dataSnapshot.child("lines").getValue().toString();
String Pic = dataSnapshot.child("pic").getValue().toString();
String visite_id = dataSnapshot.getKey();
dataItem obj = new dataItem(visite_id, Lines, Pic);
getResult.add(obj);
mDataAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
AdsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String fB_Latest = dataSnapshot.child("fB_Latest").getValue(String.class);
// Facebook Banner Ads
adView = new AdView(getActivity(), fB_Latest, AdSize.BANNER_HEIGHT_50);
LinearLayout adContainer = (LinearLayout) myView.findViewById(R.id.latest_facebook_ads);
adContainer.addView(adView);
adView.loadAd();
// end
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
return getResult;
}
}
dataAdapter
/**
* Created by Vinay Singh on 16/02/2019.
*/
public class dataAdapter extends RecyclerView.Adapter<DataViewHolders>
implements Filterable {
private List<dataItem> myList;
private List<dataItem> myListFull;
private Context context;
public dataAdapter(List<dataItem> myList, Context context) {
this.myList = myList;
this.context = context;
myListFull = new ArrayList<>(myList);
}
#Override
public DataViewHolders onCreateViewHolder(ViewGroup viewGroup, int position) {
View layoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view, null, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutView.setLayoutParams(lp);
DataViewHolders rcv = new DataViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(DataViewHolders holder, int position) {
String lines = myList.get(position).getLines();
holder.mLines.setText(myList.get(position).getLines());
holder.mVisit_id.setText(myList.get(position).getVisite_id());
if (myList.get(position).getPic().equals("default")) {
Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
}else if (myList.get(position).getPic().equals("Funny"))
{
Picasso.get().load(R.drawable.funny).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Romantic"))
{
Picasso.get().load(R.drawable.romantic).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Chat Tips"))
{
Picasso.get().load(R.drawable.chat).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Good Morning"))
{
Picasso.get().load(R.drawable.goodmorning).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Motivation"))
{
Picasso.get().load(R.drawable.motivation).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Shayri"))
{
Picasso.get().load(R.drawable.shayari).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("WhatsApp"))
{
Picasso.get().load(R.drawable.whatsapp).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Jokes"))
{
Picasso.get().load(R.drawable.jokes).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Good Night"))
{
Picasso.get().load(R.drawable.goodnight).into(holder.mImage);
}
else if (myList.get(position).getPic().equals("Chatting"))
{
Picasso.get().load(R.drawable.chatting).into(holder.mImage);
}
else
{
Picasso.get().load(R.drawable.app_logo).into(holder.mImage);
}
}
#Override
public int getItemCount() {
return this.myList.size();
}
#Override
public Filter getFilter() {
return myListFilter;
}
private Filter myListFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String charString = constraint.toString();
if (charString.isEmpty())
{
myListFull = myList;
}
else
{
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myListFull)
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
}
FilterResults results = new FilterResults();
results.values = myListFull;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
myList.clear();
myList.addAll((List) results.values);
notifyDataSetChanged();
}
};
}
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myList) // myListFull wrong
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
First Remove this code in your fragment
private ArrayList<dataItem> getResult = new ArrayList<dataItem>();
private List<dataItem> getDataSetLines() {
return getResult;
}
}
and intialized ArrayList in above of onCreateView method and change this code in onCreateView method
mDataAdapter = new dataAdapter(getResult, getContext());
Now add this code in your Adapter
List<dataItem> filteredList = new ArrayList<>();
for (dataItem item : myList) // myListFull wrong
{
if (item.getLines().contains(charString)){
filteredList.add(item);
}
}
myListFull = filteredList;
In your myListFull ArrayList to not add data of myList.
I hope this can help You!
Thank You.
I'm making an app in Android.
I'm getting JSON data containing pokemons name from URL(http://kerast.com/pokemon/pokemons.json) using retrofit. The names and types display in a recyclerView and after clicking on one another Activity opens and display attack, defense and moves.
So far I've been able to open a new activity but have no idea how to pass the object. I suppose there is no need to reload the json by re writing the same code twice for each activity ?
Here is my class :
public class Pokemon {
private String name;
private String type;
private Integer attack;
private Integer defense;
private Integer evolveLevel;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public Integer getattack() { return attack; }
public Integer getdefense() { return defense; }
public Integer getEvolveLevel() { return evolveLevel; }
}
My DataAdpater :
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements Filterable {
private ArrayList<Pokemon> mArrayList;
private ArrayList<Pokemon> mFilteredList;
public DataAdapter(ArrayList<Pokemon> arrayList) {
mArrayList = arrayList;
mFilteredList = arrayList;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_name.setText(mFilteredList.get(i).getName());
viewHolder.tv_version.setText(mFilteredList.get(i).getName());
viewHolder.tv_api_level.setText(mFilteredList.get(i).getType());
}
#Override
public int getItemCount() {
return mFilteredList.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
mFilteredList = mArrayList;
} else {
ArrayList<Pokemon> filteredList = new ArrayList<>();
for (Pokemon marraylist : mArrayList) {
if (marraylist.getName().toLowerCase().contains(charString) || marraylist.getType().toLowerCase().contains(charString)) {
filteredList.add(marraylist);
}
}
mFilteredList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = mFilteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
mFilteredList = (ArrayList<Pokemon>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_name,tv_version,tv_api_level;
public ViewHolder(View view) {
super(view);
tv_name = (TextView)view.findViewById(R.id.tv_name);
tv_version = (TextView)view.findViewById(R.id.tv_version);
tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Main2Activity.class);
intent.putExtra("attack", Pokemon);
view.getContext().startActivity(intent);
}
});
}
}
}
And finally my MainActivity :
public class MainActivity extends AppCompatActivity {
public static final String BASE_URL = "http://kerast.com";
private RecyclerView mRecyclerView;
private ArrayList<Pokemon> mArrayList;
private DataAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initViews();
loadJSON();
}
private void initViews(){
mRecyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
}
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mArrayList = new ArrayList<>(Arrays.asList(jsonResponse.getPokemons()));
mAdapter = new DataAdapter(mArrayList);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, 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) {
mAdapter.getFilter().filter(newText);
return true;
}
});
}
}
So how can I get only Attack Defense and evolveLevel to be display in the second Activity ?
implement the Serializable interface Pokemon implements Serializable
and
then you can pass object instances in the intent extra using the putExtra()
//send :
intent.putExtra("Pokemon", obj);
//retrieve :
getIntent().getSerializableExtra("MyClass");
Well answer by akshay is correct but i think this will better way to do it. We can use Parcelable class instead of Serializable.
Refer the following link for difference b/w parcelable and serializale
and to create a POJO class paracelable i use online creator.
Rest is the same
//Sending data
intent.putExtra("String name", object);
//Receving end
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Pokemon pokemon = (Pokemon) bundle.getParcelable("String name")
}
I am using a recyclerView to show a grid of movie posters. The posters are contained in a List<> along with their respective title and so on.
I implemented a searchView widget and I can successuflly get a List of matching results. But I can't hide the other ones.
As you understand I don't want to delete the irrelevant movies from the adapter or the user would not be able to see them again.
This is the code:
public class SearchUtils {
public static List<String> search(List<Show> list, String keyword){
List<String> results = new ArrayList<>();
for (Show curVal : list){
String curTitle = curVal.getTitle().toLowerCase().trim();
if (curTitle.contains(keyword)){
results.add(curTitle);
}else{
results = new ArrayList<>();
}
}
return results;
}
}
ListFragment.java
public class ListFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Show>> {
private static final String LOG_TAG = "ListFragment";
private static final String ARG_SCOPE = "com.dcs.shows.activity_to_launch";
private static final String BASE_URL = "http://api.themoviedb.org/3";
private TextView tv;
private ProgressBar pb;
private int scope;
private RecyclerView mRecyclerView;
private ShowAdapter mShowAdapter;
private SearchView mSearchView;
public static ListFragment newInstance(int target) {
Bundle args = new Bundle();
args.putInt(ARG_SCOPE, target);
ListFragment fragment = new ListFragment();
fragment.setArguments(args);
return fragment;
}
public ListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scope = getArguments().getInt(ARG_SCOPE);
setHasOptionsMenu(true);
Log.i(LOG_TAG, "onCreate#Scope is: " + scope);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list, container, false);
mShowAdapter = new ShowAdapter(new ArrayList<Show>());
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
GridLayoutManager glm = new GridLayoutManager(getActivity(), 4);
mRecyclerView.setLayoutManager(glm);
mRecyclerView.addItemDecoration(new SpacesItemDecoration(8, getActivity()));
mRecyclerView.setAdapter(mShowAdapter);
mRecyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(glm) {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
}
});
pb = (ProgressBar)rootView.findViewById(R.id.progress_view);
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
getLoaderManager().initLoader(1, null, this);
} else {
// display error
pb.setVisibility(View.GONE);
}
return rootView;
}
List<Show> searchList;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
mSearchView = (SearchView) myActionMenuItem.getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
if(!mSearchView.isIconified()) {
mSearchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if(s != null || !s.isEmpty()) {
for(Show movie : mShowAdapter.getList()) {
if(movie.getTitle().toLowerCase().contains(s.toLowerCase())){
mShowAdapter.add(movie);
}
mShowAdapter.notifyDataSetChanged();
}
} else {
mShowAdapter.addItemsToList(searchList, false);
}
return false;
}
});
mSearchView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewDetachedFromWindow(View arg0) {
// search was detached/closed
Log.v(LOG_TAG, "Restoring list: " + searchList + " size: " + searchList.size());
mShowAdapter.addItemsToList(searchList, false);
}
#Override
public void onViewAttachedToWindow(View arg0) {
// search was opened
searchList = mShowAdapter.getList();
}
});
}
private class ShowHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView;
public ShowHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.grid_item_image);
mTextView = (TextView) itemView.findViewById(R.id.grid_item_title);
}
}
private class ShowAdapter extends RecyclerView.Adapter<ShowHolder> {
private List<Show> mShows;
public ShowAdapter(List<Show> shows) {
mShows = shows;
}
public void add(Show show){
mShows.add(show);
notifyDataSetChanged();
}
public void addItemsToList(List<Show> newShows, boolean append){
if(append){
mShows.addAll(newShows);
}else {
mShows = newShows;
}
notifyDataSetChanged();
}
public void removeItemsFromList(int index){
mShows.remove(index);
notifyItemRemoved(index);
}
public List<Show> getList(){
return mShows;
}
#Override
public ShowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(R.layout.list_item_row, parent, false);
return new ShowHolder(rootView);
}
#Override
public void onBindViewHolder(ShowHolder holder, int position) {
Show currentShow = mShows.get(position);
holder.mTextView.setText(currentShow.getTitle());
Glide.with(getActivity()).load(currentShow.getImage()).into(holder.mImageView);
}
#Override
public int getItemCount() {
return mShows.size();
}
}
#Override
public Loader<List<Show>> onCreateLoader(int i, Bundle bundle) {
//start the loader with the appropriate uri
//for now it only supports movies+popular
//it will support movies+top, tv+popular, tv+top.
Uri baseUri = Uri.parse(BASE_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendPath("movie");
uriBuilder.appendPath("popular");
uriBuilder.appendQueryParameter("api_key", QueryUtils.API_KEY);
uriBuilder.appendQueryParameter("page", Integer.valueOf(1).toString());
Log.v(LOG_TAG, "onCreateLoader#URL built: " + uriBuilder.toString());
return new ShowLoader(getActivity(), uriBuilder.toString());
}
#Override
public void onLoadFinished(Loader<List<Show>> loader, List<Show> shows) {
// Clear the adapter of previous earthquake data
clearAdapter();
// If there is a valid list of Shows, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (shows != null && !shows.isEmpty()) {
mShowAdapter.addItemsToList(shows, false);
mShowAdapter.notifyDataSetChanged();
}
pb.setVisibility(View.GONE);
}
#Override
public void onLoaderReset(Loader<List<Show>> loader) {
// Loader reset, so we can clear out our existing data.
clearAdapter();
}
private void clearAdapter(){
List<Show> empty = new ArrayList<>();
mShowAdapter.addItemsToList(empty, false);
mShowAdapter.notifyDataSetChanged();
}
Thanks
You can use two lists, one with all the elements (original), and one with just queried elements (this one should use recyclerview adapter). When querying, just select from original list and add them to adapter list, then notify changes. Don't forget to clear adapter list before adding new entries.
Edit: you can try something like this on onQueryTextChange method. Adapt for your own wish.
if(s != null && !s.isEmpty()) {
for(String movie : originalList) {
if(movie.toLowerCase().contains(s.toLowerCase()){
adapter.add(movie);
}
notifyChanges();
}
}
} else { adapter.addAll(originalList); }
I have a problem with my application. Actually, I'm totally stuck. I have a list of countries with implemented clicklistener and searchview. In a situation when I click on a given element without searching the list, everything displays correctly and shows information about a given country. But when I search the list and click on the element, the application goes to the information about the random country. I dont know why this is happening. I have no error. Only a warning:
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
MainActivity
public static final String EXTRA_COUNTRY_NAME = "country_name";
public static final String EXTRA_COUNTRY_REGION = "country_region";
public static final String EXTRA_COUNTRY_NATIVE_NAME = "country_nativename";
public static final String EXTRA_COUNTRY_NAME_LANGUGES= "country_namelanguages";
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<ModelJsona> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://restcountries.eu/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<ModelJsona>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<ModelJsona>>() {
#Override
public void onResponse(Call<List<ModelJsona>> call, Response<List<ModelJsona>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
dataAdapter.setOnitemClickListener(MainActivity.this);
}
#Override
public void onFailure(Call<List<ModelJsona>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
dataAdapter.getFilter().filter(newText);
if (dataAdapter !=null)dataAdapter.getFilter().filter(newText);
return true;
}
});
}
#Override
public void onItemClick(int position) {
Intent detailsIntent = new Intent(this,Details.class);
ModelJsona click = dataArrayList.get(position);
detailsIntent.putExtra(EXTRA_COUNTRY_NAME,click.getName());
detailsIntent.putExtra(EXTRA_COUNTRY_REGION,click.getRegion());
detailsIntent.putExtra(EXTRA_COUNTRY_NATIVE_NAME,click.getNativeName());
detailsIntent.putExtra(EXTRA_COUNTRY_NAME_LANGUGES,click.getLanguages().get(0).getName());
startActivity(detailsIntent);
}
}
DataAdapter
private Context context;
private List<ModelJsona> dataList;
private List<ModelJsona> filtr;
private OnitemClickListener mListener;
public interface OnitemClickListener {
void onItemClick (int position);
}
public void setOnitemClickListener (OnitemClickListener listener)
{
mListener=listener;
}
public DataAdapter(Context context, List<ModelJsona> dataList) {
this.context = context;
this.dataList = dataList;
this.filtr= dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.country_name.setText(filtr.get(position).getName());
holder.country_region.setText(filtr.get(position).getRegion());
holder.country_nativename.setText(filtr.get(position).getNativeName());
holder.country_languagename.setText(filtr.get(position).getLanguages().get(0).getName());
}
#Override
public int getItemCount() {
return filtr.size();
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filtr = dataList;
} else {
ArrayList<ModelJsona> listadoprzeszukiwan = new ArrayList<>();
for (ModelJsona wyszukiwarka : dataList) {
if (
wyszukiwarka.getName().contains(charString) ||
wyszukiwarka.getName().toLowerCase().contains(charString) ||
wyszukiwarka.getRegion().contains(charString) ||
wyszukiwarka.getRegion().toLowerCase().contains(charString) ||
wyszukiwarka.getNativeName().contains(charString) ||
wyszukiwarka.getNativeName().toLowerCase().contains(charString) ||
wyszukiwarka.getTopLevelDomain().contains(charString))
{
listadoprzeszukiwan.add(wyszukiwarka);
}
}
filtr = listadoprzeszukiwan;
}
FilterResults wynikiszukania = new FilterResults();
wynikiszukania.values = filtr;
return wynikiszukania;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults wynikiszukania) {
filtr = (ArrayList<ModelJsona>) wynikiszukania.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView country_name, country_region, country_languagename,country_nativename;
public MyViewHolder(View itemView) {
super(itemView);
country_name = (TextView) itemView.findViewById(R.id.country_name);
country_region = (TextView) itemView.findViewById(R.id.country_region);
country_nativename = (TextView) itemView.findViewById(R.id.country_nativename);
country_languagename= (TextView) itemView.findViewById(R.id.country_languagename);
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));
}
}
}
i see that you get the position in filter list refer to different object with same position value in dataList because after filtering filter list become reference to result but still dataList hold all data.
you can replace itemView click listner by this:
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
String name = filtr.get(position).getName();
for (int i=0 ; i <dataList.size() ; i++ ){
if(name.equals(dataList.get(i).getName()){
position = i;
break;
}
}
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));