I created buttons for display current time for start and stop parking and its work.
But when I clicked on the deductbtn, the apps on the phone will pop up and show "my Application 1 has stopped"
How can I fix this? Any help will be much appciated.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_info);
firebaseAuth = FirebaseAuth.getInstance();
parkBtn = (Button)findViewById(R.id.parkBtn);
stopparkBtn = (Button)findViewById(R.id.stopparkBtn);
deductBtn = (Button)findViewById(R.id.deductBtn);
timeResult = (TextView)findViewById(R.id.timeResult);
timeResult2 = (TextView)findViewById(R.id.timeResult2);
diffResult = (TextView)findViewById(R.id.diffResult);
parkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Date d = new Date();
SimpleDateFormat sdf1=new SimpleDateFormat("hh:mm a");
final String currentDateTimeString = sdf1.format(d);
timeResult.setText(currentDateTimeString);
}
});
stopparkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Date d1= new Date();
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm a");
final String currentDateTimeString1 = sdf2.format(d1);
timeResult2.setText(currentDateTimeString1);
}
});
deductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float totalTime = Float.parseFloat(timeResult2.getText().toString());
float totalTime1 = Float.parseFloat(timeResult.getText().toString());
final float timeUsage = totalTime - totalTime1;
diffResult.setText(String.valueOf(timeUsage));
}
});
}
}
The new code is here :
#Override
public void onClick(View view) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a");
Date date1 = null;
try {
date1 = simpleDateFormat.parse(timeResult.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = simpleDateFormat.parse(timeResult2.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
String diffResult= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.FORMAT_SHOW_TIME).toString();
deductBtn.setText(diffResult);
}
You are getting exception because
float totalTime = Float.parseFloat(timeResult2.getText().toString());
float totalTime1 = Float.parseFloat(timeResult.getText().toString());
Here, If you click this button after performing click on other buttons, then textview's text will be in the format hh:mm a
And if you click button for the first time without clicking other buttons , The strings will be empty
Both will throw exception
java.lang.NumberFormatException: Invalid float
You can use,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a");
date1 = simpleDateFormat.parse(timeResult2.getText().toString());
date2 = simpleDateFormat.parse(timeResult.getText().toString());
String diff= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.HOUR_IN_MILLIS).toString();
Make sure that your textviews strings are not empty before doing it.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When click on next button i need to set the next month to text view without opening the month picker and similarly to previous button also. Please can any one help me.
Here is my code
Date today = Calendar.getInstance().getTime();//getting date
SimpleDateFormat formatter = new SimpleDateFormat("MMM-YYYY");
String date = formatter.format(today);
Calendar today1 = Calendar.getInstance();
textView.setText(date);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String dateString = textView.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-YYYY");
//Date date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Get month,year from Calender as String , then parse it as LocalDate then format it through formater .
Example-
public class MainActivity extends AppCompatActivity {
private TextView monthView;
Button next, previous;
public static LocalDate localDate;
private String dateFormat;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
monthView = findViewById(R.id.tvLDate);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
getDate();
next.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
localDate = localDate.plusMonths(1);
monthView.setText(monthFormat(localDate));
}
});
previous.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
localDate = localDate.minusMonths(1);
monthView.setText(monthFormat(localDate));
}
});
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void getDate() {
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
String year = String.valueOf(calendar.get(Calendar.YEAR));
dateFormat = "01/" + month + "/" + year;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
localDate = LocalDate.parse(dateFormat, formatter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private String monthFormat(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM");
return date.format(formatter);
}
}
what you could do is ->
// Get an instance of calendar and set the required Date()
val calendar = Calendar.getInstance()
mButtonNextMonth.setOnClickListener {
calendar[Calendar.MONTH] += 1 // This will give you the currently selected month +1
}
mButtonNextMonth.setOnClickListener {
calendar[Calendar.MONTH] -= 1 // This will give you the currently selected month -1
}
I'm using two text views in a dialog, one is for from date and another is for to date. Now when i click on from date text view the date picker dialog opens and when i select the date it is not updated in the text view, if i open the date picker again and select the date for the second time the date is updated in the text view. can any one figure out why it is not updated the first time.
public static void datePickerDialog(final Context context) {
dialog = new Dialog(context);
dialog.setContentView(R.layout.date_picker_dialog);
fromDateText = dialog.findViewById(R.id.from_date);
toDateText = dialog.findViewById(R.id.to_date);
fromDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePicker(context);
}
});
toDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
datePicker(context);
}
});
dialog.show();
fromDateText.setText(fromDate);
toDateText.setText(toDate);
}
public static void datePicker(Context context){
fromDatePicker = new DatePickerDialog(context, android.R.style.Theme_Holo_Light_Dialog_MinWidth
,fromDateListner, fromDay, fromMonth, fromYear);
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
fromDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fromDatePicker.show();
fromDateListner = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month+=1;
fromDate = dayOfMonth+"/"+month+"/"+year;
setDate();
}
};
}
private static void setDate() {
try {
dateFrom = simpleDateFormat.parse(fromDate);
dateTo = simpleDateFormat.parse(toDate);
} catch (ParseException e) {
e.printStackTrace();
}
fromDateText.setText(dateFrom.toString());
toDateText.setText(dateTo.toString());
}
fromDateListner is initialized after the dialog creation, so the first time the DatePickerDialog is created without listener.
Move the fromDateListner = new DatePickerDialog.OnDateSetListener() ... part before fromDatePicker = new DatePickerDialog(context ...
Can you try like this?
private static void setDate() {
try {
dateFrom = simpleDateFormat.parse(fromDate);
dateTo = simpleDateFormat.parse(toDate);
fromDateText.setText(dateFrom.toString());
toDateText.setText(dateTo.toString());
} catch (ParseException e) {
e.printStackTrace();
}
}
// Edit:
Check my code:
private void showDatePicker() {
final Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
setDate(myCalendar.getTime());
}
};
if (getActivity() != null) {
new DatePickerDialog(getActivity(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
}
private void setDate(Date time) {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.US);
editText.setText(sdf.format(time));
}
Try this code ..
take boolean variable for selected textview ...
change method like this way..
public class DialogActiivty extends AppCompatActivity {
private TextView fromDateText,toDateText;
private String fromDate,toDate;
private Dialog dialog;
private DatePickerDialog fromDatePicker;
private SimpleDateFormat simpleDateFormat;
private Calendar calendar;
private int year, month, day;
private boolean fromSelected=false,toSelected=true;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datePickerDialog(DialogActiivty.this);
}
public void datePickerDialog(final Context context) {
calendar=Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
dialog = new Dialog(context);
dialog.setContentView(R.layout.date_picker_dialog);
fromDateText = dialog.findViewById(R.id.from_date);
toDateText = dialog.findViewById(R.id.to_date);
fromDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toSelected=false;
fromSelected=true;
datePicker(context);
}
});
toDateText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fromSelected=false;
toSelected=true;
datePicker(context);
}
});
dialog.show();
// fromDateText.setText(fromDate);
// toDateText.setText(toDate);
}
public void datePicker(Context context){
fromDatePicker = new DatePickerDialog(context, android.R.style.Theme_Holo_Light_Dialog_MinWidth
,fromDateListner, year, month, day);
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
fromDatePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
fromDatePicker.show();
}
DatePickerDialog.OnDateSetListener fromDateListner = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month+=1;
fromDate = dayOfMonth+"/"+month+"/"+year;
setDate(fromDate);
}
};
private void setDate(String fromDate) {
if (fromSelected) {
fromDateText.setText(fromDate);
}
if (toSelected) {
toDateText.setText(fromDate);
}
}
}
public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!
i want to take the date that looks like that ("Year-mm-DD") from date picker in android studio and compare if it with the current date when i press a button.
public class UserMenu extends ActionBarActivity {
DatePicker date;
ImageButton next;
Date currentDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_menu);
date = (DatePicker) findViewById(R.id.datePicker);
next = (ImageButton) findViewById(R.id.nxt);
currentDate = new Date();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(date.getYear(), date.getMonth(), date.getDayOfMonth()));
String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(currentDate);
if (dateFormat.compareTo(nowDate) < 0) {
Toast.makeText(getApplicationContext(), "The date is too old", Toast.LENGTH_LONG);
} else {
Intent i = new Intent(UserMenu.this, UserMenuTime.class);
i.putExtra("date", dateFormat);
startActivity(i);
}
}
});
}
}
Use before and after methods to compare dates:
Date pickerDate = new Date(date.getYear(), date.getMonth(), date.getDayOfMonth());
if (pickerDate.before(currentDate)) {
Toast.makeText(getApplicationContext(), "The date is too old", Toast.LENGTH_LONG);
} else {
Intent i = new Intent(UserMenu.this, UserMenuTime.class);
i.putExtra("date", dateFormat);
startActivity(i);
}
I have 2 date-picker in one activity. What i want to do is when user try to select date from second date-picker then that date should greater than first date-picker's date otherwise it should show alert dialog.
So below is my code.
public class Assignment_Create extends Activity implements OnClickListener {
DataManipulator dataManipulator;
static final int DIALOG_ID = 1;
ImageView imageViewDateAssign, imageViewDueDate, imageViewSubmit;
TextView textViewDtAssign, textViewDueDt;
EditText editTextTitle, editTextDesc;
static final int DATE_DIALOG_ID = 0;
int cDay, cMonth, cYear;
private TextView activeDateDisplay;
private Calendar activeDate;
// Update database
String updateId;
public boolean isEdit;
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment_create);
imageViewDateAssign = (ImageView) findViewById(R.id.dateassign);
imageViewDueDate = (ImageView) findViewById(R.id.duedate);
imageViewSubmit = (ImageView) findViewById(R.id.submit);
textViewDtAssign = (TextView) findViewById(R.id.textViewDateAssign);
textViewDueDt = (TextView) findViewById(R.id.textViewDueDate);
editTextTitle = (EditText) findViewById(R.id.title);
editTextDesc = (EditText) findViewById(R.id.description);
isEdit = getIntent().getExtras().getBoolean("isEdit");
updateId = getIntent().getExtras().getString("idNo");
if (isEdit) {
editTextTitle.setText(getIntent().getExtras().getString(
"AsmntTitle"));
editTextDesc
.setText(getIntent().getExtras().getString("AsmntDesc"));
}
Code.AssignDate = Calendar.getInstance();
Code.DueDate = Calendar.getInstance();
imageViewDateAssign.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showDateDialog(textViewDtAssign, Code.AssignDate);
}
});
imageViewDueDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showDateDialog(textViewDueDt, Code.DueDate);
}
});
imageViewSubmit.setOnClickListener(this);
updateDisplay(textViewDtAssign, Code.AssignDate);
updateDisplay(textViewDueDt, Code.DueDate);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
Code.title = editTextTitle.getText().toString().trim();
Code.description = editTextDesc.getText().toString().trim();
Code.diff = Code.DueDate.getTimeInMillis()
- Code.AssignDate.getTimeInMillis();
Code.days = Code.diff / (24 * 60 * 60 * 1000);
Code.strDays = String.valueOf(Code.days);
Date assignDate = new Date(Code.AssignDate.getTimeInMillis());
Date dueDate = new Date(Code.DueDate.getTimeInMillis());
if (dueDate.before(assignDate) || dueDate.equals(assignDate)) {
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Assignment_Create.this);
myDialogBattery.setTitle("How to use Less Battery");
myDialogBattery.setMessage("hahahahahaha");
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
}
if (isEdit) {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.update(updateId);
this.dataManipulator.close();
} else {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.insert(Code.title, Code.description,
Code.strDays);
this.dataManipulator.close();
}
Toast.makeText(getApplicationContext(),
"Details are saved successfully", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Assignment Created Succesfully", Toast.LENGTH_LONG).show();
Assignment_Create.this.finish();
break;
}
}
private void updateDisplay(TextView dateDisplay, Calendar date) {
dateDisplay.setText(new StringBuilder()
// Month is 0 based so add 1
.append(date.get(Calendar.MONTH) + 1).append("-")
.append(date.get(Calendar.DAY_OF_MONTH)).append("-")
.append(date.get(Calendar.YEAR)).append(" "));
}
#SuppressWarnings("deprecation")
public void showDateDialog(TextView dateDisplay, Calendar date) {
activeDateDisplay = dateDisplay;
activeDate = date;
showDialog(DATE_DIALOG_ID);
}
private OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
activeDate.set(Calendar.YEAR, year);
activeDate.set(Calendar.MONTH, monthOfYear);
activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDisplay(activeDateDisplay, activeDate);
unregisterDateDisplay();
}
};
private void unregisterDateDisplay() {
activeDateDisplay = null;
activeDate = null;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, dateSetListener,
activeDate.get(Calendar.YEAR),
activeDate.get(Calendar.MONTH),
activeDate.get(Calendar.DAY_OF_MONTH));
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(
activeDate.get(Calendar.YEAR),
activeDate.get(Calendar.MONTH),
activeDate.get(Calendar.DAY_OF_MONTH));
break;
}
}
}
I have tried with the following link but not getting solution as i want
how to not allow user select past date in datepicker?
Setting upper and lower date limits to date picker dialog
How to set min-max age limit with datepicker android
Date Picker with max and minimum date in onDateChanged() in Android 1.5?
so i am setting date, now when user click on submit button and if the date-picker2's date is lesser than date-picker1's date then alert dialog should come..
So what i am doing wrong, can anyone help me please. Thanks in advance.
Just compare getTimeInMillis of Calendar
Calendar mCalendarFirst = Calendar.getInstance();
mSelectedCalendar.set(Calendar.YEAR, your_year_from_frist_datepicker);
mSelectedCalendar.set(Calendar.MONTH, your_month_from_frist_datepicker);
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_frist_datepicker);
Calendar mCalendarSecond = Calendar.getInstance();
mSelectedCalendar.set(Calendar.YEAR, your_year_from_second_datepicker);
mSelectedCalendar.set(Calendar.MONTH, your_month_from_seconf_datepicker);
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_second_datepicker);
if(mCalendarSecond.getTimeInMillis() <= mCalendarFirst.getTimeInMillis())
{
//Your second date is less than first date
//Show your dialog here.
}
Update:
For your situation use below:
if(Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis())
{
//Your second date is less than first date
//Show your dialog here.
}
Try Below code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
Code.title = editTextTitle.getText().toString().trim();
Code.description = editTextDesc.getText().toString().trim();
Code.diff = Code.DueDate.getTimeInMillis()
- Code.AssignDate.getTimeInMillis();
Code.days = Code.diff / (24 * 60 * 60 * 1000);
Code.strDays = String.valueOf(Code.days);
Date assignDate = new Date(Code.AssignDate.getTimeInMillis());
Date dueDate = new Date(Code.DueDate.getTimeInMillis());
if (Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis()){
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Assignment_Create.this);
myDialogBattery.setTitle("How to use Less Battery");
myDialogBattery.setMessage("hahahahahaha");
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
}else
{
if (isEdit) {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.update(updateId);
this.dataManipulator.close();
} else {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.insert(Code.title, Code.description,
Code.strDays);
this.dataManipulator.close();
}
Toast.makeText(getApplicationContext(),
"Details are saved successfully", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Assignment Created Succesfully", Toast.LENGTH_LONG).show();
Assignment_Create.this.finish();
}
break;
}
}
try following code. Here firstDate and secondDate are Date object
if (firstDate.after(secondDate)) { OR //secondDate.before(firstDate)
//display alert here
} else {
}