To pass only incremented value to listview on nextpage - android

I am able to send data on listview in nextpage.But problem is that items with quantity 0 is also passed.I want to show items whose quantity is incremented and not all items present in listview.Here is my code-
MainActivity.java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener{
Button show;
ListView list_item;
ArrayList<Items> itemsArrayList;
SearchView searchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
intent.putExtra("data", itemsArrayList);
startActivity(intent);
}
});
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
}
public void setupSearchView()
{
searchview.setOnQueryTextListener(this);
searchview.setQueryHint("Search Here");
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)) {
list_item.clearTextFilter();
} else {
list_item.setFilterText(s);
}
return true;
}
}
Custom.java
public class Custom extends BaseAdapter implements Filterable{
Activity a;
ArrayList<Items> itemsArrayList;
ArrayList<Items> filtered;
public Custom(Activity a, ArrayList<Items> itemsArrayList) {
this.a = a;
this.itemsArrayList = itemsArrayList;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int i) {
return itemsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results=new FilterResults();
ArrayList<Items> data=new ArrayList<Items>();
if (filtered==null)
filtered=itemsArrayList;
if (filtered != null && filtered.size() > 0) {
for (final Items g : filtered) {
if (g.getItemname().toLowerCase()
.contains(charSequence.toString()))
data.add(g);
}
results.values=data;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsArrayList=(ArrayList<Items>)filterResults.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public class Holder{
TextView sr,item,qty,price,pl,min,rate;
}
#Override
public View getView(final int position, final View view, ViewGroup viewGroup) {
final Holder holder=new Holder();
LayoutInflater li=a.getLayoutInflater();
final View view1=li.inflate(R.layout.customlist,viewGroup,false);
holder.sr=(TextView)view1.findViewById(R.id.s_no);
holder.item=(TextView)view1.findViewById(R.id.i_name);
holder.qty=(TextView)view1.findViewById(R.id.qty);
holder.price=(TextView)view1.findViewById(R.id.pr);
holder.rate=(TextView)view1.findViewById(R.id.frate);
holder.pl=(TextView) view1.findViewById(R.id.pl);
holder.min=(TextView) view1.findViewById(R.id.min);
final Items model = itemsArrayList.get(position);
holder.sr.setText(String.valueOf(itemsArrayList.get(position).getSrno()));
holder.item.setText(String.valueOf(itemsArrayList.get(position).getItemname()));
holder.rate.setText(String .valueOf(itemsArrayList.get(position).getFixedrate()));
holder.qty.setText(String.valueOf(itemsArrayList.get(position).getQuantity()));
holder.price.setText(String .valueOf(itemsArrayList.get(position).getRate()));
holder.pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity(model.getQuantity() + 1);
model.setRate(model.getQuantity()*model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
});
holder.min.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(model.getQuantity()>0) {
model.setQuantity(model.getQuantity() - 1);
model.setRate(model.getQuantity() * model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
}
});
return view1;
}
}
Items.java
public class Items implements Serializable {
int srno,fixedrate,quantity,rate;
String itemname;
public Items(int srno, String itemname, int fixedrate, int quantity, int rate) {
this.srno = srno;
this.itemname = itemname;
this.fixedrate = fixedrate;
this.quantity = quantity;
this.rate = rate;
}
public int getSrno() {
return srno;
}
public void setSrno(int srno) {
this.srno = srno;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public int getFixedrate() {
return fixedrate;
}
public void setFixedrate(int fixedrate) {
this.fixedrate = fixedrate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
Custom_Trial.java
public class Custom_Trial extends BaseAdapter {
Activity a;
private ArrayList<Items> data = new ArrayList<>();
public Custom_Trial(Activity a, ArrayList<Items> data) {
this.a = a;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView sr, it, qty, amt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
LayoutInflater li = a.getLayoutInflater();
View view = li.inflate(R.layout.customtrial, parent, false);
holder.sr = (TextView) view.findViewById(R.id.head1);
holder.it = (TextView) view.findViewById(R.id.head2);
holder.qty = (TextView) view.findViewById(R.id.head3);
holder.amt = (TextView) view.findViewById(R.id.head4);
Items m = data.get(position);
holder.sr.setText(String.valueOf(m.getSrno()));
holder.it.setText(m.getItemname());
holder.qty.setText(String.valueOf(m.getQuantity()));
holder.amt.setText(String.valueOf(m.getRate()));
return view;
}
}
Trial.java
public class Trial extends Activity{
ListView listnew;
private ArrayList<Items> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trial);
listnew = (ListView) findViewById(R.id.newlist);
data.addAll((ArrayList<Items>) getIntent().getSerializableExtra("data"));
Custom_Trial ct = new Custom_Trial(this,data);
listnew.setAdapter(ct);
}
}

It's because you passing original list. You're updating values inside adapter and passing not updated list fromadapter, but original. Write method inside adapter to return your updated list.
Inside Custom.java adapter:
public ArrayList<Items> getItems(){
ArrayList<Items> quantityArrayList;
Items item;
for (int i = 0; i < itemsArrayList.size(); i++){
item = itemsArrayList.get(i);
if (item.getQuantity() > 0)
quantityArrayList.add(item);
}
return quantityArrayList;
}
And inside MainActivity onCreate() should look like this. After clicking show button you're going to get Items from Custom Adapter whose quantity >0.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
List<Items> quantityList = c.getItems();
intent.putExtra("data", quantityList);
startActivity(intent);
}
});
}

