There are three buttons like prev, next, today. If you click on them, the data should go to the string containing calender data formattedDate. String formattedDate = df.format(c.getTime());
`prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1);
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
}
});
private void requestHomeData2() {
ApiInterface apiInterface = RestAdapter.createAPI(sharedPref.getApiUrl());
callbackCall2 = apiInterface.getDate(formattedDate,AppConfig.REST_API_KEY);
this.callbackCall2.enqueue(new Callback<Callbackdate>() {
public void onResponse(Call<Callbackdate> call, Response<Callbackdate> response) {
Callbackdate responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
onFailRequest();
return;
}
displayData2(responseHome);
swipeProgress(false);
lyt_main_content.setVisibility(View.VISIBLE);
}
public void onFailure(Call<Callbackdate> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
onFailRequest();
}
}
});
}``
FormattedDate error how to fix this error image
Use this two line above the error line.
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
Related
I want to send the user notification on that particular time and date after the user choose it while adding a new task. I want to get the notification title and description from the Firebase database and I want to display notification for every individual task.
Here is my code (HOW USER SELECT THE TIME AND DATE)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser () ;
OnlineUserID = mUser.getUid() ;
// Other Features Stuff
long Sysdate = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
String dateString = sdf.format(Sysdate);
timePickerBTN = findViewById(R.id.TimePickerBTN);
datePickerBTN = findViewById(R.id.DatePickerBTN);
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("dd/MM/yy");
date = (String) android.text.format.DateFormat.format("hh:mm aa", calendar);
timePickerBTN.setText(date);
datePickerBTN.setText(dateString);
timePickerBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TimePickerDialog timePickerDialog = new TimePickerDialog(NewTaskActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hourOfDay, int Minute) {
TimeHour = hourOfDay;
TimeMinute = Minute;
Calendar calendarTime = Calendar.getInstance();
calendarTime.set(0,0,0, TimeHour, TimeMinute);
timePickerBTN.setText(android.text.format.DateFormat.format("hh:mm aa", calendarTime));
FINAL_TIME = timePickerBTN.getText().toString();
}
},12,0,false);
timePickerDialog.updateTime(TimeHour, TimeMinute);
timePickerDialog.show();
}
});
AND THE FOLLOWING CODE IS FOR SENDING DATA TO FIREBASE
DBrefrence = FirebaseDatabase.getInstance().getReference().child("tasks").child(OnlineUserID);
pdLoader = new ProgressDialog(this);
final EditText tskTitle = findViewById(R.id.taskTitle);
final EditText tskDescription = findViewById(R.id.taskDescription);
Button saveButton = findViewById(R.id.SaveTask_BTN);
datePickerBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment datePicker = new com.veria.task.DatePicker();
datePicker.show(getSupportFragmentManager() ,"Pick a date");
}
});
saveButton.setOnClickListener((v) -> {
String mTask = tskTitle.getText().toString().trim();
String mDescription = tskDescription.getText().toString().trim();
String id = DBrefrence.push().getKey();
if (currentDate == null)
{
dateCurrentSelected = DateFormat.getDateInstance().format(new Date());
}
else if (currentDate!= null)
{
dateCurrentSelected = currentDate;
}
if (FINAL_TIME == null)
{
TimeCurrent = timePickerBTN.getText().toString();
}
else if (FINAL_TIME != null)
{
TimeCurrent = FINAL_TIME;
}
String Time = FINAL_TIME;
if (TextUtils.isEmpty(mTask))
{
tskTitle.setError("Title Required");
return;
}
if (TextUtils.isEmpty(mDescription))
{
tskDescription.setError("Description Required");
return;
}
else
{
pdLoader.setTitle("Task");
pdLoader.setMessage("Please wait");
pdLoader.setCanceledOnTouchOutside(false);
pdLoader.show();
Model model = new Model(mTask, mDescription, id, dateCurrentSelected, TimeCurrent);
DBrefrence.child(id).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Intent intent = new Intent(NewTaskActivity.this, MainActivity.class);
startActivity(intent);
finish();
Toast.makeText(NewTaskActivity.this, "Task has been successfully added", Toast.LENGTH_SHORT).show();
pdLoader.dismiss();
}
else
{
Toast.makeText(NewTaskActivity.this, "Failed To Add Task", Toast.LENGTH_SHORT).show();
pdLoader.dismiss();
}
}
});
}
});
I don't know how to send notification on the time and date selected by user
If next button is clicked, its data should go to formattedDate I have tried several times and it keeps giving me an error.
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, +1);
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(c.getTime());
textView.setText(formattedDate);
post.recipe_time = formattedDate;
}
});
this formattedDate error how to clear
private void requestHomeData2() {
ApiInterface apiInterface =
RestAdapter.createAPI(sharedPref.getApiUrl());
callbackCall2 =
apiInterface.getDate(formattedDate,AppConfig.REST_API_KEY);
this.callbackCall2.enqueue(new Callback<Callbackdate>() {
public void onResponse(Call<Callbackdate> call,
Response<Callbackdate> response) {
Callbackdate responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
onFailRequest();
return;
}
displayData2(responseHome);
swipeProgress(false);
lyt_main_content.setVisibility(View.VISIBLE);
}
public void onFailure(Call<Callbackdate> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
onFailRequest();
}
}
});
}
Set your String formattedDate variable as global variable and initialize it like String formattedDate = "", then assign value formattedDate = df.format(c.getTime()); in your next button click and then invoke requestHomeData2 wherever you need it.
Hi in the below I am displaying calendarview.In calendarview I am selecting date and passing that date to GetAppointmentDate(selecteddate) if selecteddate and my date matches I am displaying gridview layout.but it is give multiple list with below .
Can any one help y duplicate list is displaying evrytime.
CalendarViewActivity.java:
public class CalendarViewActivity extends Activity implements DatetimeAdapter.MyItemClickListener{
private CalendarView mCalendarView;
private ProgressDialog progressDialog = null;
private ArrayList<GetData> getDataArrayList;
private ArrayList<GetSlots> getSlotsArrayList;
private GridView gridLayout;
private GetData getData2;
private GetSlots getSlots2;
private String Id,StartTime,SlotBooked,SlotDate,EndTime,SloteTime;
private DatetimeAdapter datetimeAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_view);
gridLayout=findViewById(R.id.gridlayout);
getDataArrayList=new ArrayList<>();
getSlotsArrayList=new ArrayList<>();
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
mCalendarView.setMinDate(System.currentTimeMillis() - 1000);
datetimeAdapter = new DatetimeAdapter(getApplicationContext(), getSlotsArrayList,this);
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
Calendar calendar = Calendar.getInstance();
int year1 = calendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH);
int dayOfMonth1 = calendar.get(Calendar.DAY_OF_MONTH);
#Override
public void onSelectedDayChange(CalendarView CalendarView, int year1, int month1, int dayOfMonth1) {
String date = new SimpleDateFormat("MM", Locale.getDefault()).format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat(date);
String selecteddate = (sdf.format(month1 + 1)) + "/" + dayOfMonth1 + "/" + year1;
GetAppointmentDate(selecteddate);
Toast.makeText(getApplicationContext(),selecteddate,Toast.LENGTH_LONG).show();
}
});
}
private void GetAppointmentDate(String outputcurrentdate) {
// progressDialog = new ProgressDialog(getApplicationContext());
// progressDialog.setIndeterminate(true);
// progressDialog.setMessage("Loading...");
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
String doctor_ids="13";
String HospitalId="PH:193";
final APIService service = RetroClass.getRetrofitInstance().create(APIService.class);
Call<GetAppointmentDateModel> call = service.GetAppointmentDate(doctor_ids,HospitalId);
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<GetAppointmentDateModel>() {
#Override
public void onResponse(Call<GetAppointmentDateModel> call, Response<GetAppointmentDateModel> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
GetAppointmentDateModel getAppointmentDateModel = response.body();
ArrayList<GetData> getData = getAppointmentDateModel.getGetAppointmentList();
for (GetData getData1 : getData) {
String date1 = getData1.getDate();
String id=getData1.getId();
DateFormat inputFormatter = new SimpleDateFormat("dd MMM yyyy HH:mm-HH:mm");
Date date = null;
try {
date = inputFormatter.parse(date1);
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date);
getData2=new GetData(id,output);
getDataArrayList.add(getData2);
Log.d("dateString",output);
ArrayList<GetSlots> getSlots = getData1.getData();
for (GetSlots getSlots1 : getSlots) {
Id=getSlots1.getId();
SlotDate=getSlots1.getDate();
StartTime=getSlots1.getStartTime();
EndTime=getSlots1.getEndTime();
SloteTime=getSlots1.getSlotTime();
SlotBooked=getSlots1.getSlotBooked();
getSlots2=new GetSlots(Id,SlotDate,StartTime,EndTime,SlotBooked,SloteTime);
getSlotsArrayList.add(getSlots2);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
String current_date=getData2.getDate();
if(current_date.equals(outputcurrentdate)) {
gridLayout.setAdapter(datetimeAdapter);
datetimeAdapter.notifyDataSetChanged();
}
}
// progressDialog.dismiss();
}
#Override
public void onFailure(Call<GetAppointmentDateModel> call, Throwable t) {
Log.d("error", t.getMessage());
// progressDialog.dismiss();
}
});
}
#Override
public void myItemClick(int position) {
}
}
Your list - getSlotsArrayList is addding new values each time and it is not clearing anywhere. This is the same list that is passed to the adapter. so it is displaying multiple values.
Call clear method before this
getSlotsArrayList.clear();
GetAppointmentDate(selecteddate);
I have two datepickers in my activity.
I want startdate of datePickerB dialog to be updated automatically based on date selected in datePickerA dialog.
I use setMinDate for datePickerB. setMinDate works fine for the very first time. But couldn't update or reset the mindate of datePickerB for consecutive updates in datePickerA. Kindly help.
Searched for all possible solutions but of no use. Kindly help
Below is my code. The code used in oncreate gets executed , but further setMinDate function called in HandleResponse ( this is the function that gets called once datepickerA is set )
//On OnCreate
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
long t = tomorrow.getTime();
fromDatePicker.getDatePicker().setMinDate(t);
//
toDatePicker.getDatePicker().setMinDate(t);
public void HandleResponse(Response response)
{
String sqlRes = "";
try {
String sResJson = response.body().string();
JSONObject jReader = new JSONObject(sResJson);
JSONObject jRes = jReader.getJSONObject("Result");
sqlRes = jRes.getString("res");
final int sqlMilkQty = jRes.getInt("qty");
String enddate = jRes.getString("date");
Date d = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d = sdf.parse(enddate);
} catch (ParseException e) {
e.printStackTrace();
}
if (d != null && fromDate!= null) {
long t = d.getTime();
long t1 = fromDate.getTime();
toDatePicker.getDatePicker().setMinDate(t1);
toDatePicker.getDatePicker().setMaxDate(t);
}
Handler mainHandler = new Handler(Looper.getMainLooper());
if (sqlRes.equals("PASS"))
{
mainHandler.post(new Runnable() {
#Override
public void run() {
milkQuantity = sqlMilkQty;
txtMilkQuantity.setText(String.valueOf(milkQuantity));
}
});
}
else {
}
} catch (IOException e) {
DisplayError();
}
catch (JSONException e) {
DisplayError();
}
}
I have the array of objects that look like this:
public class Time {
public String start_time;
public String finish_time;
public Time(String start_time, String finish_time) {
this.start_time = start_time;
this.finish_time = finish_time;
}
}
I need to implement a timer in my Fragment in the following way:
it should start counting down from the first element in array in a way that on one single Time element it should first start counting down to the time left to reach start_time, then when the timer reaches start_time, it should start counting down to finish_time and, eventually, when it reaches finish_time it should do the same previous actions for the next element in the array. And when the whole array is finished, it should display 00:00:00.
PS: start_time and finish_time are formatted like this: HH:mm however the timer should be HH:mm:ss
Can anybody help with implementing that or at least give an idea?
Finally, found the appropriate answer. Thanks a lot to the guy who helped me with it:
class Clazz {
private Timer dateTimer;
private Timer remainderTimer;
private Date nextDate;
private boolean remainderTimerStarted;
private static final long REMINDER_UPDATE_INTERVAL = 1000;
private static final String[] DATES = { "12.04.2015 22:21", "12.04.2015 22:22", "12.04.2015 22:23" };
private int currentIndex;
public Clazz() {
dateTimer = new Timer();
}
public static void main(String[] args) {
Clazz instance = new Clazz();
instance.run();
}
private void run() {
nextDate = parseDate(DATES[currentIndex]);
schedule();
}
public void schedule() {
runSecondsCounter();
dateTimer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("Current date is:" + new Date());
currentIndex++;
if (currentIndex < DATES.length) {
nextDate = parseDate(DATES[currentIndex]);
System.out.println("Next date is:" + nextDate);
schedule();
} else {
remainderTimer.cancel();
}
}
}, nextDate);
}
private Date parseDate(String nextDate) {
Date date = null;
DateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm",
Locale.ENGLISH);
try {
date = format.parse(nextDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
private void runSecondsCounter() {
if (remainderTimerStarted) {
remainderTimer.cancel();
}
remainderTimer = new Timer();
remainderTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
remainderTimerStarted = true;
long remains = nextDate.getTime() - new Date().getTime();
System.out.println("Remains: " + (remains / 1000) + " seconds");
}
}, REMINDER_UPDATE_INTERVAL, REMINDER_UPDATE_INTERVAL);
}
}