How to sum checked items data values in RecyclerView - java

My problem is how to sum all checked items values, and how to manage their changed at check/uncheck events?
This is my method for check box toggle (check/uncheck) event.
holder.itemCheckBox.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (((CheckBox) v).isChecked())
{
double price = Double.parseDouble(catalogDatabases.get(position).getPriceItem());
holder.totalPrice = holder.totalPrice + price;
holder.listener.respond(holder.totalPrice);
}
else {
}
}
});

So first of all don't rely on the view as data.
I'll explain in your code
if (((CheckBox) v).isChecked())
You relying on view's isChecked method.
This may cause a bug because of android list recycling mechanism.
You can read about it in the link below
How ListView's recycling mechanism works
TL;DR views are being recycled so when you scroll your list.
So for example the user checked item number 3 and then scrolled the list down item number 13 for example may also be shown as checked even tho it isn't .
So when onClick triggers we need to save the checked state in some list
After the theoretical intro i'll show it in code.
//Here you'll need to create some boolean array or list to store
//checked not checked positions lets call it checked
boolean[] checkedArr = new boolean[catalogDatabases.size()];
// catalogDatabases.size represents your data set size
// note that all items will be false initially
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
/**
* Other views binding.......
*/
holder.itemCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
checkedArr[position] = isChecked;
sumAllCheckedAndNotify();
}
}
);
}
(I decided to do the calculation on every check it more straight forward from making an update on the event)
private void sumAllCheckedAndNotify() {
double sum = 0;
for (int i = 0; i < checkedArr.length; i++) {
if(checkedArr[i]) {
sum += Double.parseDouble(catalogDatabases.get(i).getPriceItem());
}
}
// pudate the listener
listener.respond(sum, selectedCount);
}

Store totalPrice inside adapter and add/subtract value based on CheckBox state like below:
class YourAdapter extends ... {
double totalPrice = 0;
...
#Override
public void onBindViewHolder(#NonNull RecyclerHolder holder, int position) {
holder.itemCheckBox.setChecked(catalogDatabases.get(position).isSelected());
holder.itemCheckBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price = Double.parseDouble(catalogDatabases.get(position).getPriceItem());
boolean isSelected = !catalogDatabases.get(position).isSelected();
catalogDatabases.get(position).setSelected(isSelected);
if (isSelected) {
totalPrice += price;
} else {
totalPrice -= price;
}
holder.listener.respond(totalPrice);
notifyDataSetChanged();
}
});
}
}
Update your Model to hold checked/ unchecked state to persist data
class CatalogDatabase { //Assume this is your model class
private boolean isSelected
....
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
....
}

Related

Why is the drag animation being repeated in RecyclerView?

