How do I calculate time difference between two time pickers in android? - android

I am able to find out the difference between two time intervals, but when the time 1st 12:00am or 00:00 and 2nd time is any other time, I am not getting accurate difference. Instead I am getting a negative difference. Upon debugging I figured out the time is actually taking of the year 1970 January. I am unable to correct it by taking today's time and calculate the difference.
package com.cksapp.memoryin;
import androidx.appcompat.app.AppCompatActivity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreSettings;
import java.security.CodeSigner;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//import java.util.Date;
public class HourlyCalculator extends AppCompatActivity {
EditText wage;
TextView t1, t2, t3;
ImageView i1, i2;
Button b1;
int minutestotal;
String timex, timey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator_hourly);
wage = findViewById(R.id.hourlyrate);
t1 = findViewById(R.id.starttimetext);
t2 = findViewById(R.id.endtimetext);
t3 = findViewById(R.id.finaltime);
i1 = findViewById(R.id.startimage);
i2 = findViewById(R.id.endimage);
b1 = findViewById(R.id.calculatebutton);
Calendar c = Calendar.getInstance();
final int hour = c.get(Calendar.HOUR_OF_DAY);
final int mins = c.get(Calendar.MINUTE);
i1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TimePickerDialog time = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay1, int minute1) {
timex = hourOfDay1 + ":" + minute1;
t1.setText(timex);
Log.d("Time1", timex);
}
},hour, mins, true);
time.show();
}
});
i2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TimePickerDialog time2 = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timey = hourOfDay + ":" + minute;
t2.setText(timey);
Log.d("Time1", timey);
}
},hour,mins,true);
time2.show();
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
Date a = sdf.parse(timex);
Date b = sdf.parse(timey);
long difference = a.getTime() - b.getTime();
Log.d("Time", String.valueOf(difference));
/* minutestotal = (int) (difference/60000);
Log.d("Timearey", String.valueOf(minutestotal));
int totalwageinitital = Integer.parseInt(wage.getText().toString());
double totalwagepermin = totalwageinitital/60;
double finalprice = minutestotal * totalwagepermin;
t3.setText(String.valueOf(finalprice));*/
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
}

You are parsing the time using only hours and minutes, without providing the year, month and day the sdf will assume Jan 1st, 1970.
You should do this in a different way: initialize a calendar object for each date using Calendar.getInstance(), this will give you an instance with today's date, then set the hours and minutes for those 2 instances according to the hours and minutes in the picker and check the difference between their timeInMilliseconds.
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, hour);
time.set(Calendar.MINUTE, minute);

Related

