Reputation: 25
As the image shows, my list is not being sorted according date and time
RecyclerView Image and this is my firebase structure
Add Appointment.java -> this is how i add my data to firebase
public class AddAppointment extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseUser mCurrentUser;
private EditText dateApp,timeApp,nameTxt,addressTxt,telTxt;
int mYear,mMonth,mDay,mHour,mMinute;
private Button saveBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_appointment);
Firebase.setAndroidContext(this);
nameTxt = (EditText) findViewById(R.id.nameText);
addressTxt= (EditText) findViewById(R.id.addressText);
telTxt = (EditText) findViewById(R.id.telText);
dateApp = (EditText)findViewById(R.id.dateAppointment);
timeApp = (EditText)findViewById(R.id.timeAppointment);
dateApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
datePic();
}
});
timeApp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
timePic();
}
});
saveBtn = (Button)findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firebaseAuth = FirebaseAuth.getInstance();
mCurrentUser = firebaseAuth.getCurrentUser();
DatabaseReference db= FirebaseDatabase.getInstance().getReference().child("Email").child(mCurrentUser.getUid()).child("Appointment").push();
String name = nameTxt.getText().toString().trim();
String address = addressTxt.getText().toString().trim();
String tel = telTxt.getText().toString().trim();
String date = dateApp.getText().toString().trim();
String time = timeApp.getText().toString().trim();
//Adding values
db.child("name").setValue(name);
db.child("address").setValue(address);
db.child("tel").setValue(tel);
db.child("date").setValue(date);
db.child("time").setValue(time);
//Storing values to firebase
Toast.makeText(AddAppointment.this,"Saved",Toast.LENGTH_SHORT).show();
Intent mainIntent = new Intent(AddAppointment.this,MainActivity.class);
startActivity(mainIntent);
}
});
}
public void datePic()
{
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
mYear = year;
mMonth = monthOfYear+1;
mDay = dayOfMonth;
dateApp.setText((mDay+"-"+mMonth+"-"+mYear));
}
},mDay,mMonth,mYear);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.show();
}
public void timePic()
{
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
int hour = hourOfDay % 12;
timeApp.setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
minute, hourOfDay < 12 ? "a.m." : "p.m."));
}
},mHour,mMinute,false);
timePickerDialog.show();
}
}
AppointmentData.java -> this is my data setup
public class AppointmentData {
private String name,tel,address,time,date;
public AppointmentData() {
}
public void setName(String name) {
this.name = name;
}
public void setTel(String tel) {
this.tel = tel;
}
public void setAddress(String address) {
this.address = address;
}
public void setTime(String time) {
this.time = time;
}
public void setDate(String date) {
this.date = date;
}
public AppointmentData(String name, String tel, String address, String time, String date) {
this.name=name;
this.tel=tel;
this.address=address;
this.time=time;
this.date=date;
}
public String getName() {
return name;
}
public String getTel() {
return tel;
}
public String getAddress() {
return address;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
ViewAppointment.java -> this is how i display my recyclerview
public class ViewAppointment extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseUser mCurrentUser;
private DatabaseReference db;
private RecyclerView recyclerView;
private FirebaseRecyclerAdapter<AppointmentData,myViewHolder> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_appointment);
recyclerView=(RecyclerView)findViewById(R.id.recycle);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
firebaseAuth = FirebaseAuth.getInstance();
mCurrentUser = firebaseAuth.getCurrentUser();
db= FirebaseDatabase.getInstance().getReference().child("Email").child(mCurrentUser.getUid()).child("Appointment");
db.keepSynced(true);
mAdapter= new FirebaseRecyclerAdapter<AppointmentData, myViewHolder>(
AppointmentData.class,R.layout.model,myViewHolder.class,db
) {
@Override
protected void populateViewHolder(final myViewHolder viewHolder, final AppointmentData model, final int position) {
viewHolder.nameTxt.setText(model.getName());
viewHolder.dateApp.setText(model.getDate());
viewHolder.timeApp.setText(model.getTime());
viewHolder.mapBtn.setText("Map");
viewHolder.detailBtn.setText("Detail");
viewHolder.deleteBtn.setText("Delete");
viewHolder.editBtn.setText("Edit");
Log.e("myFirebase UID", mAdapter.getRef(position).getKey());
viewHolder.editBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), UpdateAppointment.class);
i.putExtra("NAME_KEY",model.getName());
i.putExtra("ADDRESS_KEY",model.getAddress());
i.putExtra("TEL_KEY",model.getTel());
i.putExtra("DATE_KEY",model.getDate());
i.putExtra("TIME_KEY",model.getTime());
view.getContext().startActivity(i);
Log.e("Item Click position",""+position);
mAdapter.getRef(+position).removeValue();
}
});
viewHolder.detailBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailActivity.class);
i.putExtra("NAME_KEY",model.getName());
i.putExtra("ADDRESS_KEY",model.getAddress());
i.putExtra("TEL_KEY",model.getTel());
i.putExtra("DATE_KEY",model.getDate());
i.putExtra("TIME_KEY",model.getTime());
view.getContext().startActivity(i);
}
});
viewHolder.mapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), Distance.class);
i.putExtra("ADDRESS_KEY",model.getAddress());
view.getContext().startActivity(i);
}
});
viewHolder.deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e("Item Click position",""+position);
mAdapter.getRef(+position).removeValue();
}
});
}
};
recyclerView.setAdapter(mAdapter);
}
public static class myViewHolder extends RecyclerView.ViewHolder{
private TextView nameTxt,dateApp,timeApp;
private Button detailBtn,mapBtn,deleteBtn,editBtn;
public myViewHolder(View itemView){
super(itemView);
nameTxt=(TextView)itemView.findViewById(R.id.nameTxt);
dateApp= (TextView) itemView.findViewById(R.id.dateAppointment);
timeApp=(TextView)itemView.findViewById(R.id.timeAppointment);
mapBtn = (Button) itemView.findViewById(R.id.mapBtn);
detailBtn = (Button) itemView.findViewById(R.id.detailBtn);
deleteBtn = (Button) itemView.findViewById(R.id.deleteBtn);
editBtn = (Button) itemView.findViewById(R.id.editBtn);
}
}
}
Upvotes: 2
Views: 15064
Reputation: 11
you can use kotlin lamda with comparable interface to compare date to sort out list. first implement compareable interface in your list type model then use Collection.Sort(Listname)
vaccinationTypesList.sortWith { o1, o2 ->
o1.vaccinationDate
.compareTo(o2.vaccinationDate)
}
Upvotes: 0
Reputation: 41
I had made a food delivery app and in which the order history is storing date wise as you can see Order History First just look at my database Database
now if you look my database carefully you will get the logic behind that.Logic is simple instead of using RandomUId = UUID.randomUUID().toString();
I had use RandomUId = getrandoumUID();
where getrandoumUID()
is
public String getrandoumUID(){
Calendar cr = Calendar.getInstance();
SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Date todayr = cr.getTime();
String dater = sdfr.format(todayr);
return dater;
}
When you are storing data to firebase instead of using random uid just use this method. Now when you retrive this data normally in recyclerview it will retrive in opposite order, to ensure that just add each item in the list at '0'th index
ArrayList.add(0,item);
adapter.notifyDataSetChanged();
Make sure to declare below steps in OnCreate()
function
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(Activity.this));
ArrayList= new ArrayList<>();
adapter = new Adapter(Activity.this,ArrayList);
recyclerView.setAdapter(adapter);
Upvotes: 0
Reputation: 2635
Change make following changes to your AppointmentData
public class AppointmentData {
// ...
private Object date;
// ...
public void setDate(Object date) {
this.date = date;
}
// ...
public AppointmentData(String name, String tel, String address, String time, Object date) {
// ...
}
// ...
public Object getDate() {
return date;
}
}
Change db to this:
Query db = FirebaseDatabase.getInstance().getReference().child("Email").child(mCurrentUser.getUid()).child("Appointment").orderByChild("date");
Change this line inside populateViewHolder to this: viewHolder.dateApp.setText(timestampToDateString(model.getDate()));
where timestampToDateString is a utility method:
public static String timestampToDateString(long timestamp){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date(timestamp);
return dateFormat.format(date);
}
change btnSave.onClickListener to this
final String key = FirebaseDatabase.getInstance().getReference().child("Email").child(mCurrentUser.getUid()).child("Appointment").push().getKey();
// ...
Long date = mSelectedDate;
// ...
AppointmentData appointmentData = new AppointmentData(name, tel, address, time, date);
FirebaseDatabase.getInstance().getReference().child("Email").child(mCurrentUser.getUid()).child("Appointment").child(key).setValue(appointmentData);
// ...
add the field like so
private long mSelectedDate;
initialize it in datePic() like so
// ...
mYear = c.get(Calendar.YEAR);
// ...
mSelectedDate = fieldToTimestamp(mYear, mMonth, mDay);
and in onDateSelectedListener.onDateSet(...) like so
// ...
mSelectedDate = fieldToTimestamp(year, monthOfYear, dayOfMonth);
where fieldToTimestamp is helper method
private long fieldToTimestamp(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
return (long) (calendar.getTimeInMillis() / 1000L);
}
I think that should be all of it.. Oh, and delete all your old Appointments so it doesn't cause exceptions.
Upvotes: 1
Reputation: 3954
This is sample which can solve your problem
// above i have store date in millisecond formate.
ref.child("date").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<Long> d = new ArrayList<>();
for (DataSnapshot child : dataSnapshot.getChildren()) {
// save all millis in array list you can take your Bean class also
try {
long daa = Long.parseLong(child.getValue().toString());
d.add(daa);
} catch (Exception e) {
e.printStackTrace();
}
}
// sort array list you can use comparator if you have bean class
Collections.sort(d);
for (int i = 0; i < d.size(); i++) {
String dateString = new SimpleDateFormat("dd-MM-yyyy").format(new Date(d.get(i)));
Log.e("!_@@ date", dateString + "");
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("!!__: ", "onCancelled ", firebaseError.toException());
}
});
output is :-
14-01-1970
26-01-1970
06-03-1970
14-04-1970
Upvotes: 0