I am using the ItemTouchHelper class to support drag and drop in my RecyclerView. While I am dragging an item around it visually updates (swaps rows) as expected. Once I drop the item, another **visual** drag occurs. For example (see diagram below) if I drag item "a" from index 0 to index 3, the correct list shows that item "b" is now at index 0. They recycler view repeats the operation and takes the new item at index 0 ("b") and drags it to index 3! This repeated drag happens no matter what index I drag from or to.
I called it a **visual** drag because the list I am submitting to my RecyclerView's ListAdapter is correctly ordered (verified by logs). And if I restart my app the list is in the correct order. Or if I call notifyDataSetChanged(), after the unwanted animation, it will order itself properly. What could be causing this second animation?
EDIT: According to the documentation, if you use equals() method in your areContentsTheSame() method (DiffUtil), "Incorrectly returning false here will result in too many animations." As far as I can tell, I am properly overriding this method in my POJO file below. I am stumped...
MainActivity.java
private void setListObserver() {
viewModel.getAllItems().observe(this, new Observer<List<ListItem>>() {
#Override
// I have verified newList has the correct order through log statements
public void onChanged(List<ListItem> newList) {
adapterMain.submitList(newList);
}
});
}
...
// This method is called when item starts dragging
public void onSelectedChanged(#Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
...
if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
currentList = new ArrayList<>(adapterMain.getCurrentList()); // get current list from adapter
}
...
}
// This method is called when item is dropped
public void clearView(#NonNull RecyclerView recyclerView,
#NonNull RecyclerView.ViewHolder viewHolder) {
...
// I have verified that all code in this method is returning correct values through log statements.
// If I restart the app, everything is in the correct order
// this is position of the where the item was dragged to, gets its value from the onMoved method.
// it's the last "toPos" value in onMoved() after the item is dropped
int position = toPosition;
// Skip this code if item was deleted (indicated by -1). Otherwise, update the moved item
if(position != -1) {
ListItem movedItem = currentList.get(position);
// If dragged to the beginning of the list, subtract 1 from the previously lowest
// positionInList value (the item below it) and assign it the moved item. This will ensure
// that it now has the lowest positionInList value and will be ordered first.
if(position == 0) {
itemAfterPos = currentList.get(position + 1).getPositionInList();
movedItemNewPos = itemAfterPos - 1;
// If dragged to the end of list, add 1 to the positionInList value of the previously
// largest value and assign to the moved item so it will be ordered last.
} else if (position == (currentList.size() - 1)) {
itemBeforePos = currentList.get(position - 1).getPositionInList();
movedItemNewPos = itemBeforePos + 1;
// If dragged somewhere in the middle of list, get the positionInList variable value of
// the items before and after it. They are used to compute the moved item's new
// positionInList value.
} else {
itemBeforePos = currentList.get(position - 1).getPositionInList();
itemAfterPos = currentList.get(position + 1).getPositionInList();
// Calculates the moved item's positionInList variable to be half way between the
// item above it and item below it
movedItemNewPos = itemBeforePos + ((itemAfterPos - itemBeforePos) / 2.0);
}
updateItemPosInDb(movedItem, movedItemNewPos);
}
private void updateItemPosInDb(ListItem movedItem, double movedItemNewPos) {
movedItem.setPositionInList(movedItemNewPos);
viewModel.update(movedItem); // this updates the database which triggers the onChanged method
}
public void onMoved(#NonNull RecyclerView recyclerView,
#NonNull RecyclerView.ViewHolder source, int fromPos,
#NonNull RecyclerView.ViewHolder target, int toPos, int x, int y) {
Collections.swap(currentList, toPos, fromPos);
toPosition = toPos; // used in clearView()
adapterMain.notifyItemMoved(fromPos, toPos);
}
}).attachToRecyclerView(recyclerMain);
RecyclerAdapterMain.java
public class RecyclerAdapterMain extends ListAdapter<ListItem, RecyclerAdapterMain.ListItemHolder> {
// Registers MainActivity as a listener to checkbox clicks. Main will update database accordingly.
private CheckBoxListener checkBoxListener;
public interface CheckBoxListener {
void onCheckBoxClicked(ListItem item); // Method implemented in MainActivity
}
public void setCheckBoxListener(CheckBoxListener checkBoxListener) {
this.checkBoxListener = checkBoxListener;
}
public RecyclerAdapterMain() {
super(DIFF_CALLBACK);
}
// Static keyword makes DIFF_CALLBACK variable available to the constructor when it is called
// DiffUtil will compare two objects to determine if updates are needed
private static final DiffUtil.ItemCallback<ListItem> DIFF_CALLBACK =
new DiffUtil.ItemCallback<ListItem>() {
#Override
public boolean areItemsTheSame(#NonNull ListItem oldItem, #NonNull ListItem newItem) {
return oldItem.getId() == newItem.getId();
}
// Documentation - NOTE: if you use equals, your object must properly override Object#equals().
// Incorrectly returning false here will result in too many animations.
// As far as I can tell I am overriding the equals() properly in my POJO below
#Override
public boolean areContentsTheSame(#NonNull ListItem oldItem, #NonNull ListItem newItem) {
return oldItem.equals(newItem);
}
};
#NonNull
#Override
public ListItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_item_layout_main, parent, false);
return new ListItemHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ListItemHolder holder, int position) {
ListItem item = getItem(position);
Resources resources = holder.itemView.getContext().getResources();
holder.txtItemName.setText(item.getItemName());
holder.checkBox.setChecked(item.getIsChecked());
// Set the item to "greyed out" if checkbox is checked, normal color otherwise
if(item.getIsChecked()) {
holder.txtItemName.setTextColor(Color.LTGRAY);
holder.checkBox.setButtonTintList(ColorStateList
.valueOf(resources.getColor(R.color.checkedColor, null)));
} else {
holder.txtItemName.setTextColor(Color.BLACK);
holder.checkBox.setButtonTintList(ColorStateList
.valueOf(resources.getColor(R.color.uncheckedColor, null)));
}
}
public class ListItemHolder extends RecyclerView.ViewHolder {
private TextView txtItemName;
private CheckBox checkBox;
public ListItemHolder(#NonNull View itemView) {
super(itemView);
txtItemName = itemView.findViewById(R.id.txt_item_name);
// Toggle checkbox state
checkBox = itemView.findViewById(R.id.checkBox);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkBoxListener.onCheckBoxClicked(getItem(getAdapterPosition()));
}
});
}
}
public ListItem getItemAt(int position) {
return getItem(position);
}
}
ListItem.java (POJO)
#Entity(tableName = "list_item_table")
public class ListItem {
#PrimaryKey(autoGenerate = true)
private long id;
private String itemName;
private boolean isChecked;
private double positionInList;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public boolean getIsChecked() {
return isChecked;
}
public void setPositionInList(double positionInList) {
this.positionInList = positionInList;
}
public double getPositionInList() {
return positionInList;
}
#Override
public boolean equals(#Nullable Object obj) {
ListItem item = new ListItem();
if(obj instanceof ListItem) {
item = (ListItem) obj;
}
return this.getItemName().equals(item.getItemName()) &&
this.getIsChecked() == item.getIsChecked() &&
this.getPositionInList() == item.getPositionInList();
}
}