How do I find days between two date pickers in android? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Android Days between two dates
(19 answers)
How to calculate number of days between two datepicker in android and display in the edit text
(3 answers)
Closed 2 years ago.
I have been trying to find the difference between two dates from date picker. My app is getting crashed for null point object exception.
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
package com.cksapp.dateformat;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static java.util.Calendar.YEAR;
public class MainActivity extends AppCompatActivity {
TextView t1, t2, t3, t4, difference;
Button b1;
Date datefrom, dateOne;
Date dateto, dateTwo;
Date d1, d2;
private DatePickerDialog.OnDateSetListener mDate1;
private DatePickerDialog.OnDateSetListener mDate2;
private Object Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = findViewById(R.id.textView);
t2 = findViewById(R.id.textView2);
t3 = findViewById(R.id.textView3);
t4 = findViewById(R.id.textView4);
difference = findViewById(R.id.textView7);
b1 = findViewById(R.id.button);
t1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int year = c.get(YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDate1,
year,month,day);
//Date dateOne = c.getTime();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDate1 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String datefrom = month + "/" + dayOfMonth + "/" + year;
t2.setText(datefrom);
}
};
//next
t3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int year = c.get(YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(MainActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDate2,
year,month,day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDate2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String dateto = month + "/" + dayOfMonth + "/" + year;
t4.setText(dateto);
}
};
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This is where I tried performing subtraction but it didn't work
long diff = dateto.getTime() - datefrom.getTime();
difference.setText((int) diff);
}
});
}
}
By putting String in front of dateto, you've made it a declaration of a local variable rather than a reference to the instance variable (that you're trying to access later). So it will forever be null. Change:
String dateto = month + "/" + dayOfMonth + "/" + year;
to
dateto = new Date(month, dayOfMonth, year); // no "String"
However, the Date constructor is deprecated and using Date is strongly discouraged, so you should really use something like:
import java.time.LocalDate;
import java.time.Instant;
import java.time.ZoneOffset;
//...
Instant dateto;
//...
LocalDate localDate = LocalDate.of(month, dayOfMonth, year);
dateto = localDate.atStartOfDay(ZoneOffset.UTC).toInstant();
Never mind, I figured out the answer using joda library
I have made it with different UI, joda library dependancy is included in build.gradle. It worked perfect.
package com.cksapp.newdateformat;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import net.danlew.android.joda.JodaTimeAndroid;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static org.joda.time.Days.daysBetween;
public class MainActivity extends AppCompatActivity {
TextView t1, t2, t3, t4, today;
Button b1, b2, b3;
String date1, date2, todaydate;
int daysy, daysm, daysd, daysss;
DatePickerDialog.OnDateSetListener dateSetListener;
DatePickerDialog.OnDateSetListener dateSetListener2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JodaTimeAndroid.init(this);
today = findViewById(R.id.today);
t1 = findViewById(R.id.starttext);
t2 = findViewById(R.id.endtext);
t3 = findViewById(R.id.daystext);
t4 = findViewById(R.id.daysinyears);
b1 = findViewById(R.id.startbutton);
b2 = findViewById(R.id.endbutton);
b3 = findViewById(R.id.calculatebutton);
Calendar c = Calendar.getInstance();
final int year = c.get(Calendar.YEAR);
final int month = c.get(Calendar.MONTH);
final int day = c.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
todaydate = sdf.format(Calendar.getInstance().getTime());
today.setText("Today is " + todaydate);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(v.getContext(),dateSetListener,year,month,day);
datePickerDialog.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
date1 = dayOfMonth + "/" + month + "/" + year;
t1.setText(date1);
}
};
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog datePickerDialog2 = new DatePickerDialog(v.getContext(),dateSetListener2,year,month,day);
datePickerDialog2.getDatePicker().setMaxDate(new Date().getTime());
datePickerDialog2.show();
}
});
dateSetListener2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
date2 = dayOfMonth + "/" + month + "/" + year;
t2.setText(date2);
}
};
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(date1 == null || date2 == null){
Toast.makeText(getApplicationContext(), "Please enter the date field(s)",Toast.LENGTH_SHORT).show();
}
else {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
try {
Date d1 = sdf1.parse(date1);
Date d2 = sdf1.parse(date2);
long fromdate = d1.getTime();
long todate = d2.getTime();
Period p = new Period(fromdate, todate, PeriodType.yearMonthDay());
int years = p.getYears();
int months = p.getMonths();
int days = p.getDays();
t4.setText(years + " years" + months + " months" + days + " days");
int diff = (int) (d2.getTime() - d1.getTime());
int YO = diff/86400000;
//Log.d("Days", String.valueOf(diff));
t3.setText(String.valueOf(YO));
} catch (ParseException e) {
e.printStackTrace();
}
}}
});
}
}

how to ring alarm in android studio