Related

filter function on recyclerview not showing list

i need help for this filter or search with editText on fragment with recyclerView, when afterTextChanged running filter and toast show correct data, but in recyclerView not showing anything only blank list, i try create new add list but still nothing.
this is my fragment
public class HomeFragment extends Fragment {
private SQLiteHandler db;
private TextView welcome;
private TextView jmlInspection;
private RecyclerView mRecyclerView;
private ListAdapter mListadapter;
EditText searchHome;
private ArrayList<DataNote> arraylist = new ArrayList<DataNote>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
// SqLite database handler
db = new SQLiteHandler(getActivity().getApplicationContext());
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
welcome = (TextView) view.findViewById(R.id.txtWelcome);
jmlInspection = (TextView) view.findViewById(R.id.txtJmlInspection);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
searchHome = (EditText) view.findViewById(R.id.searchHome);
welcome.setText("Welcome, "+name +"!");
jmlInspection.setText("Saat ini anda memiliki 7 Data.");
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
//ArrayList data = new ArrayList<DataNote>();
for (int i = 0; i < DataNoteImformation.id.length; i++)
{
DataNote wp = new DataNote(
DataNoteImformation.id[i],
DataNoteImformation.branchArray[i],
DataNoteImformation.assetcodeArray[i],
DataNoteImformation.customerArray[i],
DataNoteImformation.licenseplateArray[i]
);
arraylist.add(wp);
}
mListadapter = new ListAdapter(arraylist);
mRecyclerView.setAdapter(mListadapter);
searchHome.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence query, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
String text = searchHome.getText().toString().toLowerCase(Locale.getDefault());
mListadapter.filter(text);
}
});
return view;
}
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>
{
private ArrayList<DataNote> dataList;
private List<DataNote> filterlist = null;
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
this.filterlist = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textViewBranch;
TextView textViewAsset;
TextView textViewCustomer;
TextView textViewLicense;
Button btnReceive;
public ViewHolder(View itemView)
{
super(itemView);
this.textViewBranch = (TextView) itemView.findViewById(R.id.branch);
this.textViewAsset = (TextView) itemView.findViewById(R.id.assetcode);
this.textViewCustomer = (TextView) itemView.findViewById(R.id.customername);
this.textViewLicense = (TextView) itemView.findViewById(R.id.licenseplate);
this.btnReceive = (Button) itemView.findViewById(R.id.receiveBtn);
}
}
#Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ListAdapter.ViewHolder holder, final int position)
{
holder.textViewBranch.setText(dataList.get(position).getBranch());
holder.textViewAsset.setText(dataList.get(position).getAssetcode());
holder.textViewCustomer.setText(dataList.get(position).getCustomer());
holder.textViewLicense.setText(dataList.get(position).getLisenceplate());
holder.btnReceive.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(),
AssetReceiveActivity.class);
intent.putExtra("name",dataList.get(position).getCustomer());
intent.putExtra("code",dataList.get(position).getAssetcode());
intent.putExtra("plat",dataList.get(position).getLisenceplate());
startActivity(intent);
}
});
}
#Override
public int getItemCount()
{
return dataList.size();
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
filterlist.clear();
if (charText.length() == 0) {
filterlist.addAll(dataList);
}
else
{
for (DataNote wp : dataList)
{
if (wp.getCustomer().toLowerCase().contains(charText.toLowerCase()))
{
//Toast.makeText(getActivity(), "data " + wp.getCustomer() , Toast.LENGTH_SHORT).show();
filterlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
no error on Logcat. i need help for this, sorry for bad english.
Look at this example
Adapter
public class ListAdapter extends RecyclerView.Adapter<ItemHolder> implements Filterable {
private Context iContext;
private List<DataNote > dataList = new ArrayList<>();
private List<DataNote > filterlist = new ArrayList<>();
public ListAdapter (List<DataNote > dataList, Context context) {
this.dataList = dataList;
this.filterlist = dataList;
iContext = context;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
dataList= (List<DataNote >) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<DataNote> filteredList = new ArrayList<>();
String searchText = constraint.toString().toLowerCase();
String[] split = searchText.split(",");
ArrayList<String> searchGenres = new ArrayList<>(split.length);
for (String aSplit : split) {
// remove spaces
String trim = aSplit.trim();
// skip empty entries
if (trim.length() > 0)
searchGenres.add(trim);
}
for (DataNote dataNames : filterlist) {
// filter by title
if (dataNames.getCustomer().toLowerCase().trim().contains(searchText)) {
filteredList.add(dataNames);
}
}
results.count = filteredList.size();
results.values = filteredList;
return results;
}
};
return filter;
}
}
In Fragment :
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mListadapter.getFilter().filter(s.toString());
}
1) In on bind, you are accessing object from dataList Object and your getItemCount() is also returning the size of dataList.
2) During filtering, you are performing filtering and storing the filtered data in filterlist and calling notifyDataSetChanged().
So here your dataList which has all the data, is shown always and not the filterlist which has the data which is filtered.
If you want to show the filtered data, you should use the filterlist with the recyclerview like,
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
this.filterlist = new ArrayList(dataList);
}
#Override
public int getItemCount()
{
return filterlist.size();
}
#Override
public void onBindViewHolder(ListAdapter.ViewHolder holder, final int position)
{
holder.textViewBranch.setText(filterlist.get(position).getBranch());
holder.textViewAsset.setText(filterlist.get(position).getAssetcode());
holder.textViewCustomer.setText(filterlist.get(position).getCustomer());
holder.textViewLicense.setText(filterlist.get(position).getLisenceplate());
holder.btnReceive.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(),
AssetReceiveActivity.class);
intent.putExtra("name",filterlist.get(position).getCustomer());
intent.putExtra("code",filterlist.get(position).getAssetcode());
intent.putExtra("plat",filterlist.get(position).getLisenceplate());
startActivity(intent);
}
});
}

