I am currently using searchView to filter results on a RecyclerView. The problem is when the fragment is initialized, the list won't appear not until I click on the search icon on the toolbar and type some texts on it. I've tried modifying the codes. Take a look specifically at the adapter and holder classes, if you'll try to exchange my current codes to these:
public MembershipActivationAdapter(Context context, List<Member> members){
this.context = context;
this.mMembers = members;
}
and
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
,it will show the list upon calling the fragment however if I'll type something on the SearchView, it seems to function only as a one way filter. It will filter names but whenever I'll try to remove a character or a text on the searchview, it won't show the list back. Please help me with this. These are my codes:
Adapter & ViewHolder class:
public class MembershipActivationAdapter extends RecyclerView.Adapter<MembershipActivationAdapter.MembershipActivationViewHolder> {
private final List<Member> mMembers;
private final LayoutInflater inflater;
//private final Context context;
public MembershipActivationAdapter(Context context, List<Member> members){
inflater = LayoutInflater.from(context);
mMembers = new ArrayList<>(members);
//this.context = context;
//this.mMembers = members;
}
#Override
public int getItemCount() {
return mMembers.size();
}
#Override
public void onBindViewHolder(MembershipActivationViewHolder holder, final int position) {
final Member m = mMembers.get(position);
holder.name.setText(m.getName());
holder.email.setText(m.getEmail());
if(m.getStatus().equals("Active")){
holder.status.setText(Html.fromHtml("<font color='#00CD00'>" + m.getStatus() + "</font>"));
}else{
holder.status.setText(Html.fromHtml("<font color='#ff0000'>" + m.getStatus() + "</font>"));
}
}
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = inflater.inflate(R.layout.member_activation_content, viewGroup, false);
return new MembershipActivationViewHolder(itemView);
//final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
public static class MembershipActivationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView name;
public final TextView email;
public final TextView status;
public MembershipActivationViewHolder(View v) {
super(v);
v.setOnClickListener(this);
name = (TextView) v.findViewById(R.id.member_name);
email = (TextView) v.findViewById(R.id.member_email);
status = (TextView) v.findViewById(R.id.member_status);
}
}
public List<Member> getMemberList() {
return mMembers;
}
public void animateTo(List<Member> members) {
applyAndAnimateRemovals(members);
applyAndAnimateAdditions(members);
applyAndAnimateMovedItems(members);
}
private void applyAndAnimateRemovals(List<Member> newMembers) {
for (int i = mMembers.size() - 1; i >= 0; i--) {
final Member member = mMembers.get(i);
if (!newMembers.contains(member)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Member> newMembers) {
for (int i = 0, count = newMembers.size(); i < count; i++) {
final Member member = newMembers.get(i);
if (!mMembers.contains(member)) {
addItem(i, member);
}
}
}
private void applyAndAnimateMovedItems(List<Member> newMembers) {
for (int toPosition = newMembers.size() - 1; toPosition >= 0; toPosition--) {
final Member member = newMembers.get(toPosition);
final int fromPosition = mMembers.indexOf(member);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Member removeItem(int position) {
final Member member = mMembers.remove(position);
notifyItemRemoved(position);
return member;
}
public void addItem(int position, Member member) {
mMembers.add(position, member);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Member member = mMembers.remove(fromPosition);
mMembers.add(toPosition, member);
notifyItemMoved(fromPosition, toPosition);
}
}
Fragment Class:
public class MembershipActivationFragment extends Fragment implements SearchView.OnQueryTextListener{
private static String url = "http://www.xxxxx.org/portal/webservices/get_members.php";
private List<Member> memberList;
private RecyclerView recyclerView;
private MembershipActivationAdapter adapter;
private String pid;
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.member_activation, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.members_recycler_view);
setHasOptionsMenu(true);
memberList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
populate();
return rootView;
}
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
String name, email, status;
Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
member = new Member(name, email, status);
memberList.add(member);
} catch (Exception e) {
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
adapter = new MembershipActivationAdapter(getActivity(), memberList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<Member> filteredMemberList = filter(memberList, query);
adapter.animateTo(filteredMemberList);
recyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Member> filter(List<Member> members, String query) {
query = query.toLowerCase();
final List<Member> filteredModelList = new ArrayList<>();
for (Member member : members) {
final String text = member.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(member);
}
}
return filteredModelList;
}
private void hidePDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
RecyclerView container xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/members_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Content class:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name here"
android:textStyle="bold"
android:id="#+id/member_name"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_email"
android:layout_below="#+id/member_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_status"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
Model Class:
public class Member {
private String name;
private String email;
private String status;
public Member(String name, String email, String status) {
this.name = name;
this.email = email;
this.status = status;
}
public Member(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Atlast! I was able to find the resolution for this. Kudos to the developer himself, Xaver Kapeller!
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
// hidePDialog();
String email, status;
// Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
final String name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
mModels.add(new ExampleModel(name));
// member = new Member(name, email, status);
} catch (Exception e) {
}
}
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
Just tranfer these two lines of code inside onResponse() and everything will work perfectly fine:
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
Related
same data appear in whole Recyclerview and position increasing but data same appear
in useradapter i log the position and position increase but data is same in onbindviewholder
useradapter
public class useradapter extends RecyclerView.Adapter<useradapter.CustomView> {
String nn = "m";
List<allusermodel> list1;
private Context context;
private LayoutInflater layoutInflater;
public useradapter(Context context, List<allusermodel> list1) {
Log.e("reached1", nn);
this.context = context;
this.list1 = list1;
}
#Override
public useradapter.CustomView onCreateViewHolder(final ViewGroup parent, final int viewType) {
Log.e("reached2", nn);
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
final Entrys newsBinding = Entrys.inflate(layoutInflater, parent, false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView(newsBinding);
}
#Override
public void onBindViewHolder(useradapter.CustomView holder,int position) {
Log.e("reached3", nn);
// News news = newsList.get(position);
// holder.desc.setText(news.getDesc());
allusermodel newsModel1 = list1.get(position);
// Log.e("list", String.valueOf(list1));
Log.e("nameeeee",newsModel1.getAll_user());
// Log.e("position", String.valueOf(position));
//Log.e("names",newsModel1.getAll_user());
holder.bind(newsModel1);
}
#Override
public int getItemCount() {
return list1.size();
}
public class CustomView extends RecyclerView.ViewHolder {
private Entrys newsBinding;
// public TextView title;
//TextView title, desc;
public CustomView(Entrys newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
Log.e("reached4", nn);
// title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
newsBinding.setRecyclerclick(new Presenters2() {
#Override
public void onclickListener() {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
allusermodel clickedDataItem = list1.get(pos);
Intent intent = new Intent(context, messagelist.class);
intent.putExtra("clickid", clickedDataItem.getId());
context.startActivity(intent);
}
}
});
}
public void bind(allusermodel newsModel1)
{
Log.e("reached5", String.valueOf(newsModel1));
//String j = newsModel1.getAll_user();
// Log.e("bind",nn);
this.newsBinding.setAlluserentry(newsModel1);
}
public Entrys getNewsBinding() {
Log.e("reached6", nn);
return newsBinding;
}
}
}
userlist
public class userlist extends AppCompatActivity {
private static final String TAG = "userlist";
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private useradapter customAdapter;
private DataManager2 dataManger;
private List<allusermodel> newsList;
private RecyclerView.Adapter adapter;
String token2;
String URL1 = "https://chat.promactinfo.com/api/user";
private int userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
token2 = pref.getString("sherdtoken", "");
Log.e("token", token2);
dataManger = new DataManager2(this);
recyclerView = (RecyclerView) findViewById(R.id.recycle);
/*recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
customAdapter = new useradapter(this, newsList);
recyclerView.setAdapter(customAdapter);*/
newsList = new ArrayList<>();
getdata();
}
public void getdata() {
dataManger.sendVolleyRequest1(token2, userlist.this, new DataValue() {
#Override
public void setJsonDataResponse1(JSONArray response) {
allusermodel userModel = new allusermodel();
// newsList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
// Log.e("final", String.valueOf(i));
// userid = jsonObject.getInt("id");
userModel.setId(jsonObject.getInt("id"));
// Log.e("getid", String.valueOf(jsonObject.getInt("id")));
userModel.setAll_user(jsonObject.getString("name"));
// Log.e("getname", String.valueOf(jsonObject.getString("name")));
newsList.add(userModel);
// Log.e("userlist", String.valueOf(newsList));
} catch (JSONException jsonDataResponse) {
Log.e("error", String.valueOf(jsonDataResponse));
}
}
adapter = new useradapter(getApplicationContext(),newsList);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void setVolleyError1(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
}
});
}
}
allusermodel
public class allusermodel extends BaseObservable {
public int id;
public String all_user;
public allusermodel() {
}
public allusermodel(int id,String name ) {
this.id = id;
this.all_user = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAll_user() {
return all_user;
}
public void setAll_user(String all_user) {
this.all_user = all_user;
}
#Override
public String toString() {
return "allusermodel{" +
"id=" + id +
", all_user='" + all_user + '\'' +
'}';
}
}
userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mayurpancholi.chat_mvvm.userlist"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycle"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
innerlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class ="Entrys">
<variable
name="alluserentry"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.allusermodel"/>
<variable
name="recyclerclick"
type="com.example.mayurpancholi.chat_mvvm.interfaces.Presenters2"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:padding="10dp"
android:onClick="#{()->recyclerclick.onclickListener()}"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleval"
android:textSize="20dp"
android:text="#{alluserentry.all_user}"
android:textStyle="bold"
android:layout_marginTop="10dp"
/>
</LinearLayout>
</layout>
whole recyclerview have same data which i previous add in api
(if i enter name in entry then it show previous entry in whole recylerview
ane then if i enter name1 in entry then it show name in whole recylerview )
It seems, the issue is coming because you have created the Model object outside the for loop when you are populating the data from sever. As a result the last value in the list will show to all the RecyclerView items.
Now the solution is that you create the model inside the "for-loop" as a first statement.
public void getdata() {
dataManger.sendVolleyRequest1(token2, userlist.this, new DataValue() {
#Override
public void setJsonDataResponse1(JSONArray response) {
//allusermodel userModel = new allusermodel();
// newsList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
allusermodel userModel = new allusermodel();
try {
JSONObject jsonObject = response.getJSONObject(i);
I hope it will resolve your issue.
I have a recyclerview with some data and I have a searchview, and filter is working just fine. But un-filtering not working. I can't get the whole data in the recyclerview after un-filter. No data is showing. I have to re-open the activity to get data. I tried to used two data sets. But i have no idea where to use them.
My Fragment.
public class YourDealerListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static final String STATE_DEALER_LIST = "state_dealer_list";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VollySingleton vollySingleton;
private RequestQueue requestQueue;
private RecyclerView recyclerView;
private DealerListAdapter dlAdapter;
private HashMap<String, String> hashMap;
private ArrayList<SuggestGetSet> dealerList = new ArrayList<>();
private ArrayList<SuggestGetSet> filteredDealerList = new ArrayList<>();
private String repNo;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private GridMenuFragment mGridMenuFragment;
private Toolbar toolbar;
private ItemSorter itemSorter;
private Button sortButton;
private SearchView searchView;
private ProgressView progressView;
public static List<String> disChannel;
public YourDealerListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment YourDealerListFragment.
*/
// TODO: Rename and change types and number of parameters
public static YourDealerListFragment newInstance(String param1, String param2) {
YourDealerListFragment fragment = new YourDealerListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
vollySingleton = VollySingleton.getsInstance();
requestQueue = vollySingleton.getmRequestQueue();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_your_dealer_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.dealerListRecyclerView);
progressView = (ProgressView) view.findViewById(R.id.pViewew);
itemSorter = new ItemSorter();
dlAdapter = new DealerListAdapter();
disChannel = new ArrayList<String>();
repNo = UserLogIn.getRepNo();
if (savedInstanceState != null) {
dealerList = savedInstanceState.getParcelableArrayList(STATE_DEALER_LIST);
dlAdapter.setDealertList(dealerList);
} else {
getJsonRequest();
}
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.frame_layout);
frameLayout.getBackground().setAlpha(0);
final FloatingActionsMenu fabMenu = (FloatingActionsMenu) view.findViewById(R.id.fab_menu);
final FloatingActionButton fabName = (FloatingActionButton) view.findViewById(R.id.fab_name);
final FloatingActionButton fabCollection = (FloatingActionButton) view.findViewById(R.id.fab_collection);
fabName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSortByName();
fabMenu.collapse();
}
});
fabMenu.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() {
#Override
public void onMenuExpanded() {
frameLayout.getBackground().setAlpha(240);
frameLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fabMenu.collapse();
return true;
}
});
}
#Override
public void onMenuCollapsed() {
frameLayout.getBackground().setAlpha(0);
frameLayout.setOnTouchListener(null);
}
});
searchView = (SearchView) view.findViewById(R.id.dealerNameSearchView);
searchView.setOnQueryTextListener(listener);
//custom context menu
mGridMenuFragment = GridMenuFragment.newInstance(R.drawable.background);
setupGridMenu();
mGridMenuFragment.setOnClickMenuListener(new GridMenuFragment.OnClickMenuListener() {
#Override
public void onClickMenu(GridMenu gridMenu, int position) {
switch (position) {
case 0:
Intent intent = new Intent(getActivity(), SelectItem.class);
getActivity().finish();
startActivity(intent);
getActivity();
break;
}
}
});
//dealers' recycler view item click
recyclerView.addOnItemTouchListener(new NavigationDrawerFragment.RecycleTouchListner(getActivity(), recyclerView, new NavigationDrawerFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
FragmentTransaction tx = getActivity().getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main_frame, mGridMenuFragment);
tx.addToBackStack(null);
tx.commit();
}
}));
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet movie : filteredModelList) {
filteredModelList.add(movie);
}
dlAdapter = new DealerListAdapter(filteredModelList, getActivity());
recyclerView.setAdapter(dlAdapter);
}
//search dealer from search view
SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
final ArrayList<SuggestGetSet> filteredModelList = filter(dealerList, s);
dlAdapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
};
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
//custom context menu data
private void setupGridMenu() {
List<GridMenu> menus = new ArrayList<>();
menus.add(new GridMenu("Order", R.drawable.nnn));
menus.add(new GridMenu("Banking", R.drawable.n));
menus.add(new GridMenu("Credit Note", R.drawable.nn));
menus.add(new GridMenu("Cheques", R.drawable.nnnn));
menus.add(new GridMenu("Invoice Dispatch", R.drawable.nnnnn));
menus.add(new GridMenu("Goods Return", R.drawable.nnnnnn));
mGridMenuFragment.setupMenu(menus);
}
private void getJsonRequest() {
progressView.start();
final SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity().getApplicationContext());
Cursor cr = sqLiteHandler.getData(sqLiteHandler);
cr.moveToFirst();
do {
repNo = cr.getString(0);
} while (cr.moveToNext());
cr.close();
CustomJsonObjectRequest request = new CustomJsonObjectRequest(Request.Method.POST, AppConfig.URL_JSON_DEALER_LIST, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressView.stop();
try {
JSONObject jsonObject = new JSONObject(String.valueOf(response));
if (jsonObject.names().get(0).equals("feed")) {
dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);
JSONArray arrayAchSum = response.getJSONArray("feedd");
for (int i = 0; i < arrayAchSum.length(); i++) {
JSONObject obj3 = arrayAchSum.getJSONObject(i);
String a = obj3.getString("dis_channel");
disChannel.add(a);
}
} else {
Toast.makeText(getActivity(), "No Dealers Available", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*dealerList = parseJsonResponse(response);
dlAdapter.setDealertList(dealerList);*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
hashMap = new HashMap<String, String>();
hashMap.put("repNo", repNo);
return hashMap;
}
};
requestQueue.add(request);
request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
private ArrayList<SuggestGetSet> parseJsonResponse(JSONObject response) {
ArrayList<SuggestGetSet> groupList = new ArrayList<>();
if (response != null || response.length() > 0) {
try {
JSONArray arrayDelaers = response.getJSONArray(KEY_FEED_NAME);
for (int i = 0; i < arrayDelaers.length(); i++) {
JSONObject currentObject = arrayDelaers.getJSONObject(i);
String rep = currentObject.getString(KEY_REP_ID);
String name = currentObject.getString(KEY_REP_NAME);
String dealerId = currentObject.getString(KEY_DEALER_ID);
SuggestGetSet delaers = new SuggestGetSet();
delaers.setId(rep);
delaers.setName(name);
delaers.setDealerId(dealerId);
groupList.add(delaers);
}
//Toast.makeText(getApplicationContext(), productList.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
return groupList;
}
public void onSortByName() {
itemSorter.sortItemByName(dealerList);
dlAdapter.notifyDataSetChanged();
}
public static interface ClickListener {
public void onClick(View view, int position);
//public void onLongClick(View view, int position);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_DEALER_LIST, dealerList);
}
}
My Adapter class.
public class DealerListAdapter extends RecyclerView.Adapter<DealerListAdapter.ViewHolderDealerList> {
private LayoutInflater layoutInflater;
public Context mcontext;
private List<SuggestGetSet> dealerArrayList;
private List<SuggestGetSet> originalDealerArrayList;
Typeface type;
private static String selectedRepId, selectedDealerId, selectedDealerName;
public DealerListAdapter() {
}
public DealerListAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public static String getDealerName() {
return selectedDealerName;
}
public static String getDealerID() {
return selectedDealerId;
}
public static String getRepID() {
return selectedRepId;
}
public DealerListAdapter(ArrayList<SuggestGetSet> dList, Context context) {
this.mcontext = context;
layoutInflater = LayoutInflater.from(context);
dealerArrayList = new ArrayList<>(dList);
originalDealerArrayList = new ArrayList<>(dList);
type = Typeface.createFromAsset(context.getAssets(), "helvr.ttf");
}
public void setDealertList(ArrayList<SuggestGetSet> dealerAList) {
this.dealerArrayList = dealerAList;
originalDealerArrayList = new ArrayList<>(dealerAList);
notifyItemRangeChanged(0, dealerArrayList.size());
}
#Override
public ViewHolderDealerList onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_dealer_list_layout, parent, false);
ViewHolderDealerList viewHolderDealerList = new ViewHolderDealerList(view);
return viewHolderDealerList;
}
#Override
public void onBindViewHolder(ViewHolderDealerList holder, int position) {
final SuggestGetSet model = dealerArrayList.get(position);
holder.bind(model);
final int pos = position;
holder.dealerName.setText(dealerArrayList.get(position).getName());
holder.dealerName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDealerId = dealerArrayList.get(pos).getDealerId();
selectedRepId = dealerArrayList.get(pos).getId();
selectedDealerName = dealerArrayList.get(pos).getName();
Toast.makeText(layoutInflater.getContext(), dealerArrayList.get(pos).getName() + " / " + dealerArrayList.get(pos).getDealerId() + " / " + dealerArrayList.get(pos).getId(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return dealerArrayList.size();
}
public void setModels(ArrayList<SuggestGetSet> models) {
dealerArrayList = new ArrayList<>(models);
}
static class ViewHolderDealerList extends RecyclerView.ViewHolder {
private TextView dealerName, dealerId;
public ViewHolderDealerList(View itemView) {
super(itemView);
dealerName = (TextView) itemView.findViewById(R.id.yourDelaerName);
//dealerId = (TextView) itemView.findViewById(R.id.txtDelaerCollection);
}
public void bind(SuggestGetSet model) {
dealerName.setText(model.getName());
}
}
//search animations
public SuggestGetSet removeItem(int position) {
final SuggestGetSet model = dealerArrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, SuggestGetSet model) {
dealerArrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final SuggestGetSet model = dealerArrayList.remove(fromPosition);
dealerArrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(ArrayList<SuggestGetSet> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateMovedItems(ArrayList<SuggestGetSet> models) {
for (int toPosition = dealerArrayList.size() - 1; toPosition >= 0; toPosition--) {
final SuggestGetSet model = dealerArrayList.get(toPosition);
final int fromPosition = models.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateAdditions(ArrayList<SuggestGetSet> models) {
for (int i = 0, count = dealerArrayList.size(); i < count; i++) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
addItem(i, model);
}
}
notifyDataSetChanged();
}
private void applyAndAnimateRemovals(ArrayList<SuggestGetSet> models) {
for (int i = dealerArrayList.size() - 1; i >= 0; i--) {
final SuggestGetSet model = dealerArrayList.get(i);
if (!models.contains(model)) {
removeItem(i);
}
}
notifyDataSetChanged();
}
}
Just Modify your function and Add check for null or "" .
it will work fine
private ArrayList<SuggestGetSet> filter(ArrayList<SuggestGetSet> models, String query) {
if(TextUtils.isEmpty(query)){
return models;
}
query = query.toLowerCase();
final ArrayList<SuggestGetSet> filteredModelList = new ArrayList<>();
for (SuggestGetSet model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
I have used this solution to filter my RecyclerView. Using the solution I was able to get the result while typing. But when I clear the search widget I don't get the full list instead I get the empty RecyclerView.
This is how my result looks like.
https://imgur.com/nwyetEd
This is my Adapter
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
private LayoutInflater inflater;
private ContactViewHolder viewHolder;
private ArrayList<Contact> contactsList = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
boolean fromMyContacts;
Context context;
public ContactsAdapter(Context context, boolean fromMyContacts){
inflater = LayoutInflater.from(context);
this.context = context;
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
this.fromMyContacts = fromMyContacts;
}
public void setContactsList(ArrayList<Contact> contactsList){
this.contactsList = contactsList;
notifyItemRangeChanged(0, contactsList.size());
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.contact_list, parent, false);
viewHolder = new ContactViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact current = contactsList.get(position);
viewHolder.name.setText(current.name);
viewHolder.phone.setText(current.phone);
viewHolder.city.setText(current.location + ", " + current.city);
if(fromMyContacts) {
if (current.verified) {
viewHolder.verified.setImageResource(R.drawable.ic_check_circle);
} else {
viewHolder.verified.setImageResource(R.drawable.ic_cancel);
}
}
String image_url = current.image_url;
if(!image_url.equals("null")){
Picasso.with(context).load(image_url).into(viewHolder.contactIcon);
}else{
viewHolder.contactIcon.setImageResource(R.drawable.contact_icon);
}
}
#Override
public int getItemCount() {
return contactsList.size();
}
public Contact removeItem(int position){
final Contact contacts = contactsList.remove(position);
notifyItemRemoved(position);
return contacts;
}
public void addItem(int position, Contact contactList){
contactsList.add(position, contactList);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition){
final Contact contacts = contactsList.remove(fromPosition);
contactsList.add(toPosition, contacts);
notifyItemMoved(fromPosition, toPosition);
}
public void animateTo(List<Contact> contacts){
applyAndAnimateRemovals(contacts);
applyAndAnimateAdditions(contacts);
applyAndAnimateMovedItems(contacts);
}
private void applyAndAnimateRemovals(List<Contact> newModels) {
for (int i = contactsList.size() - 1; i >= 0; i--) {
final Contact model = contactsList.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Contact> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final Contact model = newModels.get(i);
if (!contactsList.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<Contact> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final Contact model = newModels.get(toPosition);
final int fromPosition = contactsList.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
}
And this is my Model
public class Contact {
String name;
String phone;
String city;
String location;
Boolean verified;
String image_url;
public Contact(String name, String phone, String city, String location, Boolean verified, String image_url){
this.name = name;
this.phone = phone;
this.city = city;
this.location = location;
this.verified = verified;
this.image_url = image_url;
}
}
This is the Activity where I use my filter
public class MyContactsActivity extends AppCompatActivity implements View.OnClickListener, SearchView.OnQueryTextListener {
private RecyclerView recyclerView;
private ContactsAdapter adapter;
private NetworkChecker networkChecker;
private SessionManager sessionManager;
private AppConfig appConfig;
private RelativeLayout loading, retry;
private Button tryAgain;
AlertHelper alertHelper;
final ArrayList<Contact> contactArrayList = new ArrayList<>();
String url;
DebugHelper debugHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
debugHelper = new DebugHelper();
loading = (RelativeLayout) findViewById(R.id.loadingPanel);
retry = (RelativeLayout) findViewById(R.id.retry);
tryAgain = (Button) findViewById(R.id.tryAgainButton);
tryAgain.setOnClickListener(this);
alertHelper = new AlertHelper(this);
networkChecker = new NetworkChecker(this);
sessionManager = new SessionManager(this);
appConfig = new AppConfig();
String phone = sessionManager.getLoggedInUserPhone();
url = appConfig.getApiUrlForSpecificContacts(phone);
recyclerView = (RecyclerView) findViewById(R.id.contactsView);
adapter = new ContactsAdapter(getApplicationContext(), true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
sendJsonRequest(url);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView phone = (TextView) view.findViewById(R.id.contact_phone);
TextView name = (TextView) view.findViewById(R.id.contact_name);
Intent i = new Intent(getApplicationContext(), ContactProfileActivity.class);
i.putExtra("selected_user_phone", phone.getText());
i.putExtra("selected_user_name", name.getText());
startActivity(i);
}
})
);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddContactActivity.class));
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void sendJsonRequest(String url) {
if (networkChecker.networkAvailable()) {
loading.setVisibility(View.VISIBLE);
RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("contact_info");
if(jsonArray != null){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentContact = jsonArray.getJSONObject(i);
String name = currentContact.getString("name");
String phone = currentContact.getString("phone");
String city = currentContact.getString("city");
String address = currentContact.getString("address");
Boolean verified = currentContact.getBoolean("verified");
String image_url = currentContact.getString("image_url");
Contact contact = new Contact(name, phone, city, address, verified, image_url);
contactArrayList.add(contact);
}
adapter.setContactsList(contactArrayList);
}
else{
alertHelper.displayDialog("No Contacts Found.");
}
}catch (Exception e){
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
alertHelper.displayDialog(getString(R.string.connection_failed));
} else {
alertHelper.displayDialog(getString(R.string.action_failed_try_again));
}
}
});
requestQueue.add(stringRequest);
} else {
retry.setVisibility(View.VISIBLE);
tryAgain.setClickable(true);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list_menu, menu);
debugHelper.L("Search Click Vayo");
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tryAgainButton:
sendJsonRequest(url);
break;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<Contact> filteredModelList = filter(contactArrayList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactArrayList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
Can anyone help me please?
assuming contactsList is var with the full contacts
private List<Contact> filter(List<Contact> models, String query) {
query = query.toLowerCase();
if(query.equals("")) { return contactsList; }
final List<Contact> filteredModelList = new ArrayList<>();
for (Contact model : models) {
final String text = model.name.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
He has defined in this way:
public void setModels(List<ExampleModel> models) {
mModels = new ArrayList<>(models);
}
Initialize like the way he has done.
Your soultion would be:
this.contactsList = new ArrayList<>(contactsList);
You need to move your filter() method from your Activity to your Adapter. At your Adapter add one additional variable to hold a copy of unfiltered dataset. In your case, you need contactsList and copyOfContactsList variables.
Change your Adapter's constructor as follows:
public class ContactsAdapter extends RecyclerView.Adapter<ContactViewHolder> {
....
private ArrayList<Contact> contactsList = new ArrayList<>();
private ArrayList<Contact> copyOfContactsList = new ArrayList<>();
....
public ContactsAdapter(Context context, ArrayList<Contact> dataSet, boolean fromMyContacts){
...
this.contactsList = dataSet;
copyOfContactsList.addAll(dataSet);
...
}
and this is the filter method to be added to your Adapter:
public void filter(String text) {
if(text.isEmpty()){
contactsList.clear();
contactsList.addAll(copyOfContactsList);
} else{
ArrayList<Contact> result = new ArrayList<>();
text = text.toLowerCase();
for(Contact item: copyOfContactsList){
if(item.getName().toLowerCase().contains(text)){
result.add(item);
}
}
contactsList.clear();
contactsList.addAll(result);
}
notifyDataSetChanged();
}
http://i.stack.imgur.com/HZ3v6.png
this is the picture of the recycler view
i dont understand what might be causing this problem. so please guys can you give a probablity of what might be the reason.
Thanks in Advance.
public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ProductViewHolder> {
//implements Filterable {
private final LayoutInflater inflator;
private final List<ProductInfo> products;
private Context context;
private ProductAdapterListener listener;
ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
//private List<ProductInfo> BackupProducts= Collections.emptyList();
ProductInfo current;
public ProductAdaptor(Context context, List<ProductInfo> data, ProductAdapterListener listener) {
inflator = LayoutInflater.from(context);
products = data;
this.context = context;
this.listener = listener;
//BackupProducts=data;
}
#Override
public ProductAdaptor.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.custom_product, parent, false);
ProductViewHolder holder = new ProductViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductAdaptor.ProductViewHolder holder, final int position) {
current = products.get(position);
holder.title.setText(current.getName());
holder.icon.setImageUrl(current.getImage(), imageLoader);
holder.price.setText("Price: Rs. " + current.getPrice());
holder.description.setText(current.getDescription());
holder.add_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
products.get(position).setQuantity(Integer.parseInt(holder.etQuantity.getText().toString()));
listener.onAddToCartPressed(products.get(position));
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Reading Position", "" + current.getId());
Intent base = new Intent(context, Products.class);
base.putExtra("product_id", Integer.parseInt(products.get(position).getId()));
base.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(base);
}
});
}
public void setData(List<ProductInfo> list) {
products.clear();
products.addAll(list);
notifyDataSetChanged();
}
/*
public void flushFilter(){
products.clear();
products.addAll(BackupProducts);
notifyDataSetChanged();
}*/
public void animateTo(List<ProductInfo> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ProductInfo> newModels) {
for (int i = products.size() - 1; i >= 0; i--) {
final ProductInfo model = products.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ProductInfo> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ProductInfo model = newModels.get(i);
if (!products.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ProductInfo> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ProductInfo model = newModels.get(toPosition);
final int fromPosition = products.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ProductInfo removeItem(int position) {
final ProductInfo model = products.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ProductInfo model) {
products.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ProductInfo model = products.remove(fromPosition);
products.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public int getItemCount() {
return products.size();
}
/*
#Override
public Filter getFilter() {
//flushFilter();
return new CardFilter(this,BackupProducts);
}
*/
public interface ProductAdapterListener {
void onAddToCartPressed(ProductInfo product);
}
static class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
NetworkImageView icon;
TextView price;
TextView description;
LinearLayout add_Cart;
TextView etQuantity;
public ProductViewHolder(final View itemView) {
super(itemView);
icon = (NetworkImageView) itemView.findViewById(R.id.productImage);
title = (TextView) itemView.findViewById(R.id.productName);
price = (TextView) itemView.findViewById(R.id.productPrice);
description = (TextView) itemView.findViewById(R.id.productDescription);
add_Cart = (LinearLayout) itemView.findViewById(R.id.add_cart);
etQuantity = (TextView) itemView.findViewById(R.id.quanity);
}
#Override
public void onClick(View v) {
}
}
/*
//FILTER THE SEARCH RESULTS
private static class CardFilter extends Filter {
private final ProductAdaptor adapter;
private final List<ProductInfo> originalList;
private final List<ProductInfo> filteredList;
private CardFilter(ProductAdaptor adapter, List<ProductInfo> originalList) {
super();
this.adapter = adapter;
this.originalList = new LinkedList<ProductInfo>(originalList);
this.filteredList = new ArrayList<ProductInfo>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final ProductInfo productInfo : originalList) {
if (productInfo.getName().toLowerCase().trim().contains(filterPattern)) {
filteredList.add(productInfo);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.setData((ArrayList<ProductInfo>) results.values);
adapter.notifyDataSetChanged();
}
}
*/
}
Product Fragment
public class ProductFragment extends Fragment implements SearchView.OnQueryTextListener,ProductAdaptor.ProductAdapterListener {
private static final String TAG = ProductFragment.class.getSimpleName();
private ProductAdaptor adapter;
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
// To store all the products
private List<ProductInfo> productsList=new ArrayList<>();
ProductAdaptor.ProductAdapterListener listener;
//Progress dialog
private ProgressDialog pDialog;
public static ProductFragment newInstance() {
return new ProductFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
listener=this;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.product_fragment,container,false);
recyclerView= (RecyclerView) layout.findViewById(R.id.productList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog.setMessage("Fetching products...");
showpDialog();
volleySingleton=VolleySingleton.getInstance();
requestQueue=volleySingleton.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, AppConfig.URL_PRODUCTS, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//hide the progress dialog
hidepDialog();
adapter=new ProductAdaptor(getActivity(),parseJSONOResponse(response),listener);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(MyApplication.getAppContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Wait 20 seconds and don't retry more than once
requestQueue.add(jsObjRequest);
recyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
/*
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main,menu);
final MenuItem item = menu.findItem(R.id.search);
final SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
*/
public boolean PerformSearch(String searchString){
//adapter.getFilter().filter(searchString);
return true;
}
public void setDataSet(List<ProductInfo> newDataSet){
adapter=new ProductAdaptor(MyApplication.getAppContext(),newDataSet,this);
recyclerView.swapAdapter(adapter, false);
//new way of filtering data
}
private List<ProductInfo> parseJSONOResponse(JSONObject response){
try {
JSONArray products = response.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("product_id");
String name = product.getString("name");
String description = product
.getString("description");
String image = AppConfig.URL_IMAGE_PRODUCTS + product.getString("image");
BigDecimal price = new BigDecimal(product
.getString("price"));
ProductInfo p = new ProductInfo(id, name, description,
image, price);
productsList.add(p);
}
return productsList;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
return productsList;
}
#Override
public void onAddToCartPressed(ProductInfo product) {
CartHandler cartHandler=new CartHandler(MyApplication.getAppContext());
Log.d("Insert: ", "Inserting ..");
if (cartHandler.getProductsInCartCount()==0) {
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
else{
ProductInfo temp=cartHandler.getProductInCart(Integer.parseInt(product.getId()));
if (temp!=null){
cartHandler.updateProduct(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}else
{
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final List<ProductInfo> filteredModelList = filter(productsList, query);
adapter.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
return true;
}
private List<ProductInfo> filter(List<ProductInfo> models, String query) {
query = query.toLowerCase();
final List<ProductInfo> filteredModelList = new ArrayList<>();
for (ProductInfo model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
This problem is caused because of overlapping fragments and i was starting the fragment like this
fragment=ProductFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.productFragment,fragment )
.commit();
so making it simply
fragment=ProductFragment.newInstance();
solved my problem.
Thanks guys for help #MohammadAllam
Here is the image
Please ask me more for more information
public class ProductFragment extends Fragment implements SearchView.OnQueryTextListener,ProductAdaptor.ProductAdapterListener {
private static final String TAG = ProductFragment.class.getSimpleName();
/** The default socket timeout in milliseconds */
public static final int DEFAULT_TIMEOUT_MS = 2500;
/** The default number of retries */
public static final int DEFAULT_MAX_RETRIES = 1;
/** The default backoff multiplier */
public static final float DEFAULT_BACKOFF_MULT = 1f;
private ProductAdaptor adapter;
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private VolleySingleton volleySingleton;
// To store all the products
private static List<ProductInfo> productsList=new ArrayList<>();
ProductAdaptor.ProductAdapterListener listener;
//Progress dialog
private ProgressDialog pDialog;
public static ProductFragment newInstance() {
return new ProductFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
listener=this;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.product_fragment,container,false);
recyclerView= (RecyclerView) layout.findViewById(R.id.productList);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
pDialog.setMessage("Fetching products...");
showpDialog();
volleySingleton=VolleySingleton.getInstance();
requestQueue=volleySingleton.getRequestQueue();
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, AppConfig.URL_PRODUCTS, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//hide the progress dialog
hidepDialog();
adapter=new ProductAdaptor(getActivity(),parseJSONOResponse(response),listener);
recyclerView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(MyApplication.getAppContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Wait 20 seconds and don't retry more than once
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
DEFAULT_TIMEOUT_MS,
DEFAULT_MAX_RETRIES,
DEFAULT_BACKOFF_MULT));
requestQueue.add(jsObjRequest);
return layout;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
}
public boolean PerformSearch(String searchString){
//adapter.getFilter().filter(searchString);
return true;
}
public void setDataSet(List<ProductInfo> newDataSet){
productsList = newDataSet;
adapter=new ProductAdaptor(MyApplication.getAppContext(),productsList,this);
recyclerView.swapAdapter(adapter, false);
//new way of filtering data
}
private List<ProductInfo> parseJSONOResponse(JSONObject response){
try {
JSONArray products = response.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject product = (JSONObject) products
.get(i);
String id = product.getString("product_id");
String name = product.getString("name");
String description = product
.getString("description");
String image = AppConfig.URL_IMAGE_PRODUCTS + product.getString("image");
BigDecimal price = new BigDecimal(product
.getString("price"));
ProductInfo p = new ProductInfo(id, name, description,
image, price);
productsList.add(p);
}
return productsList;
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
return productsList;
}
#Override
public void onAddToCartPressed(ProductInfo product) {
CartHandler cartHandler=new CartHandler(MyApplication.getAppContext());
if (cartHandler.getProductsInCartCount()==0) {
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
else{
ProductInfo temp=cartHandler.getProductInCart(Integer.parseInt(product.getId()));
if (temp!=null){
cartHandler.updateProduct(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}else
{
cartHandler.addProductInCart(product);
Toast.makeText(MyApplication.getAppContext(),
product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
}
}
}
private void showpDialog() {
if (!pDialog.isShowing()){
pDialog.show();
}
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// final List<ProductInfo> filteredModelList = filter(productsList, query);
// adapter.animateTo(filteredModelList);
//recyclerView.scrollToPosition(0);
return true;
}
private List<ProductInfo> filter(List<ProductInfo> models, String query) {
query = query.toLowerCase();
final List<ProductInfo> filteredModelList = new ArrayList<>();
for (ProductInfo model : models) {
final String text = model.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
}
Product adaptor
public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ProductViewHolder>{
//implements Filterable {
private final LayoutInflater inflator;
private final List<ProductInfo> products;
private Context context;
private ProductAdapterListener listener;
ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
//private List<ProductInfo> BackupProducts= Collections.emptyList();
ProductInfo current;
public ProductAdaptor(Context context, List<ProductInfo> data, ProductAdapterListener listener){
inflator= LayoutInflater.from(context);
products=data;
this.context=context;
this.listener=listener;
//BackupProducts=data;
}
#Override
public ProductAdaptor.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.custom_product, parent, false);
ProductViewHolder holder=new ProductViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ProductAdaptor.ProductViewHolder holder, final int position) {
current=products.get(position);
holder.title.setText(current.getName());
holder.icon.setImageUrl(current.getImage(), imageLoader);
holder.price.setText("Price: Rs. " + current.getPrice());
holder.description.setText(current.getDescription());
holder.add_Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
products.get(position).setQuantity(Integer.parseInt(holder.etQuantity.getText().toString()));
listener.onAddToCartPressed(products.get(position));
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Reading Position", "" + current.getId());
Intent base=new Intent(context, Products.class);
base.putExtra("product_id", Integer.parseInt(products.get(position).getId()));
base.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(base);
}
});
}
public void setData(List<ProductInfo> list){
products.clear();
products.addAll(list);
notifyDataSetChanged();
}
/*
public void flushFilter(){
products.clear();
products.addAll(BackupProducts);
notifyDataSetChanged();
}*/
public void animateTo(List<ProductInfo> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(List<ProductInfo> newModels) {
for (int i = products.size() - 1; i >= 0; i--) {
final ProductInfo model = products.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<ProductInfo> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final ProductInfo model = newModels.get(i);
if (!products.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(List<ProductInfo> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final ProductInfo model = newModels.get(toPosition);
final int fromPosition = products.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public ProductInfo removeItem(int position) {
final ProductInfo model = products.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, ProductInfo model) {
products.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final ProductInfo model = products.remove(fromPosition);
products.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
#Override
public int getItemCount() {
return products.size();
}
/*
#Override
public Filter getFilter() {
//flushFilter();
return new CardFilter(this,BackupProducts);
}
*/
public interface ProductAdapterListener {
void onAddToCartPressed(ProductInfo product);
}
class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView title;
NetworkImageView icon;
TextView price;
TextView description;
LinearLayout add_Cart;
TextView etQuantity;
public ProductViewHolder(final View itemView) {
super(itemView);
icon =(NetworkImageView) itemView.findViewById(R.id.productImage);
title = (TextView) itemView.findViewById(R.id.productName);
price= (TextView) itemView.findViewById(R.id.productPrice);
description=(TextView) itemView.findViewById(R.id.productDescription);
add_Cart= (LinearLayout) itemView.findViewById(R.id.add_cart);
etQuantity= (TextView) itemView.findViewById(R.id.quanity);
}
#Override
public void onClick(View v) {
}
}
These are both of the classes for this Product list please if you need more information please comment
Thanks in advance
There are two classes and those take products from my json and assign it to view holder
This problem is caused because of overlapping fragments and i was starting the fragment like this
fragment=ProductFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.productFragment,fragment )
.commit();
so making it simply
fragment=ProductFragment.newInstance();
solved my problem.
Thanks guys for help #MohammadAllam
I have this issue too after many search i fixed it whit update gradle dependencies i think its happened because one of old android dependencies.