Collecting all checkbox (checked) items into Array or ArrayList

I have ActivityNewGame which has an ArrayList (mPlayerList) with items of type NewGamePlayerItem. Each NewGamePlayerItem instance contains a checked boolean flag and the player's name. I must collect all checked names within an Array or ArrayList for later use.
In the following method you can see how the player's list is built and how it gets its items. False is the default value for the checked flag and getText1() returns the player's name from other activity name list.
private void insertNames() {
if (ActivityPlayers.mNameList == null) {
mPlayerList = new ArrayList<>();
} else {
mPlayerList = new ArrayList<>();
for (int i = 0; i < ActivityPlayers.mNameList.size(); i++) {
mPlayerList.add(new NewGamePlayerItem(false, ActivityPlayers.mNameList.get(i).getText1()));
}
}
}
Here is my Adapter implementation:
public void onBindViewHolder(#NonNull final NewGamePlayerViewHolder holder, int position) {
final NewGamePlayerItem currentItem = mNewGamePlayerList.get(position);
/** In some cases, this will prevent unwanted situations **/
holder.mCheckBox.setOnCheckedChangeListener(null);
/** If true, checkbox will be selected, else unselected **/
holder.mCheckBox.setChecked(currentItem.getCheckBox());
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/** set object's last status **/
currentItem.setSelected(isChecked);
}
});
/** Set name **/
holder.mName.setText(currentItem.getmText());
}
Here is the item:
public class NewGamePlayerItem {
private boolean mCheckBox;
private String mText;
public NewGamePlayerItem(boolean checkBox, String text) {
mCheckBox = checkBox;
mText = text;
}
public boolean getCheckBox() {
return mCheckBox;
}
public String getmText() {
return mText;
}
public void setSelected(boolean isSelected) {
mCheckBox = isSelected;
}
}
So what could I do in order to save all checked items/those names in items into array or arraylist?
You could possibly do something like
List<NewGamePlayerItem> checkedItems = new ArrayList<>();
for(NewGamePlayerItem item : mPlayerList)
{
if(item.getCheckBox())
{
checkedItems.add(item);
}
}
That would iterate over all NewGamePlayerItem in the list mPlayerList and check if the checkbox is selected, if it is then it adds it to an ArrayList called checkedItems. Now checkedItems contains a list of all selected items.
You could also then get the names from this list as well.
Or if all you needed was the names then it would be something like
List<String> checkedNames = new ArrayList<>();
for(NewGamePlayerItem item : mPlayerList)
{
if(item.getChecked())
{
checkedNames.add(item.getmText());
}
}