recycle view won't recieve a bundle data

i'm trying to pass a bundle from a product detail activity to a cart with a recycle view but when i click on add to cart the cart is opened but remains empty i don't know what's wrong with the code
here is the first activity
public class product_details extends AppCompatActivity {
ImageView product_img, share;
TextView name, price;
public int img;
public int price1;
public String name1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
product_img = (ImageView) findViewById(R.id.Product_Img);
name = (TextView) findViewById(R.id.product_name);
price = (TextView) findViewById(R.id.product_price);
share = (ImageView) findViewById(R.id.share);
img = getIntent().getIntExtra("img", 00);
Glide.with(this).load(img).into(product_img);
name1 = getIntent().getStringExtra("name");
name.setText(name1);
price1 = getIntent().getIntExtra("price", 0);
price.setText(String.valueOf(price1));
ImageView cart = (ImageView) findViewById(R.id.add_cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CartActivity.class);
Bundle extras = new Bundle();
extras.putString("price1", String.valueOf((price1)));
extras.putString("name1", name1);
extras.putString("img1",String.valueOf(img));
intent.putExtras(extras);
startActivity(intent);
}
my second activity class
public class CartRecycler {
int images_id;
String productname,productprice,productquantity;
public String getProductquantity() {
return productquantity;
}
public CartRecycler(int images_id , String productname , String productprice , String productquantity){
this.setImages_id(images_id);
this.setProductname(productname);
this.setProductprice(productprice);
this.setProductquantity(productquantity);
}
public CartRecycler(String productname, int images_id, String productprice) {
this.productname = productname;
this.images_id = images_id;
this.productprice = productprice;
}
public int getImages_id() {
return images_id;
}
public void setImages_id(int images_id) {
this.images_id = images_id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductprice() {
return productprice;
}
public void setProductprice(String productprice) {
this.productprice = productprice;
}
public void setProductquantity(String productquantity) {
this.productquantity = productquantity;
}
}
cart adapter
public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {
ArrayList<CartRecycler> adapterlist = new ArrayList<>();
CartActivity cartactivity;
Context cnx;
public CartAdapter(ArrayList<CartRecycler> adapterlist,Context cnx){
this.adapterlist =adapterlist;
this.cnx =cnx;
cartactivity = (CartActivity) cnx;
}
#Override
public CartViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cart_cards,parent,false);
CartViewHolder cartviewholder = new CartViewHolder(v,cartactivity);
return cartviewholder;
}
#Override
public void onBindViewHolder(CartViewHolder holder, int position) {
holder.image.setImageResource(adapterlist.get(position).getImages_id());
holder.name.setText(adapterlist.get(position).getProductname());
holder.price.setText(adapterlist.get(position).getProductprice());
holder.quantity.setText(adapterlist.get(position).getProductquantity());
if(!cartactivity.edit_mode){
holder.checkornot.setVisibility(View.GONE);
}
else {
holder.checkornot.setVisibility(View.VISIBLE);
holder.checkornot.setChecked(false);
}
}
#Override
public int getItemCount() {
return adapterlist.size();
}
public static class CartViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView image;
TextView price,quantity,name;
CheckBox checkornot;
CartActivity cartactivity;
CardView cardv;
public CartViewHolder(View itemView, CartActivity cartactivity) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.cartimage);
name = (TextView) itemView.findViewById(R.id.pn);
price = (TextView) itemView.findViewById(R.id.p);
quantity = (TextView) itemView.findViewById(R.id.q);
checkornot = (CheckBox) itemView.findViewById(R.id.ckbox);
this.cartactivity= cartactivity;
cardv = (CardView) itemView.findViewById(R.id.cardd);
cardv.setOnLongClickListener((View.OnLongClickListener) cartactivity);
checkornot.setOnClickListener(this);
}
#Override
public void onClick(View view) {
cartactivity.prepareselection(view,getAdapterPosition());
}
}
public void updateadapter(ArrayList<CartRecycler> list){
for(CartRecycler cartRecycler:list){
adapterlist.remove(cartRecycler);
}
notifyDataSetChanged();
}
}
second activity
public class CartActivity extends AppCompatActivity implements View.OnLongClickListener{
Button l;
ImageView imv;
Toolbar t;
RecyclerView rv;
RecyclerView.LayoutManager layoutmanager;
RecyclerView.Adapter adapter;
ArrayList<CartRecycler> cartitems = new ArrayList<>();
ArrayList<CartRecycler> selected_items_list = new ArrayList<>();
int countt =0;
boolean edit_mode =false;
TextView counterr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
t = (Toolbar) findViewById(R.id.toolb);
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
l = (Button) findViewById(R.id.checkoutsummary);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent n = new Intent(CartActivity.this,SummaryActivity.class);
startActivity(n);
}
});
rv = (RecyclerView) findViewById(R.id.mycartrecycler);
layoutmanager = new LinearLayoutManager(this);
rv.setLayoutManager(layoutmanager);
rv.setHasFixedSize(true);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String price = extras.getString("price1");
String img1 = extras.getString("img1");
int imag1 = Integer.parseInt(img1);
String name = extras.getString("name1");
for (int i = 0; i < cartitems.size(); i++) {
CartRecycler cart = new CartRecycler(name, imag1, price);
cartitems.add(cart);
adapter.notifyDataSetChanged();
i++;
}
} else {
Intent intent = new Intent(this, test.class);
startActivity(intent);
}
adapter = new CartAdapter(cartitems,CartActivity.this);
rv.setAdapter(adapter);
counterr = (TextView) findViewById(R.id.selecteditemcounter);
counterr.setVisibility(View.GONE);
}
#Override
public boolean onLongClick(View view) {
t.getMenu().clear();
t.inflateMenu(R.menu.cart_edit_mode);
counterr.setVisibility(View.VISIBLE);
edit_mode = true;
adapter.notifyDataSetChanged();
return true;
}
public void prepareselection(View view,int position){
if(((CheckBox)view).isChecked()){
selected_items_list.add(cartitems.get(position));
countt = countt+1;
updatecounter(countt);
}
else {
selected_items_list.remove(cartitems.get(position));
countt = countt -1;
updatecounter(countt);
}
}
public void updatecounter(int counter){
if(counter==0){
counterr.setText("0 items selected");
}
else {
counterr.setText(counter+" item selected");
}
}
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.item_delete){
CartAdapter cartAdapter = (CartAdapter) adapter;
cartAdapter.updateadapter(selected_items_list);
}
else if(item.getItemId()== android.R.id.home)
{
adapter.notifyDataSetChanged();
}
return true;
}
}
for (int i = 0; i < cartitems.size(); i++) This loop will not run until and unless size of cartitems is greater than 0 and hence all the code under it's scope will never get executed