Hi i am currently working on application of reminder in android and using Firebase as database. My reminder is getting set properly without any issue but when i retrieve data from Firebase, i'am getting data of particular date but don't know how to ring it on time that user had entered.
This is my code :
Miscelleneous.java
package com.example.dell.reminder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Miscelleneous extends Activity {
private static Button setting,resetting;
private EditText text;
private TextView rem1,date1,time1;
private FirebaseDatabase fdb;
private DatabaseReference db5;
private Button btn1,btn2;
private DatePickerDialog.OnDateSetListener dateSetListener;
private TimePickerDialog.OnTimeSetListener timeSetListener;
String strDate;
String timeString = "";
public static final String REM_KEY = "com.example.dell.reminder.REM_KEY";
public static final String DATE_KEY = "com.example.dell.reminder.DATE_KEY";
public static final String TIME_KEY = "com.example.dell.reminder.TIME_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.miscelleneous);
setting = (Button)findViewById(R.id.remset);
Toolbar tool = (Toolbar)findViewById(R.id.setreminder);
text = (EditText)findViewById(R.id.editText);
btn1 = (Button)findViewById(R.id.selectdate);
btn2 = (Button)findViewById(R.id.selecttime);
rem1 = (TextView)findViewById(R.id.rem1);
date1 = (TextView)findViewById(R.id.date1);
time1 = (TextView)findViewById(R.id.time11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Miscelleneous.this,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,dateSetListener,year,month,day);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
dialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// Log.d("Miscelleneous","OnDateSet: mm/dd/yyyy" +month + "/" + day + "/" + year);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
month = month - 1;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
strDate = format.format(calendar.getTime());
// date = day + "/" + month + "/" + year;
btn1.setText(strDate);
}
};
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
//int second = cal.get(Calendar.SECOND);
TimePickerDialog tdialog = new TimePickerDialog(Miscelleneous.this,
android.R.style.Theme_Holo_Light_Dialog,timeSetListener,hours,minute,false);
tdialog.show();
}
});
timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hours_x, int minute_x) {
//String timeString = "";
if (hours_x == 0) {
timeString = "12:"+minute_x+" "+"a.m.";
btn2.setText(timeString);
} else if (hours_x < 12) {
timeString = hours_x + ":" + minute_x +" "+ "a.m.";
btn2.setText(timeString);
} else if (hours_x == 12) {
timeString = hours_x+":"+minute_x+" "+"p.m.";
btn2.setText(timeString);
} else {
timeString = hours_x-12+ ":" + minute_x +" "+"p.m.";
btn2.setText(timeString);
}
}
};
db5 = FirebaseDatabase.getInstance().getReference().child("user1");
setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(text.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(),"Please write something",Toast.LENGTH_LONG).show();
else if(btn1.getText().toString().isEmpty() && btn2.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Please select date and time",Toast.LENGTH_LONG).show();
}
else if(btn1.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select date",Toast.LENGTH_LONG).show();
}
else if(btn2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select time",Toast.LENGTH_LONG).show();
}
else{
final HashMap<String,String> adddata = new HashMap<String, String>();
adddata.put("Reminder",text.getText().toString());
adddata.put("Date",btn1.getText().toString());
adddata.put("Time",btn2.getText().toString());
db5.child("Users Own").setValue(adddata).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),
"Reminder has been set successfully!!!",Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(),
"Problem in reminder setting !!",Toast.LENGTH_LONG).show();
}
}
});
retrive();
/*Intent intent = new Intent(Miscelleneous.this,History.class);
intent.putExtra(REM_KEY,validate1);
intent.putExtra(DATE_KEY,validate2);
intent.putExtra(TIME_KEY,validate3);
startActivity(intent);*/
//send();
}
}
});
}
/*private void send(){
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(validate1);
arrayList.add(validate2);
arrayList.add(validate3);
Intent i = new Intent(Miscelleneous.this,History.class);
i.putExtra(REM_KEY,arrayList);
startActivity(i);
}*/
private void retrive(){
long current_date = System.currentTimeMillis();
long current_time = System.currentTimeMillis();
// String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a");
String System_Date = sdf.format(current_date);
final String System_Time = sdf1.format(current_time);
String usrdate = btn1.getText().toString().trim();
final String usrtime = btn2.getText().toString().toLowerCase().trim();
// Log.d("Miscelleneous",usrtime);
// Log.d("Miscelleneous",usrdate);
if( System_Date.equals(usrdate)){
db5.child("Users Own").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tim="",date="",remind="";
for (DataSnapshot cdata:dataSnapshot.getChildren()) {
remind = cdata.getValue(String.class).toString();
date = cdata.getValue(String.class).toString();
tim = cdata.getValue(String.class).toString();
}
if(usrtime.equals(System_Time)){
Log.d("Miscelleneous","actual reminder");
Log.d("Miscelleneous","Date:"+remind);
Log.d("Miscelleneous","Reminder:"+date);
Log.d("Miscelleneous","Time:"+tim);
rem1.setText("Reminder : "+remind);
date1.setText("Date : "+date);
time1.setText("Time : "+tim);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(this,"User date matches with System date",Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(this,"User date doesn't matches with System date",Toast.LENGTH_SHORT).show();
}
}
}
Can anyone give me a solution please,
Thanks
you can use AlarmManager to ringing or notify user at particular time.
private AlarmManager alarmManager;
private static Intent alarmIntent;
private static PendingIntent pendingAlarmIntent;
public void setTimings(){
private Calender alarmCalender = Calendar.getInstance();
alarmCalender.setTimeInMillis(System.currentTimeMillis());
alarmCalender.set(Calendar.HOUR_OF_DAY, "hour"); // hour=07
alarmCalender.set(Calendar.MINUTE, "minute"); // minute=01
alarmCalender.set(Calendar.SECOND, "second"); // second=0
alarmCalender.set(Calendar.MILLISECOND, "millisecond");//millisecond=0
setAlarm(AlarmManager.RTC_WAKEUP, alarmCalender, AlarmManager.INTERVAL_DAY);
}
public void setAlarm(int type, Calendar calendar, long timeInMillis){
alarmIntent = new Intent(context, yourBroadcastReciever.class);
pendingAlarmIntent = PendingIntent.getBroadcast(context, Constant.ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(type, calendar.getTimeInMillis(), timeInMillis, pendingAlarmIntent);
}
To handle the alarm at particular time you create the Reciever
yourBroadcastReciever.class
#Override
public void onReceive(Context context, Intent intent) {
// here you handle the task when alarm ringing
}
[Note: Intent and Pending Intent is compulsory for create an Alarm]
use a broadcast receiver and set the time which you are getting.

Android: DatePicker value saved in a variable doesn't go in onCreate

I have a rather simple issue but this is bugging me out!
I am trying to build an app in which I have 2 DatePickers, periodFrom and periodTo.
Basically what I'm trying to do is let the user pick dates on both cases and then calculate the difference between dates in days. I already know how to get the difference, how to get the date from the DatePicker. The problem is I don't know where I should get the value from the DatePicker, as my onCreate intializes the listener for the DatePickers but it doesn't store the set dates in the global variables, only the current date which it gets from Calendar.getInstance();
Here is my code for the MainActivity, maybe you can enlighten me on this issue I'm having. Thank you!
MainActivity.class
package com.endtech.utilitycalculator;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private EditText periodFrom, periodTo;
private Calendar mCalendarFrom = Calendar.getInstance();
private Calendar mCalendarTo = Calendar.getInstance();
private long from, to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
periodFrom = (EditText) findViewById(R.id.periodFrom);
periodTo = (EditText) findViewById(R.id.periodTo);
initListeners();
from = mCalendarFrom.getTimeInMillis(); //This is current time, not the set time
to = mCalendarTo.getTimeInMillis(); //This is current time, not the set time
}
private void initListeners() {
setDateFrom();
setDateTo();
}
private void setDateFrom() {
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendarFrom.set(Calendar.YEAR, year);
mCalendarFrom.set(Calendar.MONTH, monthOfYear);
mCalendarFrom.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabelFrom();
}
};
periodFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(MainActivity.this, date, mCalendarFrom.get(Calendar.YEAR),
mCalendarFrom.get(Calendar.MONTH), mCalendarFrom.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabelFrom() {
String mFormat = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(mFormat, Locale.GERMANY);
periodFrom.setText(sdf.format(mCalendarFrom.getTime()));
}
private void setDateTo() {
final DatePickerDialog.OnDateSetListener date2 = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendarTo.set(Calendar.YEAR, year);
mCalendarTo.set(Calendar.MONTH, monthOfYear);
mCalendarTo.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabelTo();
}
};
periodTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(MainActivity.this, date2, mCalendarTo.get(Calendar.YEAR),
mCalendarTo.get(Calendar.MONTH), mCalendarTo.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabelTo() {
String mFormat = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(mFormat, Locale.GERMANY);
periodTo.setText(sdf.format(mCalendarTo.getTime()));
}
}
The problem is you are getting the dates before selecting them.
Simply Create a button (when you click on the button then the process of converting difference into days get done). then on button click get the values of dates and then convert it into days.
Let me know if you find some problem by commenting below.