Recyclerview checkbox are checked when not clicked

I have a Recyclerview with checkboxes. When a user checks a box, when they scroll down another box will already be checked. I understand why, because that box is being recycled which makes sense.
But I am having issues to set it so it does not do this:
My current onBindViewHolder:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position){
holder.playerNameNumber.setText(playerData.get(position).name + "\n" +playerData.get(position).number );
holder.pickedPlayer.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View thisView){
PlayerDetails contact = new PlayerDetails();
int contactPos = position;
if(holder.pickedPlayer.isChecked()) {
contact.number = playerData.get(position).number;
contact.name = playerData.get(position).name;
playerListGame.addPlayer(contact);
String name = contact.name;
Toast.makeText(thisView.getContext(), name + " Added", Toast.LENGTH_LONG).show();
holder.pickedPlayer.setChecked(true);
}
else if(!holder.pickedPlayer.isChecked()){
contact.number = playerData.get(position).number;
contact.name = playerData.get(position).name;
for(PlayerDetails i : playerListGame.myPlayers){
if(i.name == contact.name && i.number == contact.number){
contactPos = playerListGame.myPlayers.indexOf(i);
}
}
playerListGame.removePlayer(contactPos);
String name = contact.name;
Toast.makeText(thisView.getContext(), name + " Removed", Toast.LENGTH_LONG).show();
}
}
});
}
Now I know that SetIsRecyclable is a big no no, though it does fix my problem:
public ViewHolder(View v){
super(v);
playerNameNumber = v.findViewById(R.id.playerDetails);
pickedPlayer =v.findViewById(R.id.
this.setIsRecyclable(false);
How do I avoid using such a method to resolve this issue?
holder.pickedPlayer.setOnCheckedChangeListener(null);
//define private boolean selected with setter and getter
holder.pickedPlayer.setChecked(playerData.isSelected());
holder.pickedPlayer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
playerData.setSelected(isChecked);
if (isChecked)
{
Toast.makeText(context,"checked", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(context,"not checked", Toast.LENGTH_LONG).show();
}
}
});
you have to use a boolean into your dataset also.so when user check or uncheck a box that time update the boolean value of respected position’s dataset and call notify item changed
arraylist.get(pos).setDataCheked(true);
notifyItemChanged(pos);
You need to set the current value of the checkbox just like you're setting the player name and number. I've assumed it's called something like picked in your playerData.
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.playerNameNumber.setText(playerData.get(position).name + "\n" +playerData.get(position).number );
holder.pickedPlayer.setChecked(playerData.get(position).picked);
// same onclick listener, removed for readability
}

Best solution for Checkbox in LinearLayout

