I'm trying to display data from firebase using dates. But I only know how to display data for the current date. I would like to change the dates so I can display data from firebase with different dates. The current code I have is only displaying the data on a recyclerView from 8-9-2020. I would like to get the data from the previous day which is 7-9-2020.
firebaseAuth= FirebaseAuth.getInstance();
FirebaseUser user = firebaseAuth.getCurrentUser();
calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String currentDate = sdf.format(calendar.getTime());
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(currentDate);
buttonCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCalendar();
}
});
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
theDate.setText(date);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(#NonNull CalendarView view, int year, int month, int dayOfMonth) {
month = month +1;
String date = String.format("%02d-%02d-%d", dayOfMonth, month, year);
Intent intent = new Intent(CalendarActivity.this, Breakfast.class);
intent.putExtra("date", date);
startActivity(intent);
}
});
What I'm trying to do is it will display the current date data, then when I select a new date from the calendar, it will retrieve data of the newly selected date.
I would like to somehow update the .child(currentDate) to .child(date) in which the date contains the newly selected date.
As per your code, you're opening a calendar in the new activity I can suggest if you want to use android DatePickerDialog to get a date in the same activity.
And if you want to get a date back from a particular activity you can use a startActivityForResult(yourIntent,request_code); and get result and data in
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
And after getting a successful result you can use the below method to get your firebase data.
private void getFirebaseData(String date){
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(date);
// rest is your code
}
I figured out simple way to do it:
setDate();
String date = setDate();
if (date == null || date.equals("")){
date = currentDate;
}
mDatabase = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("food").child(date);
made a method for setting the new date:
public String setDate(){
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
theDate.setText(date);
return date;
}
Related
I did everything when it comes to creating notification on selected time in timepicker but I cannot pass it to textview in another activity. Can someone help me with this?
I want to pass time value from SecondActivity to textView named textviewAlarm in HomeActivity when clicking button Done.
public class Second extends AppCompatActivity implements View.OnClickListener{
private int notificationId = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
// Set Onclick Listener.
findViewById(R.id.setBtn).setOnClickListener(this);
findViewById(R.id.cancelBtn).setOnClickListener(this);
}
#Override
public void onClick(View view) {
EditText editText = findViewById(R.id.editText);
TimePicker timePicker = findViewById(R.id.timePicker);
// Set notificationId & text.
Intent intent = new Intent(Second.this, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("todo", editText.getText().toString());
// getBroadcast(context, requestCode, intent, flags)
PendingIntent alarmIntent = PendingIntent.getBroadcast(Second.this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
switch (view.getId()) {
case R.id.setBtn:
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
// Create time.
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, 0);
long alarmStartTime = startTime.getTimeInMillis();
// Set alarm.
// set(type, milliseconds, intent)
alarm.set(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmIntent);
// Get TextView object which is used to show user pick date and time.
TextView textView = (TextView)findViewById(R.id.textViewAlarm);
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("You selected date time : ");
strBuffer.append(this.notificationId);
textView.setText(strBuffer.toString());
break;
case R.id.cancelBtn:
alarm.cancel(alarmIntent);
Toast.makeText(this, "Canceled.", Toast.LENGTH_SHORT).show();
break;
}
}
}
I want my selected time to be shown in textViewAlarm in HomeActivity.
You can get the time from the time picker by adding a
timePicker.setOnTimeChangedListener( new TimePicker.onTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
time = String.valueOf(hourOfDay).toString() + ":" + String.valueOf(minute).toString();
}
}
When the user changes the time it will assign the time to a variable and pass that argument through intent as follow
Intent intent = new Intent(Second.this, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("time", time);
Take that passed argument from the HomeActivity and set it to the TextView as follow
textviewAlarm.setText(time.toSring());
I have a timePicker
String mName = input.getText().toString();
if (input.getParent() != null)
((ViewGroup) input.getParent()).removeView(input);
if (layout.getParent() != null)
((ViewGroup) layout.getParent()).removeView(layout);
mAlertDialog.dismiss();
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(Chat.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
Toast.makeText(getApplicationContext(), "Make sure you have internet access at this time selected",
Toast.LENGTH_LONG).show();
}
}, hour, minute, true);// Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
I want a method to execute at the time picked by the user. How can i achieve this. Say i want to change a particular data in firebase at the given time how can i do that? Please help me out
I have a problem - I am making an app, and I want to add a new event to User's Calendar (I have a S Planner so I'm testing on it) on button click. The problem is when it comes to date and time - it just doesn't change. Here's code:
bCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent calintent = new Intent(Intent.ACTION_INSERT);
calintent.setType("vnd.android.cursor.item/event");
calintent.putExtra(CalendarContract.Events.TITLE, eventname);
calintent.putExtra(CalendarContract.Events.EVENT_LOCATION, city + ", " + street);
calintent.putExtra(CalendarContract.Events.DESCRIPTION, description);
calintent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, timestart);
startActivity(calintent);
}
});
timestart is a string which was passed through the other activity, for example "15:00".
I want to insert data from my activity into Samsung's S Planner. I have no problem with inserting everything except for date and time. Screenshot Nothing changes there. If you need any further details, please tell.
Managed to do it thanks to Selvin's pointing out my mistake.
Made a string containing date and time and converted it using SimpleDateFormat
to long.
bCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent calintent = new Intent(Intent.ACTION_INSERT);
String dateString = datestart+" "+timestart;
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try{
Date d = f.parse(dateString);
long millis = d.getTime();
calintent.setType("vnd.android.cursor.item/event");
calintent.putExtra(CalendarContract.Events.TITLE, eventname);
calintent.putExtra(CalendarContract.Events.EVENT_LOCATION, city + ", " + street);
calintent.putExtra(CalendarContract.Events.DESCRIPTION, description);
calintent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, millis);
startActivity(calintent);
} catch(ParseException e){
e.printStackTrace();
}
I am having some problem when trying to do a recurring task in Android. Here is how I populate my list view:
public View getView(int position, View convertView, ViewGroup parent) {
String recurID;
if (convertView == null) {
convertView = inflater.inflate(R.layout.recur_listview_row, null);
viewHolder = new ViewHolder();
viewHolder.txt_ddate = (TextView) convertView.findViewById(R.id.txtDisplayRecurDate);
viewHolder.txt_damount = (TextView) convertView.findViewById(R.id.txtDisplayRecurAmount);
viewHolder.txt_dfrequency = (TextView) convertView.findViewById(R.id.txtDisplayFrequency);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
recurID = _recurlist.get(position).getRecurringID();
// Format and calculate the next payment date based on frequency
try {
String dateStr = _recurlist.get(position).getRecurringStartDate();
String frequencyStr = _recurlist.get(position).getFrequency();
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormat.parse(dateStr));
if (frequencyStr.equals("Daily")) {
cal.add(Calendar.DAY_OF_MONTH, 1);
viewHolder.txt_ddate.setText("Next Payment On: " + dateFormat.format(cal.getTimeInMillis()));
cal.add(Calendar.DAY_OF_MONTH, -1);
} else if (frequencyStr.equals("Weekly")) {
cal.add(Calendar.WEEK_OF_YEAR, 1);
viewHolder.txt_ddate.setText("Next Payment On: " + dateFormat.format(cal.getTimeInMillis()));
cal.add(Calendar.WEEK_OF_YEAR, -1);
}
} catch (ParseException e) {
e.printStackTrace();
}
viewHolder.txt_dfrequency.setText(_recurlist.get(position).getFrequency().trim());
if (_recurlist.get(position).getRecurringType().equals("W")) {
viewHolder.txt_damount.setTextColor(Color.rgb(180, 4, 4));
viewHolder.txt_damount.setText("Credit $ " + amount);
} else if (_recurlist.get(position).getRecurringType().equals("D")) {
viewHolder.txt_damount.setTextColor(Color.rgb(8, 138, 8));
viewHolder.txt_damount.setText("Debit $ " + amount);
}
// Get current date
String currentDate = "Next Payment On: " + dateFormat.format(new Date());
// If current date matches with the next payment date, insert new
// transaction record
if (currentDate.equals(viewHolder.txt_ddate.getText())) {
DatabaseAdapter mDbHelper = new DatabaseAdapter(Recurring.this);
mDbHelper.createDatabase();
mDbHelper.open();
TransactionRecModel trm = new TransactionRecModel();
CategoryController cc = new CategoryController(mDbHelper.open());
trm.setDate(dateFormat.format(new Date()));
if (_recurlist.get(position).getRecurringType().equals("W")) {
trm.setType("W");
} else if (_recurlist.get(position).getRecurringType().equals("D")) {
trm.setType("D");
}
trm.setAmount(Float.parseFloat(formatAmount));
TransactionRecController trc = new TransactionRecController(mDbHelper.open());
if (trc.addTransactionRec(trm)) {
// After successfully insert transaction record, update the
// recurring start date
rm = new RecurringModel();
rm.setRecurringID(recurID);
rm.setRecurringStartDate(dateFormat.format(new Date()));
RecurringController rc = new RecurringController(mDbHelper.open());
if (rc.updateRecurringDate(rm)) {
mDbHelper.close();
}
}
}
return convertView;
}
From the code I tried to get the current date and compare with the next payment date computed based on frequency. However, with these code, it does not run in background.
Let's say I set a recurring event which will be repeating daily yesterday. But I did not run the application today. By right, the recurring should run in background and execute the recurring. But somehow, it does not.
I wonder do I need some service like AlarmManager to do this?
Thanks in advance.
EDIT
So what I've changed is the part when I try to compare the dates, if the dates matched, it will call the alarmManager and parse some values along the way:
if (currentDate.equals(viewHolder.txt_ddate.getText())) {
long when = new Date().getTime();
notificationCount = notificationCount + 1;
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context, ReminderAlarm.class);
notificationIntent.putExtra("RecurID", recurID);
notificationIntent.putExtra("Date", dateFormat.format(new Date()));
notificationIntent.putExtra("Description", viewHolder.txt_ddesc.getText().toString());
notificationIntent.putExtra("Type", _recurlist.get(position).getRecurringType());
notificationIntent.putExtra("Amount", Float.parseFloat(formatAmount));
notificationIntent.putExtra("CategoryID", viewHolder.txt_dcat.getText().toString());
notificationIntent.putExtra("NotifyCount", notificationCount);
PendingIntent pi = PendingIntent.getBroadcast(context, notificationCount, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.set(AlarmManager.RTC_WAKEUP, when, pi);
}
And in my ReminderAlarm class, I am executing the insert and update SQL statement:
public class ReminderAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String recurID = intent.getStringExtra("RecurID");
String date = intent.getStringExtra("Date");
String description = intent.getStringExtra("Description");
String type = intent.getStringExtra("Type");
Float amount = Float.parseFloat(intent.getStringExtra("Amount"));
String categoryID = intent.getStringExtra("CategoryID");
DatabaseAdapter mDbHelper = new DatabaseAdapter(ReminderAlarm.this);
mDbHelper.createDatabase();
mDbHelper.open();
TransactionRecModel trm = new TransactionRecModel();
CategoryController cc = new CategoryController(mDbHelper.open());
trm.setDate(date);
trm.setTransDescription(description);
if (type.equals("W")) {
trm.setType("W");
} else if (type.equals("D")) {
trm.setType("D");
}
trm.setAmount(amount);
// Get the categoryID based on categoryName
String catID = cc.getCatIDByName(categoryID);
trm.setCategory(catID);
TransactionRecController trc = new TransactionRecController(mDbHelper.open());
if (trc.addTransactionRec(trm)) {
// After successfully insert transaction record, update the
// recurring start date
RecurringModel rm = new RecurringModel();
rm.setRecurringID(recurID);
rm.setRecurringStartDate(date);
RecurringController rc = new RecurringController(mDbHelper.open());
if (rc.updateRecurringDate(rm)) {
mDbHelper.close();
}
}
}
}
Your Adapter should receive data that is ready to be displayed. getView is called every time a ListView item comes onto screen, so you want to keep your work here to under 16ms if you hope to maintain 60fps scrolling. Because of this, you should do all heavy work before it gets to the Adapter.
Since database data is often not display-ready, you would typically use a Loader to get the data, and turn it into a list of "items" that are Adapter-ready. This should happen in your Activity or Fragment, and you fill the Adapter in onLoadFinished. This often means creating a new POJO to represent the display data.
Best place to start is the Loader tutorial.
If you want to set a recurring task, you should use the AlarmManager, as you suspected. The AlarmManager would typically trigger a BroadcastManager, which in turn would spawn a Service to do the work.
Follow the AlarmManager tutorial for more details.
I have this code from where I can set a time and date from date picker and time picker at once:
private void dialoguetime() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialogue);
dialog.setCancelable(true);
dialog.setTitle("This is Dialog 1");
dialog.show();
TimePicker time_picker = (TimePicker) dialog
.findViewById(R.id.timePicker1);
hours = time_picker.getCurrentHour();
minute = time_picker.getCurrentMinute();
time_picker.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay,
int minutes) {
// TODO Auto-generated method stub
// Toast.makeText(CustomDialog.this,
// "hourOfDay = "+hourOfDay+"minute = "+minute , 1000).show();
hours = hourOfDay;
minute = minutes;
}
});
final DatePicker date_picker = (DatePicker) dialog
.findViewById(R.id.datePicker1);
Button btn = (Button) dialog.findViewById(R.id.button2);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
xDate = date_picker.getYear() + "-"+ (date_picker.getMonth() + 1) + "-"+ date_picker.getDayOfMonth() + " " + hours+ ":" + minute + ":00";
Toast.makeText(
getApplicationContext(),
xDate, Toast.LENGTH_LONG)
.show();
dialog.cancel();
}
}
);
}
From this I can get a string as a date format like this yyyy-mm-dd hh:mm:ss, now I want to give an alert (as alarm) to the user of that selected time. I have used alarm manager for this but it didn't allow me to select that date?
How can I do this?
If you look at the API for AlarmManager (http://developer.android.com/reference/android/app/AlarmManager.html) you can see that the method
set()
requires the following parameters:
public void set (int type, long triggerAtMillis, PendingIntent operation)
where
int type = One of ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC or RTC_WAKEUP.
long triggerAtMillis = time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type).
PendingIntent operation = Action to perform when the alarm goes off
So basicly what you should do, is to get the time between the selected date (DateFormat.parse() to parse the date-formated string to date) and the current date. Something like this:
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date parsedDate = format.parse(YOUR_PICKED_DATE_AS_STRING);
long alertTime = parsedDate.getTime() - now.getTime();
Intent someIntent = new Intent(getApplicationContext(), YourClass.class);
PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), 0, someIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.