Getting wrong item selected from filtered list using recyclerview

I have a RecyclerView & EditText. I can select the item from RecyclerView & gets correct item unless it is not filtered.
On entering in EditText, RecyclerView list gets filtered & when I select any item from the list it shows me actual list item instead of selected one.
Fragment Class :
public class RegionListFragment extends DialogFragment implements View.OnClickListener,
OnRecylerViewClickable {
private RecyclerView regionRecyclerView;
private ArrayList<RegionDetail> regionDetailArrayList = new ArrayList<>();
private GenericRegionListAdapter genericRegionListAdapter;
private Context context = this.getActivity();
private RecyclerView.LayoutManager mLayoutManager;
private View view;
private EditText editTextSearchView;
private DatabaseHandler spcl_databaseHandler;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.spinner_fragment_list_screen, container, false);
databaseHandler = new DatabaseHandler(getActivity());
regionDetailArrayList = (ArrayList<RegionDetail>) spcl_databaseHandler.getAllRegionDetails();
editTextSearchView = (EditText) view.findViewById( R.id.search);
editTextSearchView.setHint(getString(R.string.region_search_hint));
mLayoutManager = new LinearLayoutManager(context);
regionRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_Locations);
regionRecyclerView.setLayoutManager(mLayoutManager);
relativeLayoutBottom = (RelativeLayout) view.findViewById(R.id.rlBottom);
genericRegionListAdapter = new GenericRegionListAdapter(context, regionDetailArrayList, this, false);
regionRecyclerView.setAdapter(genericRegionListAdapter);
addTextListener();
return view;
}
public void addTextListener(){
editTextSearchView.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
genericRegionListAdapter.getFilter().filter(query.toString());
}
});
}
#Override
public void onClick(View view) {
}
#Override
public void onRecyclerItemClicked(int position, String itemName, String itemID) {
Log.v("Region Name", " : " + regionDetailArrayList.get(position).getRegionName());
}
}
Adapter Class :
public class GenericRegionListAdapter extends RecyclerView.Adapter<GenericRegionListAdapter.DataObjectHolder>
implements Filterable {
private ArrayList<RegionDetail> originalArrayList;
private ArrayList<RegionDetail> filterArrayList;
private GenericRegionListAdapter.ValueFilter valueFilter;
private OnRecylerViewClickable onRecylerViewClickable;
private Context mContext = null;
#Override
public GenericRegionListAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sd_custom_cardview_for_walk_list_item, parent, false);
GenericRegionListAdapter.DataObjectHolder dataObjectHolder = new GenericRegionListAdapter.DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new GenericRegionListAdapter.ValueFilter();
}
return valueFilter;
}
public class DataObjectHolder extends RecyclerView.ViewHolder{
TextView textViewWalkName;
public DataObjectHolder(View itemView) {
super(itemView);
mContext = itemView.getContext();
textViewWalkName = (TextView) itemView.findViewById(R.id.textView_Walk_Name);
}
}
public GenericRegionListAdapter(Context context, ArrayList<RegionDetail> detailsArrayList,
OnRecylerViewClickable onRecylerViewClickable, boolean doShowCheckbox) {
mContext = context;
this.originalArrayList = detailsArrayList;
this.filterArrayList = detailsArrayList;
this.onRecylerViewClickable = onRecylerViewClickable;
}
#Override
public void onBindViewHolder(final GenericRegionListAdapter.DataObjectHolder holder, final int position) {
holder.textViewWalkName.setText(originalArrayList.get(position).getRegionName());
holder.textViewWalkName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRecylerViewClickable.onRecyclerItemClicked(position, originalArrayList.get(position).getRegionName(), originalArrayList.get(position).getRegionID());
}
});
}
// method to access in activity after updating selection
public ArrayList<RegionDetail> getRegionList() {
return originalArrayList;
}
#Override
public int getItemCount() {
return originalArrayList.size();
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
for (int i = 0; i < filterArrayList.size(); i++) {
if ((filterArrayList.get(i).getRegionName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = filterArrayList.size();
results.values = filterArrayList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
Log.v("Size", " : " + originalArrayList.size());
if (originalArrayList.size() == 0) {
new GlobalToast().showToastMessage(mContext, mContext.getResources().getString(R.string.no_records_found));
}
}
}
}
Please help me.
Please use this code snippet
private class ItemFilter extends Filter {
String filterString;
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = filterArrayList.size();
ArrayList<RegionDetail> filterList = new ArrayList<RegionDetail>();
String filterableString;
for (int i = 0; i < count; i++) {
RegionDetail listItem = new RegionDetail();
listItem.setRegionID(filterArrayList.get(i).getRegionID());
listItem.setRegionName(filterArrayList.get(i).getRegionName());
filterList.add(listItem);
}
results.values =filterList;
results.count = filterList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
originalArrayList = (ArrayList<RegionDetail>) results.values;
notifyDataSetChanged();
}
}
i hope this code will filter your list correctly and you get right list item onClick.

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