In my LinearLayout, there's a variable number of CheckBoxes. In a question I had a month ago someone said it´s better to add checkboxes dynamicly instead of make them not visible.
Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10};
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {
cBox = new CheckBox(this);
cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
cBox.setId(count[i]);
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
antwortencode[position] += "" + buttonView.getId();
frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");
} else {
String id = Integer.toString(buttonView.getId());
antwortencode[position] = antwortencode[position].replaceAll(id,"");
if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
} else {
frageBeantworten.setText("Keine Checkbox(en) gewählt");
}
}
}
});
antworten.addView(cBox);
Currently, I'm able to save a string with the checked checkboxes, if I un-check a checkbox, it deletes it's value out of the string.
If I update the activity, the string is saved, and the checkboxes get a new List from the mFrageList.get(position)getAuswahlList(); and fill a new string in the "antwortencode" List with their values.
If I go back to the last position, I have the string which was generated but the checkboxes aren't checked anymore. But they have the Strings from the old position. that means everything is saved except the state of the checkboxes. I cant set a cBox.setChecked(isChecked) or buttonView.setChecked(isChecked) or buttonView.setChecked(buttonView.isChecked()) or something which is nearly the same in syntax.
I don't know what I can do besides declaring 10 Checkboxes in a xml file to talk to them one by one and set the VISIBLE.false if the auswahlList.get(position).isEmpty().
IMPORTANT: My XML is a Scrollable Activity because the size of the content overextended the screen. Thats why i didn´t and can´t use a Listview. So i need a solution that uses a LinearLayout
The truth is, you should actually use a ListView. As long as you reuse a layout multiple times - do it.
There are 2 options:
ListView as root - add other contents of your layout as different types of view
ListView inside a scrollable layout - there are many lightweight implementations of ListView that allow it to wrap content, e.g. https://github.com/paolorotolo/ExpandableHeightListView
The other thing is how to maintain the state of Checkboxes - use model classes. It's extremely easy with a ListView as it forces you to use an Adapter which provides methods to iterate over all positions.
Example of an adapter:
public class CheckableItemAdapter extends BaseAdapter {
private List<Pair<Integer, Boolean>> items = new ArrayList<>();
public void setItems(List<Pair<Integer, Boolean>> items) {
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_checkable, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
Pair<Integer, Boolean> item = items.get(position);
holder.itemCheck.setChecked(item.second);
return view;
}
static class ViewHolder {
CheckBox itemCheck;
public ViewHolder(View itemView) {
itemCheck = (CheckBox) itemView.findViewById(R.id.check);
}
}
}
I´ve managed to solve my problem alone, and now i want to share it, even if it isn´t the best example of programming.
Integer[] count = new Integer[]{1,2,3,4,5,6,7,8,9,10}; //maximum of 10 Checkboxes
size = mFrageList.get(position).getAuswahlList().size();
for (int i = 0; i < size; i++) {
cBox = new CheckBox(this);
cBox.setText(mFrageList.get(position).getAuswahlList().get(i));
cBox.setId(count[i]);
try{ //this is where the magic happens
if(antwortencode[position] != ""){ //cause i won´t want null in my db i´ve set "" as standard string in my activity for the List<String>
String code = antwortencode[position];
char[] c = code.toCharArray();
for(int j=0;j<=c.length;j++){
int x = c[j] -'0'; // 'char 1' - 'char 0' = Integer 1 , lol
if(cBox.getId()== x){ //compare them
cBox.toggle(); //if it fits, toggle
}
}
}
} catch (Exception e){
e.printStackTrace();
} //and here it ends
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
antwortencode[position] += "" + buttonView.getId();
frageBeantworten.setText("Antwort :"+antwortencode[position]+" abgeben");
} else {
String id = Integer.toString(buttonView.getId());
antwortencode[position] = antwortencode[position].replaceAll(id,"");
if(!antwortencode[position].isEmpty() || antwortencode[position]!= "") {
frageBeantworten.setText("Antwort :" + antwortencode[position] + " abgeben");
} else {
frageBeantworten.setText("Keine Checkbox(en) gewählt");
}
}
}
});
antworten.addView(cBox);
Ty for the answers and for the correction of my question.
Nostramärus

How to get a method called with different parameters?

