android recycler view two list are showing above each other - android

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

Related

Android List View Custom Adapter with Checkbox multiple selection and Search Listview

I Have implemented the ListView with Custom Adopter class and Multiple check box selection . Its working fine . After that I have given search the name in ListView. If I checked row item then I search the name in search , Search positioned was changed . Kindly help me to fix this.
Model Class
public class FullUser {
String name=null;
String id=null;
boolean checked;
public FullUser(String name, String id,boolean checked){
this.name=name;
this.id = id;
this.checked = checked;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
public Boolean getChecked(){
return this.checked;
}
public void setChecked(Boolean checked){
this.checked = checked;
}
#Override
public String toString() {
return this.name;
}
}
Adapter Class
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
}
#Override
public int getCount() {
return fullUsers.size();
}
#Override
public FullUser getItem(int position) {
return fullUsers.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new SubjectFilter();
}
return filter;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("UserConvertView", String.valueOf(position));
View row;
if (convertView == null) {
row = LayoutInflater.from(getContext()).inflate(R.layout.list_row_with_checkbox, parent, false);
}else{
row = convertView;
}
holder = new ViewHolder();
holder.name_view = (TextView) row.findViewById(R.id.nameText);
holder.firstchar_view = (TextView) row.findViewById(R.id.first_char);
holder.groupid = (TextView) row.findViewById(R.id.rowid);
holder.checkBox =(CheckBox) row.findViewById(R.id.cbBox);
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
//holder.checkBox.setChecked(checkedHolder[position]);
String communityname_text = group.getName();
holder.name_view.setText(group.getName());
String firstchar = communityname_text.substring(0, 1);
holder.firstchar_view.setText(firstchar);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true)
group.setChecked(true);
else
group.setChecked(false);
}
});
row.setTag(holder);
return row;
}
private class SubjectFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
constraint = constraint.toString().toLowerCase();
ArrayList<FullUser> filteredItems = new ArrayList<FullUser>();
for(int i = 0, l = fullUsers.size(); i < l; i++)
{
FullUser group = fullUsers.get(i);
if(group.toString().toLowerCase().contains(constraint)) {
FullUser grouplistss = new FullUser(group.getName(),group.id,group.getChecked());
filteredItems.add(grouplistss);
}
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,Filter.FilterResults results) {
if(results.count > 0) {
fullUsers = (ArrayList<FullUser>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = fullUsers.size(); i < l; i++)
add(fullUsers.get(i));
} else {
notifyDataSetInvalidated();
}
}
}
private class ViewHolder {
TextView name_view;
TextView firstchar_view;
TextView groupid;
CheckBox checkBox;
}
}
Thanks in advance.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
group.setChecked(true);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(true);
}else{
group.setChecked(false);
int pos = originalList.indexOf(group)
originalList.get(pos).setChecked(true);
fullUsers.get(position).setChecked(false);
}
}
update your adapter use SparseBooleanArray
public class FullUserAdapter extends ArrayAdapter<FullUser> {
private ArrayList<FullUser> originalList;
private ArrayList<FullUser> fullUsers;
private SubjectFilter filter;
SparseBooleanArray booleanArray ;
public FullUserAdapter(Context context, int resource, ArrayList<FullUser> fullUsers) {
super(context, resource, fullUsers);
this.fullUsers = new ArrayList<FullUser>();
this.fullUsers.addAll(fullUsers);
this.originalList = new ArrayList<FullUser>();
this.originalList.addAll(fullUsers);
booleanArray = new SparseBooleanArray();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
.
.
.
final FullUser group =getItem(position);
holder.groupid.setText(group.getId());
holder.checkBox.setOnCheckedChangeListener(null);
holder.checkBox.setChecked(booleanArray.get(group.getId().hashCode(),false));
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
booleanArray.put(group.getId().hashCode(), isChecked);
}
});
.
.
.
return row;
}
public ArrayList<FullUser> getSelectedItems() {
ArrayList<FullUser> list = new ArrayList<>();
for(FullUser group:fullUsers){
if(booleanArray.get(group.getId().hashCode(), false)){
list.add(group);
}
}
return list;
};
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".dashboard.VoterListActivity">
<ProgressBar
android:id="#+id/reqprogressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
<ListView
android:id="#+id/voter_lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_show_me"
android:divider="#null"/>
<Button
android:id="#+id/btn_show_me"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:background="#drawable/n_btn"
android:text="#string/add_family_numbers"
android:visibility="gone"
android:textColor="#ffffff"
android:textSize="20sp" />
</RelativeLayout>
Java Code
public Class Actvity extends AppCompatActivity {
ProgressBar progressBar;
ListView listView;
VoterDao voterDao;
String Token, Userid, Appid, Deviceid;
MenuItem searchview;
VoterListAdapter adapter;
String pid;
VoterDatum friend;
String value;
CheckBox mCheckBox;
Button btn_show_me;
ArrayList<VoterDatum> friends;
ListView1Adapter adapter1;
VoterDatum Model;
StringBuilder stringBuilder;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.voter_list);
stringBuilder = new StringBuilder();
Token = Util.getStringFromSP(this, "token");
Userid = Util.getStringFromSP(this, "user_id");
Appid = Util.getStringFromSP(this, "app_id");
Deviceid = Util.getStringFromSP(this, "device_id");
initViews();
getVoterData();
btn_show_me.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = 0;
if (friends.size() == i) { //do nothing
}
while (friends.size() > i) {
int count = friends.size();
Model = friends.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + friends.get(i).getCitizenId());
stringBuilder.append("," + friends.get(i).getCitizenId());
name = stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name = name.substring(1);
Log.d("fs", name);
sendToServer();
}
i++; // rise i
}
}
});
}
private void sendToServer() {
Intent intent = new Intent(VoterListActivity.this, AddFamilyNuberByVoterList.class);
intent.putParcelableArrayListExtra("CheckedList", friends);
startActivity(intent);
finish();
}
private void getVoterData() {
if (Util.isNetworkAvailable(this)) {
progressBar.setVisibility(View.VISIBLE);
SendRequestToServer();
} else {
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_connection, Snackbar.LENGTH_SHORT).show();
return;
}
}
private void SendRequestToServer() {
try {
RegistrationApi api = ServiceGenerator.createService(RegistrationApi.class);
retrofit2.Call<VoterDao> call = api.togetVoters(Userid, Token, Appid, Deviceid);
call.enqueue(new Callback<VoterDao>() {
#Override
public void onResponse(Call<VoterDao> call, Response<VoterDao> response) {
if (response.isSuccessful()) {
voterDao = response.body();
if (voterDao.getAddData().getStatus().equals(1)) {
searchview.setVisible(true);
progressBar.setVisibility(View.GONE);
friends = (ArrayList<VoterDatum>) voterDao.getAddData().getData();
adapter1 = new ListView1Adapter(getApplicationContext(), R.layout.list_voter, friends);
listView.setAdapter(adapter1);
btn_show_me.setVisibility(View.VISIBLE);
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found, Snackbar.LENGTH_SHORT).show();
}
} else {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, R.string.no_data_found + response.message(), Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<VoterDao> call, Throwable t) {
try {
searchview.setVisible(false);
progressBar.setVisibility(View.GONE);
Snackbar.make(listView, "" + t.getMessage(), Snackbar.LENGTH_SHORT).show();
Log.d("message", "" + t.getMessage());
System.out.println("onFAilureExecute" + t.getMessage());
if (t != null)
t.printStackTrace();
} catch (Throwable th) {
th.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void initViews() {
progressBar = findViewById(R.id.reqprogressbar);
listView = findViewById(R.id.voter_lv);
btn_show_me = findViewById(R.id.btn_show_me);
}
#Override
public boolean onSupportNavigateUp() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(), DashboardActivity.class));
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
searchview = menu.findItem(R.id.action_search);
final SearchView searchViewAndroidActionBar = (SearchView) MenuItemCompat.getActionView(searchview);
searchViewAndroidActionBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter1.getFilter().filter(newText);
return false;
}
});
View closeButton = searchViewAndroidActionBar.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click
searchViewAndroidActionBar.setIconified(true);
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocalHelper.onAttach(base));
}
private class ListView1Adapter extends BaseAdapter {
ListView1Adapter.ViewHolder holder;
private Context activity;
private ArrayList<VoterDatum> Friends;
private ArrayList<VoterDatum> mList;
private final String TAG = ListViewAdapter.class.getSimpleName();
boolean[] checkedItems;
public ListView1Adapter(Context applicationContext, int list_voter, ArrayList<VoterDatum> list) {
this.activity = applicationContext;
this.Friends = list;
this.mList = list;
Log.i(TAG, "init adapter");
checkedItems = new boolean[mList.size()];
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
final int pos = position;
// inflate layout from xml
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_voter, parent, false);
// get all UI view
holder = new ListView1Adapter.ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ListView1Adapter.ViewHolder) convertView.getTag();
}
friend = mList.get(position);
String nameS = friend.getFirstname() + " " + friend.getLastname();
String namesS = friend.getVoterId();
String lname = friend.getLfname() + " " + friend.getLlastname();
//set Friend data to views
String Photo = friend.getPhoto();
if (Photo.isEmpty() || Photo == null) {
holder.image.setImageResource(R.mipmap.ic_launcher);
} else {
Picasso.with(activity).load(Photo).transform(new CircleTransform()).into(holder.image);
}
holder.name.setText(nameS);
holder.lanname.setText(lname);
holder.voterid_tv.setText(namesS);
holder.check.setChecked(friend.isChecked());
holder.check.setTag(friend);
holder.check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
VoterDatum itemobj = (VoterDatum) cb.getTag();
if (mList.get(Integer.valueOf(pos)).isChecked()) {
cb.setSelected(false);
mList.get(Integer.valueOf(pos)).setIsChecked(false);
notifyDataSetChanged();
} else {
cb.setSelected(true);
mList.get(Integer.valueOf(pos)).setIsChecked(true);
notifyDataSetChanged();
}
}
});
return convertView;
}
private class ViewHolder {
private ImageView image;
private TextView name, lanname, voterid_tv;
private CheckBox check;
public ViewHolder(View v) {
image = v.findViewById(R.id.profile_iv);
name = (TextView) v.findViewById(R.id.name_tv);
lanname = (TextView) v.findViewById(R.id.desig_tv);
voterid_tv = (TextView) v.findViewById(R.id.voterid_tv);
check = (CheckBox) v.findViewById(R.id.chkEnable);
}
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<VoterDatum> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = Friends;
} else {
filteredResults = (ArrayList<VoterDatum>) getFilteredResults(constraint.toString().toLowerCase());
}
results.values = filteredResults;
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
mList = (ArrayList<VoterDatum>) results.values;
notifyDataSetChanged();
}
};
}
protected List<VoterDatum> getFilteredResults(String s) {
ArrayList<VoterDatum> results = new ArrayList<>();
for (VoterDatum item : Friends) {
String TotalSearch = item.getFirstname() + " " + item.getLastname();
if (TotalSearch.toLowerCase().contains(s) || item.getVoterId().toLowerCase().contains(s)) {
results.add(item);
}
}
return results;
}
public ArrayList<VoterDatum> getAllData() {
return mList;
}
}
}
Model Class
public class VoterDatum implements Parcelable {
#SerializedName("citizen_id")
#Expose
private String citizenId;
private boolean isChecked;
public static final Parcelable.Creator<VoterDatum> CREATOR = new Parcelable.Creator<VoterDatum>() {
public VoterDatum createFromParcel(Parcel in) {
return new VoterDatum(in);
}
public VoterDatum[] newArray(int size) {
return new VoterDatum[size];
}
};
public VoterDatum(Parcel in) {
this.citizenId = in.readString();
this.isChecked = in.readByte() != 0;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.citizenId);
dest.writeByte((byte) (this.isChecked ? 1 : 0));
}
public VoterDatum(String citizenId, boolean gender) {
this.citizenId = citizenId;
this.isChecked = false; // not selected when create
}
#SerializedName("status")
#Expose
private String status;
#SerializedName("firstname")
#Expose
private String firstname;
#SerializedName("lastname")
public boolean isChecked() {
return isChecked;
}
public void setIsChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCitizenId() {
return citizenId;
}
public void setCitizenId(String citizenId) {
this.citizenId = citizenId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getLfname() {
return lfname;
}
public void setLfname(String lfname) {
this.lfname = lfname;
}
}
Get Data From Other Class
public class ACtivity extends AppCompatActivity implements View.OnClickListener {
String Mvoterid;
GPSTracker gps;
String Token, Userid, Deviceid, Appid, Language;
Button submit_btn;
ProgressBar progressBar;
AddFamilynumberbyvoterDao addFamilynumberbyvoterDao;
// ArrayList<VoterDatum> checkedList;
List<VoterDatum> checkedList;
LinearLayout container;
VoterDatum Model;
ListView list_item;
String join;
int position;
String userName;
String name;
StringBuilder stringBuilder;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_family_nuber_by_voter_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.add_family_numbers);
VoterID = getIntent().getStringExtra("voterIDs");
stringBuilder= new StringBuilder();
checkedList = new ArrayList<VoterDatum>(); // initializing list
container = (LinearLayout) findViewById(R.id.layout);
getLocation();
initViews();
initListeners();
getDataFromIntent();
generateDataToContainerLayout();
}
#RequiresApi(api = Build.VERSION_CODES.O)
#SuppressLint("InflateParams")
private void generateDataToContainerLayout() {
int i = 0;
if (checkedList.size() == i) { //do nothing
}
while (checkedList.size() > i) {
int count = checkedList.size();
Model = checkedList.get(i);
if (Model.isChecked()) {
Log.i("ListActivity", "here" + checkedList.get(i).getCitizenId());
stringBuilder.append(","+checkedList.get(i).getCitizenId());
name=stringBuilder.toString();
String joinedString = Model.getCitizenId().toString();
Log.d("ls", "" + name);
name=name.substring(1);
Log.d("fs",name);
}
i++; // rise i
}
}
private void getDataFromIntent() {
checkedList = getIntent().getParcelableArrayListExtra("CheckedList");
}