Wrong position after filter

I have a problem with my application. Actually, I'm totally stuck. I have a list of countries with implemented clicklistener and searchview. In a situation when I click on a given element without searching the list, everything displays correctly and shows information about a given country. But when I search the list and click on the element, the application goes to the information about the random country. I dont know why this is happening. I have no error. Only a warning:
W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
MainActivity
public static final String EXTRA_COUNTRY_NAME = "country_name";
public static final String EXTRA_COUNTRY_REGION = "country_region";
public static final String EXTRA_COUNTRY_NATIVE_NAME = "country_nativename";
public static final String EXTRA_COUNTRY_NAME_LANGUGES= "country_namelanguages";
private RecyclerView recyclerView;
private DataAdapter dataAdapter;
private List<ModelJsona> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews(){
recyclerView=(RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
loadJSON();
}
private void loadJSON(){
dataArrayList = new ArrayList<>();
Retrofit retrofit=new Retrofit.Builder().baseUrl("https://restcountries.eu/").addConverterFactory(GsonConverterFactory.create()).build();
RequestInterface requestInterface=retrofit.create(RequestInterface.class);
Call<List<ModelJsona>> call= requestInterface.getJSON();
call.enqueue(new Callback<List<ModelJsona>>() {
#Override
public void onResponse(Call<List<ModelJsona>> call, Response<List<ModelJsona>> response) {
dataArrayList = response.body();
dataAdapter=new DataAdapter(getApplicationContext(),dataArrayList);
recyclerView.setAdapter(dataAdapter);
dataAdapter.setOnitemClickListener(MainActivity.this);
}
#Override
public void onFailure(Call<List<ModelJsona>> call, Throwable t) {
Log.e("Error",t.getMessage());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem search = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
search(searchView);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void search(SearchView searchView) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
dataAdapter.getFilter().filter(newText);
if (dataAdapter !=null)dataAdapter.getFilter().filter(newText);
return true;
}
});
}
#Override
public void onItemClick(int position) {
Intent detailsIntent = new Intent(this,Details.class);
ModelJsona click = dataArrayList.get(position);
detailsIntent.putExtra(EXTRA_COUNTRY_NAME,click.getName());
detailsIntent.putExtra(EXTRA_COUNTRY_REGION,click.getRegion());
detailsIntent.putExtra(EXTRA_COUNTRY_NATIVE_NAME,click.getNativeName());
detailsIntent.putExtra(EXTRA_COUNTRY_NAME_LANGUGES,click.getLanguages().get(0).getName());
startActivity(detailsIntent);
}
}
DataAdapter
private Context context;
private List<ModelJsona> dataList;
private List<ModelJsona> filtr;
private OnitemClickListener mListener;
public interface OnitemClickListener {
void onItemClick (int position);
}
public void setOnitemClickListener (OnitemClickListener listener)
{
mListener=listener;
}
public DataAdapter(Context context, List<ModelJsona> dataList) {
this.context = context;
this.dataList = dataList;
this.filtr= dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.country_name.setText(filtr.get(position).getName());
holder.country_region.setText(filtr.get(position).getRegion());
holder.country_nativename.setText(filtr.get(position).getNativeName());
holder.country_languagename.setText(filtr.get(position).getLanguages().get(0).getName());
}
#Override
public int getItemCount() {
return filtr.size();
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filtr = dataList;
} else {
ArrayList<ModelJsona> listadoprzeszukiwan = new ArrayList<>();
for (ModelJsona wyszukiwarka : dataList) {
if (
wyszukiwarka.getName().contains(charString) ||
wyszukiwarka.getName().toLowerCase().contains(charString) ||
wyszukiwarka.getRegion().contains(charString) ||
wyszukiwarka.getRegion().toLowerCase().contains(charString) ||
wyszukiwarka.getNativeName().contains(charString) ||
wyszukiwarka.getNativeName().toLowerCase().contains(charString) ||
wyszukiwarka.getTopLevelDomain().contains(charString))
{
listadoprzeszukiwan.add(wyszukiwarka);
}
}
filtr = listadoprzeszukiwan;
}
FilterResults wynikiszukania = new FilterResults();
wynikiszukania.values = filtr;
return wynikiszukania;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults wynikiszukania) {
filtr = (ArrayList<ModelJsona>) wynikiszukania.values;
notifyDataSetChanged();
}
};
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView country_name, country_region, country_languagename,country_nativename;
public MyViewHolder(View itemView) {
super(itemView);
country_name = (TextView) itemView.findViewById(R.id.country_name);
country_region = (TextView) itemView.findViewById(R.id.country_region);
country_nativename = (TextView) itemView.findViewById(R.id.country_nativename);
country_languagename= (TextView) itemView.findViewById(R.id.country_languagename);
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));
}
}
}
i see that you get the position in filter list refer to different object with same position value in dataList because after filtering filter list become reference to result but still dataList hold all data.
you can replace itemView click listner by this:
itemView.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener !=null){
int position = getAdapterPosition();
String name = filtr.get(position).getName();
for (int i=0 ; i <dataList.size() ; i++ ){
if(name.equals(dataList.get(i).getName()){
position = i;
break;
}
}
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
}));

Categories

Resources