DatePickerDialog showing abnormal behaviour in android 5.1 when timezone is changed

I have to show calender using DatePickerDialog.
The below code is used:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.Toast;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private Boolean mEnableNativeCalGridView = null;
String timeZone;
public static TimeZone tz;
private int year;
private int month;
DatePickerDialog d;
public Calendar c;
SimpleDateFormat sdf;
private int day;
public static IntentFilter s_intentFilter;
static final int DATE_PICKER_ID = 1111;
static{
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(m_timeChangedReceiver, s_intentFilter);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// sdf = new SimpleDateFormat("EEE, MMM d, ''yy");//Wed, Jul 4, '01
// Show current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_PICKER_ID:
((DatePickerDialog) dialog).updateDate(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
c= Calendar.getInstance();
c.setTimeZone(tz);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
d = new DatePickerDialog(DatePickerExample.this, pickerListener, year, month,day);
setMinMaxdate();
return d;
}
return null;
}
////////////////////Fix for issue on OS 5.1 //////////////////////
public long getDateFormatted(String date){
String givenDateString = date;
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
//////////////////////////////////////////
private DatePicker.OnDateChangedListener newchange= new OnDateChangedListener(){
#Override
public void onDateChanged(DatePicker view,
int year, int monthOfYear,int dayOfMonth) {
Toast.makeText(getApplicationContext(),
"onDateChanged", Toast.LENGTH_SHORT).show();
}};
DatePicker datePicker;
public void setMinMaxdate() {
//Time zone calculation
//TimeZone.setDefault(tz);
///////////////////////
long calEvtEndDate= getDateFormatted("Sun May 31 23:59:59 "+timeZone+" 2015");//System.currentTimeMillis();
long calEvtStartDate= getDateFormatted("Wed May 13 00:00:00 "+timeZone+" 2015");//System.currentTimeMillis()/2;
// long calEvtEndDate = getDateFormatted("Sun, may 31, '15");
//long calEvtStartDate = getDateFormatted("Wed, may 13, '15");
if(d != null){
datePicker = d.getDatePicker();
if(mEnableNativeCalGridView != null){
datePicker.setCalendarViewShown(mEnableNativeCalGridView.booleanValue());
}
// If Start Date is Greater than End Date then we are showing from valid StartDate
// value and we are not setting the maxdate.
if (calEvtStartDate > calEvtEndDate) {
datePicker.setMinDate(calEvtStartDate);
} else {
if (calEvtStartDate > 0) { // If Only ValidStart date is provided, then setting the minDate.
datePicker.setMinDate(calEvtStartDate);
}
if (calEvtEndDate > 0) { // If Only ValidEnd date is provided, then setting the maxDate.
datePicker.setMaxDate(calEvtEndDate);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("-------resumed");
}
public DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
//view.updateDate(year, month, day);
System.out.println("---------------datesetchange");
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
System.out.println("timezone changed---"+action.toString());
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
// Intent intent1 = getIntent();
// finish();
// startActivity(intent1);
showDialog(DATE_PICKER_ID);
}
}
};
}
When the app is running, I go to the settings and change the Timezone to such a value so that the current date will change. Now when we select any date in the dialog, it behaves abnormally and goes to other date. I have used setMinDate() and setMaxDate() methods. This happens only in Android OS 5.1.
Any idea or help? Thanks in advance.