Un-filtering the result is not working in Recyclerview

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;
}

RecyclerView filter not working

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();
}

SearchView and Recyclerview, showing right cards, but at the same time others are removed permanently

I'm trying to implement searchview. It works somehow, but the problem is that after you start typing it is one-way street. You get the info but if you delete text, you won't get the result as it was in the beginning. I'm working with cardviews.
Marker is a model(gettitle etc.)
My Adapter:
public class AdapterRestavracije extends
RecyclerView.Adapter<AdapterRestavracije.ViewHolderRestavracije> {
ArrayList<Marker> arrayList;
private LayoutInflater layoutInflater;
private VolleySingleton mVolleySingleton;
Context context;
public AdapterRestavracije(Context context, ArrayList<Marker> models) {
layoutInflater = LayoutInflater.from(context);
this.context = context;
mVolleySingleton = VolleySingleton.getsIstance();
arrayList = new ArrayList<Marker>(models);
// this.arrayList = new ArrayList<Marker>();
}
public void setRestaurants(ArrayList<Marker> arrayList) {
this.arrayList = arrayList;
notifyItemChanged(0, arrayList.size());
}
#Override
public ViewHolderRestavracije onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.restaurants_rview, parent, false);
ViewHolderRestavracije viewHolder = new ViewHolderRestavracije(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolderRestavracije holder, int position) {
Marker currentRest = arrayList.get(position);
holder.name.setText(currentRest.getTitle());
holder.address.setText(currentRest.getAddress());
holder.placilo.setText(currentRest.getValue_of_charge() + " €");
holder.oddaljenost.setText(currentRest.getOddaljenost());
holder.idrestavracije.setText(currentRest.getId());
try {
holder.ratingBarOverall.setRating(Float.parseFloat(currentRest.getOverallRating()));
} catch (Exception e) {
holder.ratingBarOverall.setRating(0);
}
Log.d("RESTAVRACIJEEEEE", currentRest.getTitle());
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolderRestavracije extends RecyclerView.ViewHolder {
private TextView name, oddaljenost, address, textPlacilo, placilo, idrestavracije;
private RatingBar ratingBarOverall;
private int id;
public View view;
public ViewHolderRestavracije(View itemView) {
super(itemView);
view = itemView;
name = (TextView) itemView.findViewById(R.id.tvNameRestaurant);
oddaljenost = (TextView) itemView.findViewById(R.id.tvOddaljenost);
address = (TextView) itemView.findViewById(R.id.tvAddress);
textPlacilo = (TextView) itemView.findViewById(R.id.tvDoplacilo);
placilo = (TextView) itemView.findViewById(R.id.tvDoplaciloEvri);
idrestavracije = (TextView) itemView.findViewById(R.id.idrestavracije);
ratingBarOverall = (RatingBar) itemView.findViewById(R.id.ratingOverallRestavracije);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//id = getAdapterPosition();
//Log.d("CLICKED", idrestavracije.getText().toString() + "");
//Log.d("CLICKED", name.getText().toString() + "");
String idrest = idrestavracije.getText().toString();
// Log.d("CLICKED", intid + "");
// Intent i = new Intent(context, RestaurantActivity.class);
// i.putExtra("ID_rest", intid);
// context.startActivity(i);
Intent i = new Intent(context, RestaurantActivity.class);
Bundle bundle = new Bundle();
bundle.putString("ID_rest", idrest);
i.putExtras(bundle);
context.startActivity(i);
}
});
}
}
////PRIPRAVA ZA SEARCH//////
public void animateTo(ArrayList<Marker> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
private void applyAndAnimateRemovals(ArrayList<Marker> newModels) {
for (int i = arrayList.size() - 1; i >= 0; i--) {
final Marker model = arrayList.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(ArrayList<Marker> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final Marker model = newModels.get(i);
if (!arrayList.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(ArrayList<Marker> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final Marker model = newModels.get(toPosition);
final int fromPosition = arrayList.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Marker removeItem(int position) {
final Marker model = arrayList.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, Marker model) {
arrayList.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Marker model = arrayList.remove(fromPosition);
arrayList.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
////PRIPRAVA ZA SEARCH//////
}
MY FRAGMENT:
---OTHER CODE----
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
recyclerView = (RecyclerView) view.findViewById(R.id.listRestaurants);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// recyclerView.setItemAnimator(new DefaultItemAnimator());
listRestaurants = new ArrayList<Marker>();
jsonRequest(latitude, longitude);
adapterRestavracije = new AdapterRestavracije(getActivity(),listRestaurants);
recyclerView.setAdapter(adapterRestavracije);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu2, menu);
MenuItem item = menu.findItem(R.id.action_search);
final SearchView sv = (SearchView) MenuItemCompat.getActionView(item);
sv.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onQueryTextSubmit(String query) {
// Utils.LogDebug("Submitted: "+query);
Log.d("Clicked: ", query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// Utils.LogDebug("Changed: " + newText);
final ArrayList<Marker> filteredModelList = filter(listRestaurants, query);
adapterRestavracije.animateTo(filteredModelList);
recyclerView.scrollToPosition(0);
//Log.d("Query Changed: ", query);
return false;
}
private ArrayList<Marker> filter(ArrayList<Marker> listRestaurants, String query) {
query = query.toLowerCase();
final ArrayList<Marker> filteredModelList = new ArrayList<Marker>();
for (Marker model : listRestaurants) {
final String text = model.getTitle().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
---OTHER CODE----
Thanks for the help.
Wow, fixed the problem. The problem was that the arraylist wasn't declared as final. So now that i did that it works :).
Example:
before:
List<ExampleModel> mModels;
after:
private final List<ExampleModel> mModels;

andorid Recycler View with lists are overlapping each other

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.

Categories

Resources