Я пытаюсь преобразовать этот sql запрос «Выберите значение из чтения, где дата начинается в date1 и заканчивается в date2» и сохраняет возвращаемое значение в списке массивов, а затем в конце вычисляет сумму значений в списке массивов. Моя проблема, когда я пытаюсь получить пустой Arraylist, в нем ничего не хранится. Вот как выглядит моя база данных:
{
"Reading" : {
"-M9y4MCbVmVLeIUpyJTe" : {
"bill" : 1.00009,
"date" : "2020-06-16",
"time" : "19-02-55",
"value" : 3.0E-4
},
"-M9y4NVCG4qv2e_FtfM2" : {
"bill" : 1.00021,
"date" : "2020-06-16",
"time" : "19-03-01",
"value" : 7.0E-4
},
"-M9y4Omy7rc-e7ysolWM" : {
"bill" : 1.0003,
"date" : "2020-06-16",
"time" : "19-03-06",
"value" : 0.001
},
"-M9y4PYwi17ia9gORjsv" : {
"bill" : 1.00039,
"date" : "2020-06-16",
"time" : "19-03-09",
"value" : 0.0013
}
}
Это мой код Back-end:
package com.example.datepicker;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends Activity implements OnClickListener {
private EditText fromDateEtxt;
private EditText toDateEtxt;
private TextView datetxtview,totaltxt;
private Button calculate;
private DatePickerDialog fromDatePickerDialog;
private DatePickerDialog toDatePickerDialog;
private ListView listview;
private SimpleDateFormat dateFormatter;
private char datte1[];
private Float sum= Float.valueOf(0);
private DatabaseReference readingdatabase;
private ArrayList<Float> totalAmount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalAmount=new ArrayList<>();
dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
findViewsById();
setDateTimeField();
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
String d1 = fromDateEtxt.getText ().toString ();
String d2 = toDateEtxt.getText ().toString ();
fromDateEtxt.setOnClickListener(this);
toDateEtxt.setOnClickListener(this);
Date date1 = dateFormatter.parse(d1);
Date date2 = dateFormatter.parse(d2);
d1=String.valueOf(date1);
d2=String.valueOf(date2);
long difference = Math.abs(date1.getTime() - date2.getTime());
long difftDays = difference / (24 * 60 * 60 * 1000);
FirebaseDatabase database = FirebaseDatabase.getInstance();
readingdatabase=database.getReference("Reading");
Query query;
query = readingdatabase.orderByChild("date").startAt("2020-06-16");
query.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
String ID=dataSnapshot.getKey();
Float value=dataSnapshot.child(ID).child("value").getValue(Float.class);
sum+=value;
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
/* Query query =FirebaseDatabase.getInstance().getReference().orderByValue()
.startAt("2020-06-16");
query.addListenerForSingleValueEvent(valueEventListener);
*/
/*Float sum=Float.parseFloat("0");
for(int i =0;i< totalAmount.size();i++){
sum+=totalAmount.get(i);
}*/
Log.i("Testing","days" +difftDays);
datetxtview.setText("days : " +difftDays );
totaltxt.setText(" Total Readings : "+String.valueOf(sum));
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
}
private void findViewsById() {
fromDateEtxt = (EditText) findViewById(R.id.etxt_fromdate);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
datetxtview=findViewById(R.id.datetextview);
calculate=findViewById(R.id.calculatebtn);
toDateEtxt = (EditText) findViewById(R.id.etxt_todate);
toDateEtxt.setInputType(InputType.TYPE_NULL);
totaltxt=findViewById(R.id.totaltxt);
}
private void setDateTimeField() {
fromDateEtxt.setOnClickListener(this);
toDateEtxt.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
toDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
toDateEtxt.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
@Override
public void onClick(View view) {
if (view == fromDateEtxt) {
fromDatePickerDialog.show();
} else if (view == toDateEtxt) {
toDatePickerDialog.show();
}
}
ValueEventListener valueEventListener=new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Float value= snapshot.child("value").getValue(Float.class);
totalAmount.add(value);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
}