Data exchange via Intent between Fragments works on pre-5.0 but not on Android 5.0

As a part of The Big Nerd Ranch's Android Guide example Criminal Intent,
I am updating a button with date/time entered in the
Date/TimePicker. Button and Date/TimePicker reside in different
fragments. I am transferring data between them using an Intent. It
works fine on Pre-Lollipop devices but doesn't seem to update button
text on Android 5.0 or Lollipop devices. What am I missing?
Full code can be seen at Github.
CrimeFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Date;
import java.util.UUID;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private Button mTimeButton;
private CheckBox mSolvedCheckBox;
private static final String TAG = "CriminalFragment";
public static final String EXTRA_CRIME_ID = "com.sudhirkhanger.android.criminalintent.crime_id";
private static final String DIALOG_DATE = "date";
private static final String DIALOG_TIME = "time";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TIME = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
private void updateDateAndTime() {
Date d = mCrime.getDate();
CharSequence c = DateFormat.format("EEEE, MMM dd, yyyy", d);
CharSequence t = DateFormat.format("h:mm a", d);
mDateButton.setText(c);
mTimeButton.setText(t);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before,
int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count,
int after) {
// This space intentionally left blank
}
public void afterTextChanged(Editable c) {
// This one too
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTimeButton = (Button) v.findViewById(R.id.crime_time);
mTimeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment dialog = TimePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
dialog.show(fm, DIALOG_TIME);
}
});
updateDateAndTime();
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDateAndTime();
} else if (requestCode == REQUEST_TIME) {
Date date = (Date) data
.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
mCrime.setDate(date);
updateDateAndTime();
}
}
}
DatePickerFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.sudhirkhanger.android.criminalintent.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(),
resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date) getArguments().getSerializable(EXTRA_DATE);
// Create a Calendar to get the year, month, and day
final Calendar calendar = Calendar.getInstance();
// calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(
R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v
.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month,
int day) {
// Translate year, month, day into a Date object using a
// calendar
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
mDate = new GregorianCalendar(year, month, day, hour, minute)
.getTime();
// Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
sendResult(Activity.RESULT_OK);
}
}).create();
}
}
The problem isn't with the communication between the Fragments, it's that for some reason the default CalendarView DatePicker in Lollipop never calls the OnDateChanged() method, so mDate in DatePickerFragment.java never gets changed; DatePickerFragment sends back to CrimeFragment the same value it received from CrimeFragment, so it only looks like the communication between the two Fragments isn't working.
The Lollipop DatePicker does call OnDateChanged() when it's in SpinnerView mode, so CrimeFragment's date will then get properly updated. Unfortunately, Lollipop ignores the android:calendarViewShown="false" directive in the DatePicker's tag in the dialog_date.xml file. The only way to force the DatePicker to display as spinners is to include a android:datePickerMode="spinner" directive in the DatePicker's xml tag. You will get a warning that this directive is supported in API 21 only, but it will be ignored by devices running pre-5.0 Android.You have to keep the calendarViewShown="false" directive for pre-5.0 devices.
DatePickerDialog appears to have been fixed in Android 5.0, so you could also use that resource in DatePickerFragment to make things work.

Categories

Resources