I print the milliseconds on the screen in hours, minutes, seconds. However, when I press the button, it doubles the data received with each click. For example; When 5 minutes and 10 seconds of data comes in, when I click the button again, the data appears as 10 minutes and 20 seconds. The data is multiplied by 2 each time we click the button. How can i fix that?
butondata.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String currentDateandTime = sdf.format(new Date()); startData = FirebaseDatabase.getInstance().getReference() .child("totals") .child(moTracks); PeriodHow = startData.orderByChild("availableDate").equalTo(String.valueOf(currentDateandTime)); PeriodHow.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot data : dataSnapshot.getChildren()) { if (data.child("availableDate").exists()) { long seconds = (data.getValue(SecondsPeriod.class).getDuration().getSeconds()); long minute = (data.getValue(SecondsPeriod.class).getDuration().getMinutes()); long hours = (data.getValue(SecondsPeriod.class).getDuration().getHours()); vanminit = vanminit + minute; vanhours = vanhours + hours; aggregator = aggregator + seconds; long fminute = vanminit*60*1000; long fhours = vanhours*60*60*1000; long fseconds = aggregator*1000; long asd = fhours + fminute + fseconds; if (asd < 0) { throw new IllegalArgumentException("Duration must be greater than zero!"); } long hrs = TimeUnit.MILLISECONDS.toHours(asd); asd -= TimeUnit.HOURS.toMillis(hrs); long mint = TimeUnit.MILLISECONDS.toMinutes(asd); asd -= TimeUnit.MINUTES.toMillis(mint); long scnd = TimeUnit.MILLISECONDS.toSeconds(asd); StringBuilder sb = new StringBuilder(64); sb.append(hours); sb.append(" Hours "); sb.append(mint); sb.append(" Minutes "); sb.append(scnd); sb.append(" Seconds"); timedetails.setText(sb.toString()); } } } @Override public void onCancelled(DatabaseError databaseError) { } }); } });
Advertisement
Answer
migrate these variables
vanminit = vanminit + minute; vanhours = vanhours + hours; aggregator = aggregator + seconds;
to local ones by adding long
before each
long vanminit = vanminit + minute; long vanhours = vanhours + hours; long aggregator = aggregator + seconds;
don’t keep them class available (declared on top of file above moethods), as they accumulate on each onDataChange
call
btw. asd
or fseconds
aren’t best variable names…
edit: if you want to store these values in class to be available for other methods then just copy them to class-available variables
long vanminit = vanminit + minute; long vanhours = vanhours + hours; long aggregator = aggregator + seconds; vanminitGlobal = vanminit; vanhoursGlobal = vanhours; aggregatorGlobal = aggregator;
in other methods use Global
variables