I'm fetching 3 String values from the database and then I'm converting it to Long and then I'm calculating a difference and then putting this calculated Long value in a method as parameter. I'm using FastAdapter.
The filterRequests(List <Long> l) is a method in MainActivity which do the logic of filtering requests/content based on the long l.
entire adapter:
public class GRModelClass extends AbstractItem<GRModelClass, GRClass.ViewHolder>{
private static final ViewHolderFactory<? extends ViewHolder> FACTORY = new ItemFactory();
String postedBy, postedTime, currentLat, currentLng, utcFormatDateTime, userEmail, userID;
String startDateTimeInEpoch, endDateTimeInEpoch;
DatabaseReference primaryDBKey;
long ms;
String itemID;
public GRModelClass(){}
public GRModelClass(String postedBy, String postedTime, String currentLat, String currentLng, String utcFormatDateTime, String userEmail, String userID, String startDateTimeInEpoch, String endDateTimeInEpoch, DatabaseReference primaryDBKey) {
this.postedBy = " " + postedBy;
this.postedTime = postedTime;
this.currentLat = currentLat;
this.currentLng = currentLng;
this.utcFormatDateTime = utcFormatDateTime;
this.userEmail = userEmail;
this.userID = userID;
this.startDateTimeInEpoch = startDateTimeInEpoch;
this.endDateTimeInEpoch = endDateTimeInEpoch;
this.primaryDBKey = primaryDBKey;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("pBy", postedBy);
result.put("cLat", currentLat);
result.put("cLng", currentLng);
result.put("utcFormatDateTime", utcFormatDateTime);
result.put("userEmail", userEmail);
result.put("userID", userID);
result.put("startDateTime", startDateTimeInEpoch);
result.put("endDateTime", endDateTimeInEpoch);
return result;
}
#Override
public int getType() {
return R.id.recycler_view;
}
#Override
public int getLayoutRes() {
return R.layout.sr_layout;
}
#Override
public void bindView(final ViewHolder holder, List list) {
super.bindView(holder, list);
holder.postedBy.setText(postedBy);
holder.postedBy.setTypeface(null, Typeface.BOLD);
holder.startDateTimeInEpoch.setText(startDateTimeInEpoch);
holder.startDateTimeInEpoch.setVisibility(View.INVISIBLE);
holder.endDateTimeInEpoch.setText(endDateTimeInEpoch);
holder.endDateTimeInEpoch.setVisibility(View.INVISIBLE);
MainActivity.filterButton.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
holder.geoQuery = holder.geoFireReference.queryAtLocation(new GeoLocation(holder.currentLatDouble, holder.currentLngDouble), 5);
holder.geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
primaryDBKey.child(key).child("startDateTimeInEpoch").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
holder.startTimeDateInEpochLong2 = Long.parseLong(dataSnapshot.getValue().toString());
holder.now = System.currentTimeMillis() / 1000;
holder.diffNowsdtel.add(holder.startTimeDateInEpochLong2 - holder.now);
Log.d("log1", String.valueOf(holder.diffNowsdtel));
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(holder.mContext instanceof MainActivity){
((MainActivity)holder.mContext).filterRequests(holder.diffNowsdtel);
Log.d("log2", String.valueOf(holder.diffNowsdtel));
}
}
}, 1500);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onKeyExited(String key) {
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
}
#Override
public void onGeoQueryReady() {
}
#Override
public void onGeoQueryError(DatabaseError error) {
}
});
return true;
}
});
}
/**
* our ItemFactory implementation which creates the ViewHolder for our adapter.
* It is highly recommended to implement a ViewHolderFactory as it is 0-1ms faster for ViewHolder creation,
* and it is also many many timesa more efficient if you define custom listeners on views within your item.
*/
protected static class ItemFactory implements ViewHolderFactory<ViewHolder> {
public ViewHolder create(View v) {
return new ViewHolder(v);
}
}
/**
* return our ViewHolderFactory implementation here
*
* #return
*/
#Override
public ViewHolderFactory<? extends ViewHolder> getFactory() {
return FACTORY;
}
// Manually create the ViewHolder class
protected static class ViewHolder extends RecyclerView.ViewHolder {
TextView postedBy, userID, currentLt, currentLn, requestID, postedFrom;
TextView startDateTimeInEpoch, endDateTimeInEpoch, diffNowsdtelTV;
LinearLayout linearLayout;
long difference, differenceCurrentStartTime, handlerGap;
long startTimeDateInEpochLong2;
public static long now;
List<Long> diffNowsdtel;
Context mContext;
DatabaseReference firebaseDatabase;
GeoFire geoFireReference;
GeoQuery geoQuery;
public ViewHolder(final View itemView) {
super(itemView);
postedBy = (TextView) itemView.findViewById(R.id.postedBy);
startDateTimeInEpoch = (TextView) itemView.findViewById(R.id.startTimeDateInEpoch);
endDateTimeInEpoch = (TextView) itemView.findViewById(R.id.endTimeDateInEpoch);
diffNowsdtelTV = (TextView) itemView.findViewById(R.id.diffNowsdtelTV);
this.mContext = itemView.getContext();
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) itemView.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
}
The problem is that when I'm logging log1, I'm getting all the 3 values shown in Logcat, but when I'm logging log2 only the last calculated value is getting shown and that is the value using which filterRequests(Long l) is getting called.
Update - after updating the adapter code, log1 and log2 now shows this:
D/log1: [2197]
D/log1: [2197, -1007]
D/log1: [2197, -1007, 4003]
D/log2: [2197, -1007, 4003]
filterRequests() method is the method in which the logic to filter content based on time is done. The parameter which goes in filterRequests() is holder.diffNowsdtel which has 3 long values for now and do it should do the logic based on it.. if the long value is <=900 the content which has the long value -1007 should be shown and when long value is >900, the content which has the long value 2197 and 4003 should be shown.
here's the code:
public void filterRequests(final List<Long> l) {
final int size = l.size();
Log.d("lng", String.valueOf(l));
if (isNetworkAvailable()) {
if (chkBoxLiveRqsts.isChecked()) {
firebaseDatabase.child(key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (int i = 0; i < size; i++){
if (l.get(i) <= 900) {
...
} else {
}
}
progressDialogAdding.dismiss();
} else {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
...
});
} else if (chkBoxSFLRqsts.isChecked()) {
fastItemAdapter.clear();
firebaseDatabase.child(key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
for (int i = 0; i < size; i++) {
if (l.get(i) > 900) {
...
} else {
}
}
progressDialogAdding.dismiss();
} else {
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
...
}
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "No internet connection", Snackbar.LENGTH_SHORT);
snackbar.show();
progressDialogAdding.dismiss();
}
}
});
dialog = builder.create();
dialog.show();
}
Log value of lng:
D/lng: [2197, -1007, 4003]
What I want is that the filterRequests(Long l) method should use all the values of holder.diffNowsdtelTV.getText().toString() and do the logic using them.
I'm sorry for ambiguous question. Please help me with this issue!
What you are doing
In your ViewHolder diffNowsdtel is declared as long (which saves latest value) whenever you are logging log1 Logger displays (latest value from diffNowsdtel so your log displays different values because bindView calls many times whenever you are updating your row or complete dataset)
D/log1: -22136
D/log1: -22403
D/log1: -25094
Inside onMenuItemClick you are fetching value directly from your TextView which is now -25094 that's why you have only one value in your TextView and log says
D/log2: -25094
What you should do
Set Tag using holder.diffNowsdtelTV.setTag(your database key or row_id) and inside your onMenuItemClick get your tag using
Object someTagName = (Object) holder.diffNowsdtelTV.getTag();
Now fetch your 3 String values from the database using value stored in someTagName and then do your calculations.
Edit
Actually you need 3 values to do your calculation, while in your current logic you only have the latest value stored in diffNowsdtel. So now you need a logic to store trice your values somewhere and inside onMenuItemClick use them but if you will go to save trice your values you have to change your diffNowsdtel to long[] or List<Long> and save your every value in it on every bindView call which needs some logic so simplest way is to pass your unique database column say primary key and save it in your GRModelClass
String primaryDbKey;
public GRModelClass(String primaryDbKey, ...) {
this.primaryDbKey = primaryDbKey;
....
}
Inside your onMenuItemClick use primaryDbKey to fetch your 3 String values from your database table(which you are doing somewhere else) and then do your calculations.
Edit
You made a list with Long, both List and Long are not primitive data types.
In your question you are comparing primitive and non primitive data types, for comparison both sides of a comparator should be of same data types.
What you are doing:
if (l.get(i) <= 900)
Here l.get(i) returns a Long value where as 900 is integer value.
What you should do:
Simply compare your l.get(i) with Long by doing 900L
if (l.get(i) <= 900L)
Or
if (l.get(i) > 900L)
Try to set initialize the value you want within the onBindView
Log.d("diffNowsdtel", holder.diffNowsdtelTV.getText().toString());
final String val = holder.diffNowsdtelTV.getText().toString();
MainActivity.filterButton.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
if(holder.mContext instanceof MainActivity){
((MainActivity)holder.mContext).filterRequests(Long.parseLong(val));
Log.d("diffNowsdtel2",val);
}
return true;
}
});
You have a statically defined object called filterButton in MainActivity. Every time bindView is called for a new view, it is replacing the menu item listener for that button. So when you click that menu item, it is only calling the handler you set on for the last item that bindView was called for. That's why you only see one log entry when that filter button is pressed.

Categories

Resources