Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 792
Hammad Nasir Avatar asked Dec 01 '16 13:12

Hammad Nasir


2 Answers

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)
like image 133
Haris Qurashi Avatar answered Oct 30 '22 12:10

Haris Qurashi


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;
                }
            });
like image 35
Niza Siwale Avatar answered Oct 30 '22 10:10

Niza Siwale