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.
Related
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();
}
}}
});
}
}
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);
I want to have one date and two time pickers in one dialog and I have done it, but the second time (Time to) is getting the same values as (time from). I have put some 'if cases' to try to fix it but didn't help. I get ("2016/10/27 5:41 0:00) even if I pick the time for the two "timepickers" I don't get the value for the second one or it duplicates the first one.
here is my code:
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
public class AdminActivity extends AppCompatActivity implements View.OnClickListener, TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
//firebase auth object
private FirebaseAuth firebaseAuth;
//view objects
private TextView textViewUserEmailadmin;
private Button buttonLogout;
private DatabaseReference databaseReference;
private EditText editTextinfo;
private TextView Textpass;
private Button buttonSave;
int day, month, year, hour, minute,hour1,minute1;
int dayFinal, monthFinal, yearFinal, hourFinal, minuteFinal,hourFinal1,minuteFinal1;
int i = 0;
Button btnDatePicker;
String a="";
String b="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
//initializing firebase authentication object
firebaseAuth = FirebaseAuth.getInstance();
//if the user is not logged in
//that means current user will return null
if (firebaseAuth.getCurrentUser() == null) {
//closing this activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextinfo = (EditText) findViewById(R.id.editText3);
buttonSave = (Button) findViewById(R.id.buttonSave);
//getting current user
FirebaseUser user = firebaseAuth.getCurrentUser();
//initializing views
textViewUserEmailadmin = (TextView) findViewById(R.id.textViewUserEmailAdmin);
buttonLogout = (Button) findViewById(R.id.buttonLogout);
//displaying logged in user name
textViewUserEmailadmin.setText("Welcome admin " + user.getEmail());
//adding listener to button
buttonLogout.setOnClickListener(this);
buttonSave.setOnClickListener(this);
btnDatePicker = (Button) findViewById(R.id.btn_date);
// btnTimeFrom = (Button) findViewById(R.id.btn_time_from);
// btnTimeTo = (Button) findViewById(R.id.btn_time_to);
Textpass = (TextView) findViewById(R.id.Textviewpass);
btnDatePicker.setOnClickListener(this);
}
private void saveUserInformation() {
String info = editTextinfo.getText().toString().trim();
String pass = Textpass.getText().toString().trim();
i++;
UserInformation UserInformation = new UserInformation(info, pass);
// FirebaseUser user = firebaseAuth.getCurrentUser();
//databaseReference.child(user.getUid()+i++).setValue(UserInformation);
databaseReference.child("tidnr" + i).setValue(UserInformation);
Toast.makeText(this, "Information saved...", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
//if logout is pressed
if (view == buttonLogout) {
//logging out the user
firebaseAuth.signOut();
//closing activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
if (view == buttonSave) {
saveUserInformation();
}
if (view == btnDatePicker) {
if(a == "" && b == "") {
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(AdminActivity.this, AdminActivity.this, year, month, day);
datePickerDialog.show();
}
}
}
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
yearFinal=i;
monthFinal=i1 +1;
dayFinal= i2;
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(a == "" && b == "") {
android.text.format.DateFormat dateFormat = new android.text.format.DateFormat();
//is24HourFormat = dateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog = new TimePickerDialog(AdminActivity.this, AdminActivity.this,
hour, minute, dateFormat.is24HourFormat(this));
timePickerDialog.show();
}
}
#Override
public void onTimeSet(TimePicker view, int i, int i1) {
hourFinal = i;
minuteFinal = i1;
String curTime = String.format("%02d",minuteFinal);
if(a == "" && b == ""){
a = yearFinal+"/"+monthFinal+"/"+dayFinal+" "+hourFinal+":"+curTime;
}
if(a != "" && b == "" ) {
Calendar c1 = Calendar.getInstance();
hour1 = c1.get(Calendar.HOUR_OF_DAY);
minute1 = c1.get(Calendar.MINUTE);
android.text.format.DateFormat dateFormat1 = new android.text.format.DateFormat();
//is24HourFormat = dateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog1 = new TimePickerDialog(AdminActivity.this, AdminActivity.this,
hour1, minute1, dateFormat1.is24HourFormat(this));
timePickerDialog1.show();
String curTime1 = String.format("%02d",minuteFinal1);
b = a+" "+hourFinal1+":"+curTime1;
a="";
Textpass.setText(b);
Toast.makeText(this, "test.", Toast.LENGTH_SHORT).show();
}
}
}
Replace this line
String curTime1 = String.format("%02d",minuteFinal1);
b = a+" "+hourFinal1+":"+curTime1;
with:
String curTime1 = String.format("%02d",minute1);
b = a+" "+hour1+":"+curTime1;
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.
I am new to android development and I hope you can help me solve my problem. Any help will be appreciated. I created a dialogfragment for picking dates. I am able to select the desired dates but I am having trouble in displaying the selected dates.
Here is my DialogFragment
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private Calendar mCalendar;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int monthOfYear = mCalendar.get(Calendar.MONTH);
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, monthOfYear, dayOfMonth);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
and I call it from my remindersFragment which extends fragment
private void registerButtonListenersAndSetDefaultText() {
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getActivity().showDialog(DATE_PICKER_DIALOG);
android.support.v4.app.DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
updateDateButtonText();
}
});
updateDateButtonText();
}
and my updateButton :
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
I hope you can help me. I've been trying to figure this out for days but I had no luck. Thanks in advance.
Here is the full code on my DialogFragment. I hope this will help:
package com.csu.eclassrecord;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener{
//
// Date Format
//
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
private EditText mTitleText;
private EditText mBodyText;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Long mRowId;
private RemindersDbAdapter mDbHelper;
private Calendar mCalendar;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int monthOfYear = mCalendar.get(Calendar.MONTH);
int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, monthOfYear, dayOfMonth);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
}
and on my remindersFragment:
package com.csu.eclassrecord;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.csu.eclassrecord.R;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class RemindersFragment extends Fragment {
//
// Dialog Constants
//
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
//
// Date Format
//
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:mm";
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd kk:mm:ss";
private EditText mTitleText;
private EditText mBodyText;
private Button mDateButton;
private Button mTimeButton;
private Button mConfirmButton;
private Long mRowId;
private RemindersDbAdapter mDbHelper;
private Calendar mCalendar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDbHelper = new RemindersDbAdapter(getActivity());
View rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
mCalendar = Calendar.getInstance();
mTitleText = (EditText) rootView.findViewById(R.id.title);
mBodyText = (EditText) rootView.findViewById(R.id.body);
mDateButton = (Button) rootView.findViewById(R.id.reminder_date);
mTimeButton = (Button) rootView.findViewById(R.id.reminder_time);
mConfirmButton = (Button) rootView.findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
registerButtonListenersAndSetDefaultText();
return rootView;
}
private void setRowIdFromIntent() {
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID)
: null;
}
}
#Override
public void onPause() {
super.onPause();
mDbHelper.close();
}
#Override
public void onResume() {
super.onResume();
mDbHelper.open();
setRowIdFromIntent();
populateFields();
}
/**
protected Dialog onCreateDialog(int id) {
switch(id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreate(id);
private DatePickerDialog showDatePicker() {
DatePickerDialog datePicker = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
return datePicker;
}
**/
private TimePickerDialog showTimePicker() {
TimePickerDialog timePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, minute);
updateTimeButtonText();
}
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
return timePicker;
}
private void registerButtonListenersAndSetDefaultText() {
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getActivity().showDialog(DATE_PICKER_DIALOG);
android.support.v4.app.DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
});
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(TIME_PICKER_DIALOG);
}
});
mConfirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent;
saveState();
getActivity().setResult(Activity.RESULT_OK);
Toast.makeText(getActivity(), getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
intent = new Intent(getActivity().getApplication(), Manage_Settings.class);
startActivity(intent);
}
});
updateDateButtonText();
updateTimeButtonText();
}
private void populateFields() {
// Only populate the text boxes and change the calendar date
// if the row is not null from the database.
if (mRowId != null) {
Cursor reminder = mDbHelper.fetchReminder(mRowId);
getActivity().startManagingCursor(reminder);
mTitleText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
mBodyText.setText(reminder.getString(
reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_BODY)));
// Get the date from the database and format it for our use.
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
Date date = null;
try {
String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
date = dateTimeFormat.parse(dateString);
mCalendar.setTime(date);
} catch (ParseException e) {
Log.e("ReminderEditActivity", e.getMessage(), e);
}
} else {
// This is a new task - add defaults from preferences if set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String defaultTitleKey = getString(R.string.pref_task_title_key);
String defaultTimeKey = getString(R.string.pref_default_time_from_now_key);
String defaultTitle = prefs.getString(defaultTitleKey, null);
String defaultTime = prefs.getString(defaultTimeKey, null);
if(defaultTitle != null)
mTitleText.setText(defaultTitle);
if(defaultTime != null)
mCalendar.add(Calendar.MINUTE, Integer.parseInt(defaultTime));
}
updateDateButtonText();
updateTimeButtonText();
}
private void updateTimeButtonText() {
// Set the time button text based upon the value from the database
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
}
private void updateDateButtonText() {
// Set the date button text based upon the value from the database
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());
if (mRowId == null) {
long id = mDbHelper.createReminder(title, body, reminderDateTime);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
}
new ReminderManager(getActivity()).setReminder(mRowId, mCalendar);
}
}