I have this button that will generate time and date and set it as a child in a database tree, the problem is whenever I click buttons it generates the said time but the time is not changing,
for example i clicked on the button and it generates the time 12:27 Pm, and it will be recorded into the database, now i clicked the button again for the second time and it doesn't change still printing out the 12:27 Pm Instead 12:30 Pm.
the code looks like this
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer num1 = Integer.parseInt(edt1.getText().toString());
Integer num2 = Integer.parseInt(edt2.getText().toString());
Integer result = num1+num2;
String data = "Date Computed: " + Date + Hrs +"Result: "+ result;
DateView.setText(data);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("Add", data);
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Users").child("UserID").child(Date);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
maxid = (snapshot.getChildrenCount());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference.child("Transaction"+maxid).setValue(userMap);
}
});
edt1 = findViewById(R.id.edt1);
edt2 = findViewById(R.id.edt2);
btnadd = findViewById(R.id.btnadd);
btnmin = findViewById(R.id.btnmin);
DateView = findViewById(R.id.DateView);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date = simpleDateFormat.format(calendar.getTime());
simpleHoursFormat = new SimpleDateFormat(" hh:mm:ss ");
Hrs = simpleHoursFormat.format(calendar.getTime());
Hi from the code it looks like you haven't updated your Date and Time in your onClickListener. The updated code should be like this :-
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This will fetch your updated date and time
Date = simpleDateFormat.format(calendar.getTime());
Hrs = simpleHoursFormat.format(calendar.getTime());
Integer num1 = Integer.parseInt(edt1.getText().toString());
// Rest of your code
Try to use this
import java.util.Calendar
Date currentTime = Calendar.getInstance().getTime();
Related
i got some stuck because i want to use the textview to search the date and show the data i want. but only the hard code i can do, and i dunno how to make the search through the textview and display the data i search the date.
how do i search the date, because i set the date as label, but i need my recyclerview to know what my date is showed.
here's the sample
date = findViewById(R.id.DateTextView);
recyclerView = findViewById(R.id.staffList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
attendances = new ArrayList<Attendance>();
recyclerView.setVisibility(View.GONE);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int YEAR = calendar.get(Calendar.YEAR);
int MONTH = calendar.get(Calendar.MONTH);
int DATE = calendar.get(Calendar.DATE);
DatePickerDialog datePickerDialog = new DatePickerDialog(ViewAttendActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.YEAR, year);
calendar1.set(Calendar.MONTH, month);
calendar1.set(Calendar.DATE, day);
String dateText = DateFormat.format("MM-dd-yyyy", calendar1).toString();
date.setText(dateText);
}
}, YEAR, MONTH, DATE);
datePickerDialog.show();
}
});
String dateString = date.toString();
if (dateString.isEmpty()){
Toast.makeText(ViewAttendActivity.this, "Please Select Date First!!!", Toast.LENGTH_SHORT).show();
} else {
recyclerView.setVisibility(View.VISIBLE);
databaseReference = FirebaseDatabase.getInstance().getReference("Attendance").child("08-15-2021");
databaseReference = FirebaseDatabase.getInstance().getReference("Attendance").child(dateString);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
Attendance attendance = dataSnapshot.getValue(Attendance.class);
attendances.add(attendance);
}
editStaffAttendAdapter = new EditStaffAttendAdapter(attendances, ViewAttendActivity.this);
recyclerView.setAdapter(editStaffAttendAdapter);
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(ViewAttendActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
You can retrieve the string showed by a textview using the .getText().toString() attribute, like this:
TextView date = (TextView) findViewById(R.id.DateTextView);
//Retrieve the text showed by the date TextView
String dateShowedByTextView = date.getText().toString();
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.
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 {
}