store two time picker values in single fields - java

My app lets user enter two times to set device in silent mode in a specific time for an event. What I have done so far?
take start and end time input from user
activate silent mode and restore sound mode at the given time by the user.
What I need?
store start and end time values in sqlite database but in a single Time field.
For example:
ID Event Name Time
1 study time 2:00 PM-4:00 PM
Below is my MainActivity and databasehelper class
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText etMeal, etDesert;
EditText start, end;
Button btnAdd, btnView, btnsttime, btnend;
DatabaseHelper myDB;
SimpleDateFormat simpleDateFormat,simpleDateFormat1;
DatePicker dp;
CheckBox monday;
String[] Day;
TimePickerDialog timePickerDialog, secondtimepickerdialog;
static int RQS_1 = 1;
static int RQS_2 = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnView = (Button) findViewById(R.id.btnView);
btnsttime = (Button) findViewById(R.id.sttime);
btnend = (Button) findViewById(R.id.endtime);
monday=(CheckBox)findViewById(R.id.monchk);
etMeal = (EditText) findViewById(R.id.etMeal);
//etDesert = (EditText) findViewById(R.id.etDesert);
myDB = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String meal = etMeal.getText().toString();
//String desert = etDesert.getText().toString();
if (meal.length() != 0) {
AddData(meal);
etMeal.setText("");
//etDesert.setText("");
} else {
Toast.makeText(MainActivity.this, "You must fill in the text fields!", Toast.LENGTH_LONG).show();
}
}
});
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, View_Foods.class);
startActivity(intent);
}
});
btnsttime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
btnend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
end();
}
});
}
public void dat()
{
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Toast.makeText(MainActivity.this,dayOfTheWeek,Toast.LENGTH_LONG).show();
}
public void AddData(String meal) {
boolean insertData = myDB.addData(meal);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
public void start()
{
Calendar cal=Calendar.getInstance();
// simpleDateFormat=new SimpleDateFormat("hh:mm a");
Date date = new Date();
//String time=simpleDateFormat.format(date);
int hour=cal.get(Calendar.HOUR);
int minute=cal.get(Calendar.MINUTE);
timePickerDialog=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, final int hourOfDay1,final int minute1) {
Time time = new Time(hourOfDay1, minute1,0);
//GregorianCalendar j2=new GregorianCalendar(hourOfDay1,minute1,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
btnsttime.setText(s);
//dp.getDayOfMonth();
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay1);
calSet.set(Calendar.MINUTE, minute1);
Toast.makeText(MainActivity.this,"Pending intent started",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), SilenceBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);
//final long sttimer=((shour)*60*60*1000)+((sminute)*60*1000);
}
},hour,minute,false);
timePickerDialog.setTitle("Start time");
timePickerDialog.show();
}
public void end(){
Calendar cal1=Calendar.getInstance();
simpleDateFormat1=new SimpleDateFormat("hh:mm a");
Date date1 = new Date();
String time=simpleDateFormat1.format(date1);
int hour=cal1.get(Calendar.HOUR);
int minute=cal1.get(Calendar.MINUTE);
secondtimepickerdialog=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, final int hourOfDay2,final int minute2) {
Time time = new Time(hourOfDay2, minute2,0);
//GregorianCalendar j2=new GregorianCalendar(hourOfDay1,minute1,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat1.format(time);
btnend.setText(s);
Calendar calNow1 = Calendar.getInstance();
Calendar calSet1 = (Calendar) calNow1.clone();
calSet1.set(Calendar.HOUR_OF_DAY, hourOfDay2);
calSet1.set(Calendar.MINUTE, minute2);
Toast.makeText(MainActivity.this,"Pending intent started",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), UnsilenceBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_2, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet1.getTimeInMillis(), pendingIntent);
//final long sttimer=((shour)*60*60*1000)+((sminute)*60*1000);
}
},hour,minute,false);
timePickerDialog.setTitle("End time");
secondtimepickerdialog.show();
}
}
Databasehelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "food.db";
public static final String TABLE_NAME = "food_data";
public static final String COL1 = "ID";
public static final String COL2 = "MEAL";
//public static final String COL3 = "DESERT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" MEAL TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String meal) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, meal);
//contentValues.put(COL3, desert);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}

Related

The app can't manage more than a push notification

I'm tried to manage a set of push notifications.
1. My first problem is that only last notification set up receive my smartphone. I believe that it hasn't create new instance but it overwrite the unique istance. How can I solve it?
2. My second problem is that i want that from app, the user can delete a schedule of a determinate notification.
This is my code in MovieAdapter.java (main methods are getNotification, scheduleNotification and deleteNotification ):
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder>{
private PendingIntent pendingIntent = null;
private Context context;
private List<Movie> movies;
private View itemView;
private RecyclerView rv;
//per la data
private EditText fromDateEtxt;
private EditText eReminderTime;
private boolean active = false;
private int mese = (Calendar.getInstance().getTime().getMonth())+1;
private int anno = (Calendar.getInstance().getTime().getYear())+1900 ;
private int giorno = Calendar.getInstance().getTime().getDate();
private int ora;
private int minuti;
private int secondi;
private boolean modify = false;
private Date datatime;
private static String tipo = "NOTIFY";
//non sono ancora sicuro se metterlo qui
private WorkManager mWorkManager;
static MoviesFragment fragmentInstance;
static SectionsPageAdapter spa;
public MoviesAdapter(Context context, List<Movie> movies, MoviesFragment fragment) {
this.context = context;
this.movies = movies;
this.fragmentInstance = fragment;
this.spa = null;
}
public MoviesAdapter(Context context, List<Movie> movies, SectionsPageAdapter spa) {
this.context = context;
this.movies = movies;
this.spa = spa;
this.fragmentInstance = null;
}
#Override
public MoviesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
/*if(getTipo().equals("Suggested"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Watched"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie_watched, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Notify"))
{*/
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
//}
//return null;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
mWorkManager = WorkManager.getInstance();
final Movie movie = movies.get(position);
Glide.with(context)
.load(movie.getPosterUrl())
.placeholder(R.drawable.poster_placeholder)
.into(holder.posterView);
holder.title_movie.setText(movie.getTitle());
// prende solo la data + anno
String yourString = String.valueOf(movie.getReleaseDate());
String date = yourString.substring(0, 10);
String year = yourString.substring(yourString.length()-5,yourString.length());
//per fare il testo bold
final SpannableStringBuilder sb = new SpannableStringBuilder("Release: "+date+year);
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan nss = new StyleSpan(Typeface.NORMAL); //Span to make text italic
sb.setSpan(bss, 0, 7, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(nss, 7, sb.length()-1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
holder.release_date.setText(sb);
if(getTipo().equals("NOTIFY")) {
Toast.makeText(context, "Notify", Toast.LENGTH_LONG).show();
holder.movie_notify.setVisibility(View.VISIBLE);
holder.notifyButton.setVisibility(View.GONE);
holder.changeDateTimeButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
holder.removeButton.setVisibility(View.VISIBLE);
String yourString1 = String.valueOf(movie.getNotifyDate());
Log.i("STRINGA",yourString1);
if(!(yourString1.equals("null"))) {
date = yourString1.substring(0, 16);
year = yourString1.substring(yourString1.length() - 5, yourString1.length());
//per fare il testo bold
final SpannableStringBuilder sb1 = new SpannableStringBuilder("Notify: " + date + year);
final StyleSpan bss1 = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan nss1 = new StyleSpan(Typeface.NORMAL); //Span to make text normal
sb1.setSpan(bss1, 0, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb1.setSpan(nss1, 6, sb.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
holder.movie_notify.setText(sb1);
}
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDatabase md = new MovieDatabase(context);
md.deleteMovie(movies.get(position).getId());
deleteNotify(pendingIntent);
refreshLists();
}
});
holder.changeDateTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertFormElements(position, true);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(),null);
MovieDatabase.updateMovieType(movies.get(position).getId(), 2,MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
refreshLists();
}
});
}
//solo se è di tipo suggested
if(getTipo().equals("SUGGESTED")) {
//disabilitare bottone remove
holder.movie_notify.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
holder.changeDateTimeButton.setVisibility(View.GONE);
Toast.makeText(context,"Suggested", Toast.LENGTH_LONG).show();
holder.notifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertFormElements(position, false);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(),null);
MovieDatabase.insertMovie(mdm, 2, MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
refreshLists();
}
});
}
if (getTipo().equals("WATCHED")) {
holder.movie_notify.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
holder.changeDateTimeButton.setVisibility(View.GONE);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDatabase md = new MovieDatabase(context);
md.deleteMovie(movies.get(position).getId());
refreshLists();
}
});
Toast.makeText(context,"WATCHED", Toast.LENGTH_LONG).show();
}
}
//nuovo codice riguardo l'alerDialog
public final void alertFormElements(final int position, final boolean modify) {
/*
* Inflate the XML view. activity_main is in
* res/layout/form_elements.xml
*/
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.form_elements,
null, false);
// You have to list down your form elements
/*final CheckBox myCheckBox = (CheckBox) formElementsView
.findViewById(R.id.myCheckBox);*/
final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
.findViewById(R.id.NotifyAlertRadioGroup);
//nuovo codice
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.OneDayRadioButton:
actv(false);
break;
case R.id.ReleaseDayRadioButton:
actv(false);
break;
case R.id.OnRadioButton:
actv(true);
break;
}
}
});
//questo sarà sostituito con un calendario.
/*final EditText nameEditText = (EditText) formElementsView
.findViewById(R.id.nameEditText);*/
//parte data
fromDateEtxt = (EditText) formElementsView.findViewById(R.id.nameEditText);
fromDateEtxt.setEnabled(active);
fromDateEtxt.setClickable(active);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//metodo data
//setDateTimeField();
//fromDatePickerDialog.show();
//Calendario ci servirà dopo per inserire i dati nel DB
fromDateEtxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog( context ,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
fromDateEtxt.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
anno = year;
giorno = dayOfMonth;
mese = monthOfYear + 1;
}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
});
//parte orario
ora = 9;
minuti = 30;
eReminderTime = (EditText) formElementsView.findViewById(R.id.timeEditText);
eReminderTime.setText( ora + ":" + minuti);
eReminderTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
eReminderTime.setText( selectedHour + ":" + selectedMinute);
ora = selectedHour;
minuti = selectedMinute;
}
//}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
// the alert dialog
new AlertDialog.Builder(context).setView(formElementsView)
.setTitle(movies.get(position).getTitle()+" Notify")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
//fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
String toastString = "";
String titleMovie = movies.get(position).getTitle();
String releaseDate = String.valueOf(movies.get(position).getReleaseDate());
String date = releaseDate.substring(0, 10);
String year = releaseDate.substring(releaseDate.length()-5,releaseDate.length());
releaseDate = date+year;
toastString = toastString + titleMovie + "\n" + releaseDate +"\n";
/*
* Detecting whether the checkbox is checked or not.
*/
/*if (myCheckBox.isChecked()) {
toastString += "Happy is checked!\n";
} else {
toastString += "Happy IS NOT checked.\n";
}*/
/*
* Getting the value of selected RadioButton.
*/
// get selected radio button from radioGroup
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton selectedRadioButton = (RadioButton) formElementsView
.findViewById(selectedId);
Date datatime = null;
if(selectedRadioButton.getId() == R.id.ReleaseDayRadioButton) {
toastString += "Selected radio button is: " + selectedRadioButton.getText() +"!\n";
Date release = movies.get(position).getReleaseDate();
release.setHours(ora);
release.setMinutes(minuti);
release.setSeconds(secondi);
datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
}
else if(selectedRadioButton.getId() == R.id.OneDayRadioButton) {
toastString += "Selected radio button is: "
+ selectedRadioButton.getText() + "!\n";
Date release = movies.get(position).getReleaseDate();
release.setHours(ora);
release.setMinutes(minuti);
release.setSeconds(secondi);
datatime = new Date (anno-1900,mese-1,giorno-1,release.getHours(),release.getMinutes(), release.getSeconds());
}
else if(selectedRadioButton.getId() == R.id.OnRadioButton) {
toastString += "Selected radio button is: " + fromDateEtxt.getText() +"!\n";
datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
}
setDataTime(datatime);
toastString += eReminderTime.getText();
//Date(int year, int month, int date, int hrs, int min, int sec)
//Date datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
//ora scriviamo tutta questa roba sulla base di dati
/*String testo = movies.get(position).getTitle()+ "\n" + "I WATCH IT";
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
if(modify == false) {
// public MovieDBModel(int id, String title, String overview, String posterUrl, String backdropUrl, String trailerUrl,
// Date releaseDate, float rating, boolean adult, date datatime){
//Log.i("DATATIME", datatime.toString());
MovieDBModel mdm2 = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(), datatime);
MovieDatabase.insertMovie(mdm2, 1, MainActivity.getMovieDatabase());
//notifyRequestID= scheduleNotify(datatime,position);
pendingIntent=scheduleNotification(getNotification(movies.get(position).getTitle()),datatime,movies.get(position).getId());
refreshLists();
}
else {
// provare la base di dati
MovieDatabase md = new MovieDatabase(context);
Log.i("DATATIME","ID"+ movies.get(position).getId() +"DATATIME: "+ datatime);
md.updateNotifyDate(movies.get(position).getId(),datatime);
//deleteNotify(notifyRequestID);
//inserire funzione deleteNotify
deleteNotify(pendingIntent);
pendingIntent=scheduleNotification(getNotification(movies.get(position).getTitle()),datatime, movies.get(position).getId());
refreshLists();
}
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
/*
* Getting the value of an EditText.
*/
/*toastString += "Name is: " + nameEditText.getText()
+ "!\n";*/
Toast toast = Toast.makeText(context, toastString, Toast.LENGTH_LONG);
toast.show();
dialog.cancel();
}
}).show();
}
//nuovo codice
/*#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_movie, null);
holder = new ViewHolder();
holder.title_movie = (TextView) convertView.findViewById(R.id.movie_title);
holder.release_date = (TextView) convertView
.findViewById(R.id.movie_release_date);
Movie row_pos = movies.get(position);
//holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.title_movie.setText(row_pos.getTitle());
holder.release_date.setText((CharSequence) row_pos.getReleaseDate());
//holder.contactType.setText(row_pos.getContactType());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}*/
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
Glide.clear(holder.posterView);
}
#Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.poster)
public ImageView posterView;
#BindView(R.id.movie_title)
public TextView title_movie;
#BindView(R.id.movie_release_date)
public TextView release_date;
#BindView(R.id.movie_time_notify)
public TextView movie_notify;
#BindView(R.id.editNotify)
public Button notifyButton;
#BindView(R.id.iWatchItMovie)
public Button watchedButton;
#BindView(R.id.remove)
public Button removeButton;
#BindView(R.id.change)
public Button changeDateTimeButton;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
//parte per attivare/disattivare l'editText
private void actv(final boolean active)
{
fromDateEtxt.setEnabled(active);
if (active)
{
fromDateEtxt.requestFocus();
fromDateEtxt.setText(giorno+"-"+mese+"-"+anno);
}
}
public static void setTipo(String tipo) {
MoviesAdapter.tipo = tipo;
}
public static void setFragment(MoviesFragment fragment) {
MoviesAdapter.fragmentInstance = fragment;
}
public static String getTipo() {
return tipo;
}
public Date getDatatime() {
return datatime;
}
public void setDataTime(Date datatime) {
this.datatime = datatime;
}
private Data createInputDataForUri(Movie movie) {
Data.Builder builder = new Data.Builder();
if (movie != null) {
builder.putString(KEY_MOVIE,movie.getTitle());
}
return builder.build();
}
private PendingIntent scheduleNotification(Notification notification, /*int delay*/Date d, int id) {
Intent notificationIntent = new Intent(context, NotificationPublisher.class);
//
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, id);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP,d.getTime(), pendingIntent);
return pendingIntent;
}
public void deleteNotify(PendingIntent p)
{
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(p);//cancel the alarm manager of the pending intent
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("WARNING!!! REMEMBER MOVIE: ");
builder.setContentText(content);
builder.setDefaults(DEFAULT_ALL);
builder.setSmallIcon(R.drawable.ic_launcher_foreground);
return builder.build();
}
public void refreshLists(){
if(fragmentInstance!= null){
fragmentInstance.onRefresh();
}else{
MoviesFragment mf1 = (MoviesFragment)spa.getItem(0);
mf1.setArgFragType(MoviesFragment.Type.NOTIFY);
mf1.onRefresh();
MoviesFragment mf2 = (MoviesFragment)spa.getItem(1);
mf2.setArgFragType(MoviesFragment.Type.SUGGESTED);
mf2.onRefresh();
MoviesFragment mf3 = (MoviesFragment)spa.getItem(2);
mf3.setArgFragType(MoviesFragment.Type.WATCHED);
mf3.onRefresh();
}
}
}
NotificationPublisher.java
package com.example.msnma.movienotifier.notify;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationPublisher extends BroadcastReceiver
{
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Change this line
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
To
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT); //Here 0 is the intent requestcode.
Make sure intent request code is unique in order to differentiate intents.

To store DateTime value into php and mysql

I am working on how to put Date value into my PHP/MySQL using android's date picker.
I want to make a Sharing Parking lot application that owner can register one's parking place with its information like operating time. Then user can use it with choosing the beginning and ending points.
I searched a lot but need more specific information.
How can I save operating time slot into PHP/MySQL?
The following is my android java code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.avtivity_date_time);
mText1 = (TextView) findViewById(R.id.text1);
mPickDate1 = (Button) findViewById(R.id.pickDate1);
mPickTime1 = (Button) findViewById(R.id.pickTime1);
mText2 = (TextView) findViewById(R.id.text2);
mPickDate2 = (Button) findViewById(R.id.pickDate2);
mPickTime2 = (Button) findViewById(R.id.pickTime2);
mPickDate1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID_1);
}
});
mPickDate2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID_2);
}
});
mPickTime1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID_1);
}
});
mPickTime2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID_2);
}
});
final Calendar c = Calendar.getInstance();
mYear1 = c.get(Calendar.YEAR);
mMonth1 = c.get(Calendar.MONTH);
mDay1 = c.get(Calendar.DAY_OF_MONTH);
mHour1 = c.get(Calendar.HOUR_OF_DAY);
mMinute1 = c.get(Calendar.MINUTE);
mYear2 = c.get(Calendar.YEAR);
mMonth2 = c.get(Calendar.MONTH);
mDay2 = c.get(Calendar.DAY_OF_MONTH);
mHour2 = c.get(Calendar.HOUR_OF_DAY);
mMinute2 = c.get(Calendar.MINUTE);
updateDisplay();
}
private void updateDisplay() {
mText1.setText(String.format("시작 : %d년 %d월 %d일 %d시 %d분", mYear1, mMonth1 + 1, mDay1, mHour1, mMinute1));
mText2.setText(String.format("종료 : %d년 %d월 %d일 %d시 %d분", mYear2, mMonth2 + 1, mDay2, mHour2, mMinute2));
}
private DatePickerDialog.OnDateSetListener mDateSetListener1 =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear1 = year;
mMonth1 = monthOfYear;
mDay1 = dayOfMonth;
updateDisplay();
}
};
private DatePickerDialog.OnDateSetListener mDateSetListener2 =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear2 = year;
mMonth2 = monthOfYear;
mDay2 = dayOfMonth;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener1 =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour1 = hourOfDay;
mMinute1 = minute;
updateDisplay();
}
};
private TimePickerDialog.OnTimeSetListener mTimeSetListener2 =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour2 = hourOfDay;
mMinute2 = minute;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID_1:
return new DatePickerDialog(this, mDateSetListener1, mYear1, mMonth1, mDay1);
case TIME_DIALOG_ID_1:
return new TimePickerDialog(this, mTimeSetListener1, mHour1, mMinute1, false);
case DATE_DIALOG_ID_2:
return new DatePickerDialog(this, mDateSetListener2, mYear2, mMonth2, mDay2);
case TIME_DIALOG_ID_2:
return new TimePickerDialog(this, mTimeSetListener2, mHour2, mMinute2, false);
}
return null;
}
private Long getDateInMS(String stringDateTime) throws ParseException {
SimpleDateFormat simpledateformat1 = new SimpleDateFormat("yyyy MM dd hh mm");
SimpleDateFormat simpledateformat2 = new SimpleDateFormat("yyyy MM dd hh mm");
String formatdate1 = simpledateformat1.format("mYear1, mMonth1, mDay1, mHour1, mMinute1");
String formatdate2 = simpledateformat2.format("mYear12, mMonth2, mDay2, mHour2, mMinute2");
Date startdate = simpledateformat1.parse(formatdate1);
Date enddate = simpledateformat2.parse(formatdate2);
return null;
}

Calendar cannot initialize null pointer exception on 5.1 API level

This time reminder class, time reminder is crashing on click and erroe goes on "custom.showDialogue" and the error is the following:
FATAL EXCEPTION: main
Process: com.appmetrik.notestakingapp, PID: 18607
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.app.notes.CustomDateTimePicker.showDialog()' on a null object reference
at com.app.notes.AddReminder.onClick(AddReminder.java:261)
public class AddReminder extends AppCompatActivity implements
android.view.View.OnClickListener`{
CustomDateTimePicker custom = null;
TextView txt_Time;
TextView txt_Date;
TextView txt_Day;
EditText et_Reminder_Title;
EditText et_Reminder_Description;
ImageButton btn_Submit_Reminder;
public static String var_Reminder_Title;
public String var_Reminder_Description;
public String var_Reminder_Time;
public String var_Reminder_Date;
public String var_Reminder_Day;
public int var_Not_Day;
public int var_Not_Month;
public int var_Not_Year;
public int var_Not_Hour;
public int var_Not_Min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_reminder);
txt_Time = (TextView) findViewById(R.id.txtEditTime);
txt_Time.setOnClickListener(this);
txt_Date = (TextView) findViewById(R.id.txtEditDate);
txt_Date.setOnClickListener(this);
txt_Day = (TextView) findViewById(R.id.txtEditDay);
txt_Day.setOnClickListener(this);
et_Reminder_Title= (EditText) findViewById(R.id.etEditReminderTitle);
et_Reminder_Description = (EditText) findViewById(R.id.etReminderDescription);
btn_Submit_Reminder = (ImageButton) findViewById(R.id.imgBtnSubmitReminder);
btn_Submit_Reminder.setOnClickListener(this);
try {
custom = new CustomDateTimePicker(AddReminder.this,
new CustomDateTimePicker.ICustomDateTimeListener() {
#Override
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName,
int hour24, int hour12, int min, int sec,
String AM_PM) {
txt_Time.setText(hour12 + ":" + min + " " + AM_PM);
txt_Date.setText(calendarSelected
.get(Calendar.DAY_OF_MONTH)
+ "/" + (monthNumber + 1) + "/" + year);
txt_Day.setText(weekDayFullName);
var_Not_Hour = hour24;
var_Not_Min = min;
var_Not_Month = monthNumber;
var_Not_Day = calendarSelected
.get(Calendar.DAY_OF_MONTH);
var_Not_Year = year;
}
#Override
public void onCancel() {
}
});
/**
* Pass Directly current time format it will return AM and PM if you set
* false
*/
custom.set24HourFormat(false);
/**
* Pass Directly current data and time to show when ita pop up
*/
custom.setDate(Calendar.getInstance());
}
catch (Exception ex){
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Calendar Initialization Failed...", Toast.LENGTH_LONG).show();
}
findViewById(R.id.button_date).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
custom.showDialog();
}
});
}
public void getValues(){
var_Reminder_Title = et_Reminder_Title.getText().toString();
var_Reminder_Time = txt_Time.getText().toString();
var_Reminder_Date = txt_Date.getText().toString();
var_Reminder_Day = txt_Day.getText().toString();
var_Reminder_Description = et_Reminder_Description.getText().toString();
}
public boolean validate()
{
boolean allValid = true;
if(et_Reminder_Title.getText().toString().trim().length() == 0)
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
et_Reminder_Title.setError("Please Enter a Reminder Title here");
}
});
}
if(txt_Time.getText() == "Time")
{
allValid = false;
runOnUiThread(new Runnable() {
#Override
public void run() {
et_Reminder_Title.setError("Tap Here to Select a Due Date and Time");
}
});
}
return allValid;
}
public void addReminder(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS reminders(ReminderId INTEGER PRIMARY KEY AUTOINCREMENT, ReminderTitle Text,ReminderTime Text,ReminderDate Text,ReminderDay Text, ReminderDescription Text);");
db.execSQL("INSERT INTO reminders(ReminderTitle,ReminderTime,ReminderDate,ReminderDay,ReminderDescription) VALUES('"+var_Reminder_Title+"','"+var_Reminder_Time+"','"+var_Reminder_Date+"','"+var_Reminder_Day+"','"+var_Reminder_Description+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Reminder Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Reminder Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void addNotification(){
SQLiteDatabase db = null;
db = openOrCreateDatabase("NTA_DB", MODE_PRIVATE, null);
try {
db.execSQL("CREATE TABLE IF NOT EXISTS notifications(NotificationId INTEGER PRIMARY KEY AUTOINCREMENT, NotificationTitle Text);");
db.execSQL("INSERT INTO notifications(NotificationTitle) VALUES('"+var_Reminder_Title+"');");
db.close();
Toast.makeText(AddReminder.this, "" +
"Notification Added Successfully", Toast.LENGTH_LONG).show();
}catch(Exception ex) {
ex.printStackTrace();
Toast.makeText(AddReminder.this, "Sorry! Notification Cannot be Saved", Toast.LENGTH_LONG).show();
db.close();
}
}
public void remind(){
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// set for 30 seconds later
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + 30000, alarmIntent);
Toast.makeText(AddReminder.this, "Set Alarm", Toast.LENGTH_LONG).show();
}
public void al(){
// for Alarm 25/12/2012 at 12.00
Calendar myAlarmDate = Calendar.getInstance();
myAlarmDate.setTimeInMillis(System.currentTimeMillis());
myAlarmDate.set(var_Not_Year, var_Not_Month, var_Not_Day, var_Not_Hour, var_Not_Min, 0);
//Toast.makeText(AddReminder.this, ""+var_Not_Year+" "+ var_Not_Month+" "+ var_Not_Day+" "+var_Not_Hour+" "+var_Not_Min+" "+ 0, Toast.LENGTH_LONG).show();
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
//Create pending intent & register it to your alarm notifier class
Intent intent0 = new Intent(this, AlarmReceiver.class);
//intent0.putExtra("Ringtone",getResources().getResourceName(R.raw.bbm_tone));
intent0.putExtra("Heading",var_Reminder_Title);
PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent0, 0);
//set timer you want alarm to work (here I have set it to 7.20pm)
//Intent intent0 = new Intent(this, OldEntryRemover.class);
/* Calendar timeOff9 = Calendar.getInstance();
timeOff9.set(Calendar.MONTH,12);
timeOff9.set(Calendar.DAY_OF_MONTH,1);
timeOff9.set(Calendar.YEAR,2015);
timeOff9.set(Calendar.HOUR_OF_DAY, 16);
timeOff9.set(Calendar.MINUTE, 45);
timeOff9.set(Calendar.SECOND, 0);
*/
//set that timer as a RTC Wakeup to alarm manager object
alarmMgr0.set(AlarmManager.RTC_WAKEUP, myAlarmDate.getTimeInMillis(), pendingIntent0);
// Toast.makeText(AddReminder.this, "Alarm", Toast.LENGTH_LONG).show();
}
#Override
public void onBackPressed ()
{
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.txtEditTime || v.getId() == R.id.txtEditDate || v.getId() == R.id.txtEditDay){
// custom.showDialog();
}
else if(v.getId() == R.id.imgBtnSubmitReminder) {
if (validate() == true) {
getValues();
addReminder();
// addNotification();
al();
Intent intent = new Intent(AddReminder.this, FrontScreen.class);
startActivity(intent);
finish();
}
}
}
}
this is custom date time picker class which is having the method showDialogue and it is using in the previous class. It is working perfectly on the version is less than 5.0 API but it is crashing on the version of 5.1 error is datetimepicker cannot be initialized.
public class CustomDateTimePicker implements android.view.View.OnClickListener {
private DatePicker datePicker;
private TimePicker timePicker;
private ViewSwitcher viewSwitcher;
private final int SET_DATE = 100, SET_TIME = 101, SET = 102, CANCEL = 103;
private Button btn_setDate, btn_setTime, btn_set, btn_cancel;
private Calendar calendar_date = null;
private Activity activity;
private ICustomDateTimeListener iCustomDateTimeListener = null;
private Dialog dialog;
private boolean is24HourView = true, isAutoDismiss = true;
private int selectedHour, selectedMinute;
public CustomDateTimePicker(Activity a,
ICustomDateTimeListener customDateTimeListener) {
activity = a;
iCustomDateTimeListener = customDateTimeListener;
dialog = new Dialog(activity);
// Context context = new ContextThemeWrapper(new MyContextWrapper, android.R.style.Theme_Holo_Light_Dialog);
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});
/*
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
resetData();
}
});*/
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
View dialogView = getDateTimePickerLayout();
dialog.setContentView(dialogView);
}
public View getDateTimePickerLayout() {
LinearLayout.LayoutParams linear_match_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
LinearLayout.LayoutParams linear_wrap_wrap = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
FrameLayout.LayoutParams frame_match_wrap = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams button_params = new LinearLayout.LayoutParams(
0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
LinearLayout linear_main = new LinearLayout(activity);
linear_main.setLayoutParams(linear_match_wrap);
linear_main.setOrientation(LinearLayout.VERTICAL);
linear_main.setGravity(Gravity.CENTER);
LinearLayout linear_child = new LinearLayout(activity);
linear_child.setLayoutParams(linear_wrap_wrap);
linear_child.setOrientation(LinearLayout.VERTICAL);
LinearLayout linear_top = new LinearLayout(activity);
linear_top.setLayoutParams(linear_match_wrap);
btn_setDate = new Button(activity);
btn_setDate.setLayoutParams(button_params);
btn_setDate.setText("Set Date");
btn_setDate.setId(SET_DATE);
btn_setDate.setOnClickListener(this);
btn_setTime = new Button(activity);
btn_setTime.setLayoutParams(button_params);
btn_setTime.setText("Set Time");
btn_setTime.setId(SET_TIME);
btn_setTime.setOnClickListener(this);
linear_top.addView(btn_setDate);
linear_top.addView(btn_setTime);
viewSwitcher = new ViewSwitcher(activity);
viewSwitcher.setLayoutParams(frame_match_wrap);
datePicker = new DatePicker(activity);
timePicker = new TimePicker(activity);
timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
selectedHour = hourOfDay;
selectedMinute = minute;
}
});
viewSwitcher.addView(timePicker);
viewSwitcher.addView(datePicker);
LinearLayout linear_bottom = new LinearLayout(activity);
linear_match_wrap.topMargin = 8;
linear_bottom.setLayoutParams(linear_match_wrap);
btn_set = new Button(activity);
btn_set.setLayoutParams(button_params);
btn_set.setText("Set");
btn_set.setId(SET);
btn_set.setOnClickListener(this);
btn_cancel = new Button(activity);
btn_cancel.setLayoutParams(button_params);
btn_cancel.setText("Cancel");
btn_cancel.setId(CANCEL);
btn_cancel.setOnClickListener(this);
linear_bottom.addView(btn_set);
linear_bottom.addView(btn_cancel);
linear_child.addView(linear_top);
linear_child.addView(viewSwitcher);
linear_child.addView(linear_bottom);
linear_main.addView(linear_child);
//Invisible Calender View
datePicker.getCalendarView().setVisibility(View.GONE);
return linear_main;
}
public void showDialog() {
if (!dialog.isShowing()) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
selectedHour = calendar_date.get(Calendar.HOUR_OF_DAY);
selectedMinute = calendar_date.get(Calendar.MINUTE);
timePicker.setIs24HourView(is24HourView);
timePicker.setCurrentHour(selectedHour);
timePicker.setCurrentMinute(selectedMinute);
datePicker.updateDate(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DATE));
dialog.show();
btn_setDate.performClick();
btn_setTime.performClick();
}
}
public void setAutoDismiss(boolean isAutoDismiss) {
this.isAutoDismiss = isAutoDismiss;
}
public void dismissDialog() {
if (!dialog.isShowing())
dialog.dismiss();
}
public void setDate(Calendar calendar) {
if (calendar != null)
calendar_date = calendar;
}
public void setDate(Date date) {
if (date != null) {
calendar_date = Calendar.getInstance();
calendar_date.setTime(date);
}
}
public void setDate(int year, int month, int day) {
if (month < 12 && month >= 0 && day < 32 && day >= 0 && year > 100
&& year < 3000) {
calendar_date = Calendar.getInstance();
calendar_date.set(year, month, day);
}
}
public void setTimeIn24HourFormat(int hourIn24Format, int minute) {
if (hourIn24Format < 24 && hourIn24Format >= 0 && minute >= 0
&& minute < 60) {
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = true;
}
}
public void setTimeIn12HourFormat(int hourIn12Format, int minute,
boolean isAM) {
if (hourIn12Format < 13 && hourIn12Format > 0 && minute >= 0
&& minute < 60) {
if (hourIn12Format == 12)
hourIn12Format = 0;
int hourIn24Format = hourIn12Format;
if (!isAM)
hourIn24Format += 12;
if (calendar_date == null)
calendar_date = Calendar.getInstance();
calendar_date.set(calendar_date.get(Calendar.YEAR),
calendar_date.get(Calendar.MONTH),
calendar_date.get(Calendar.DAY_OF_MONTH), hourIn24Format,
minute);
is24HourView = false;
}
}
public void set24HourFormat(boolean is24HourFormat) {
is24HourView = is24HourFormat;
}
public interface ICustomDateTimeListener {
public void onSet(Dialog dialog, Calendar calendarSelected,
Date dateSelected, int year, String monthFullName,
String monthShortName, int monthNumber, int date,
String weekDayFullName, String weekDayShortName, int hour24,
int hour12, int min, int sec, String AM_PM);
public void onCancel();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case SET_DATE:
btn_setTime.setEnabled(true);
btn_setDate.setEnabled(false);
viewSwitcher.showNext();
break;
case SET_TIME:
btn_setTime.setEnabled(false);
btn_setDate.setEnabled(true);
viewSwitcher.showPrevious();
break;
case SET:
if (iCustomDateTimeListener != null) {
int month = datePicker.getMonth();
int year = datePicker.getYear();
int day = datePicker.getDayOfMonth();
calendar_date.set(year, month, day, selectedHour,
selectedMinute);
iCustomDateTimeListener.onSet(dialog, calendar_date,
calendar_date.getTime(), calendar_date
.get(Calendar.YEAR),
getMonthFullName(calendar_date.get(Calendar.MONTH)),
getMonthShortName(calendar_date.get(Calendar.MONTH)),
calendar_date.get(Calendar.MONTH), calendar_date
.get(Calendar.DAY_OF_MONTH),
getWeekDayFullName(calendar_date
.get(Calendar.DAY_OF_WEEK)),
getWeekDayShortName(calendar_date
.get(Calendar.DAY_OF_WEEK)), calendar_date
.get(Calendar.HOUR_OF_DAY),
getHourIn12Format(calendar_date
.get(Calendar.HOUR_OF_DAY)), calendar_date
.get(Calendar.MINUTE), calendar_date
.get(Calendar.SECOND), getAMPM(calendar_date));
}
if (dialog.isShowing() && isAutoDismiss)
dialog.dismiss();
break;
case CANCEL:
if (iCustomDateTimeListener != null)
iCustomDateTimeListener.onCancel();
if (dialog.isShowing())
dialog.dismiss();
break;
}
}
/**
* #param date
* date in String
* #param fromFormat
* format of your <b>date</b> eg: if your date is 2011-07-07
* 09:09:09 then your format will be <b>yyyy-MM-dd hh:mm:ss</b>
* #param toFormat
* format to which you want to convert your <b>date</b> eg: if
* required format is 31 July 2011 then the toFormat should be
* <b>d MMMM yyyy</b>
* #return formatted date
*/
public static String convertDate(String date, String fromFormat,
String toFormat) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(fromFormat);
Date d = simpleDateFormat.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
simpleDateFormat = new SimpleDateFormat(toFormat);
simpleDateFormat.setCalendar(calendar);
date = simpleDateFormat.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
private String getMonthFullName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getMonthShortName(int monthNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM");
simpleDateFormat.setCalendar(calendar);
String monthName = simpleDateFormat.format(calendar.getTime());
return monthName;
}
private String getWeekDayFullName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private String getWeekDayShortName(int weekDayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, weekDayNumber);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE");
simpleDateFormat.setCalendar(calendar);
String weekName = simpleDateFormat.format(calendar.getTime());
return weekName;
}
private int getHourIn12Format(int hour24) {
int hourIn12Format = 0;
if (hour24 == 0)
hourIn12Format = 12;
else if (hour24 <= 12)
hourIn12Format = hour24;
else
hourIn12Format = hour24 - 12;
return hourIn12Format;
}
private String getAMPM(Calendar calendar) {
String ampm = (calendar.get(Calendar.AM_PM) == (Calendar.AM)) ? "AM"
: "PM";
return ampm;
}
enter image description here
private void resetData() {
calendar_date = null;
is24HourView = true;
}
public static String pad(int integerToPad) {
if (integerToPad >= 10 || integerToPad < 0)
return String.valueOf(integerToPad);
else
return "0" + String.valueOf(integerToPad);
}
}

How to get value TimePicker inside AlertDialog?

I have a TimePicker that is generated within a AlertDialog so do not know what your ID. How to get the value set by the user? I want to send you a notification to him every day at this time (I already have a prompt notification).
And then: what they suggest?`
/** Private members of the class */
private TextView MostraTime;
private Button Time;
private int DayHour;
private int DayMinute;
Intent VoltaMenu;
/**
* This integer will uniquely define the dialog to be used for displaying
* time picker.
*/
static final int TIME_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify);
/** Capture our View elements */
MostraTime = (TextView) findViewById(R.id.MostraTempo);
Time = (Button) findViewById(R.id.TempoAlerta);
/** Listener for click event of the button */
Time.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
/** Get the current time */
final Calendar cal = Calendar.getInstance();
DayHour = cal.get(Calendar.HOUR_OF_DAY);
DayMinute = cal.get(Calendar.MINUTE);
/** Display the current time in the TextView */
updateDisplay();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this, mTimeSetListener, DayHour,
DayMinute, false);
}
return null;
}
/** Callback received when the user "picks" a time in the dialog */
private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
DayHour = hourOfDay;
DayMinute = minute;
updateDisplay();
displayToast();
}
};
/** Updates the time in the TextView */
private void updateDisplay() {
MostraTime.setText(new StringBuilder().append(pad(DayHour)).append(":")
.append(pad(DayMinute)));
}
/** Displays a notification when the time is updated */
private void displayToast() {
VoltaMenu = new Intent(MenuNotificacao.this, Prefs.class);
startActivity(VoltaMenu);
Toast.makeText(
this,
new StringBuilder().append(
getResources().getString(R.string.horario) + " ")
.append(MostraTime.getText()), Toast.LENGTH_SHORT)
.show();
}
/** Add padding to numbers less than ten */
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}
`
try this link to get value from timepicker..link is
http://androidexample.com/Time_Picker_With_AM_PM_Values_-_Android_Example/index.php?view=article_discription&aid=86&aaid=109
/********* display current time on screen Start ********/
final Calendar c = Calendar.getInstance();
// Current Hour
hour = c.get(Calendar.HOUR_OF_DAY);
// Current Minute
minute = c.get(Calendar.MINUTE);
// set current time into output textview
updateTime(hour, minute);
/********* display current time on screen End ********/
// Add Button Click Listener
addButtonClickListener();
}
public void addButtonClickListener() {
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this, timePickerListener, hour, minute,
false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minutes) {
// TODO Auto-generated method stub
hour = hourOfDay;
minute = minutes;
updateTime(hour,minute);
}
};
private static String utilTime(int value) {
if (value < 10)
return "0" + String.valueOf(value);
else
return String.valueOf(value);
}
// Used to convert 24hr format to 12hr format with AM/PM values
private void updateTime(int hours, int mins) {
String timeSet = "";
if (hours > 12) {
hours -= 12;
timeSet = "PM";
} else if (hours == 0) {
hours += 12;
timeSet = "AM";
} else if (hours == 12)
timeSet = "PM";
else
timeSet = "AM";
String minutes = "";
if (mins < 10)
minutes = "0" + mins;
else
minutes = String.valueOf(mins);
// Append in a StringBuilder
String aTime = new StringBuilder().append(hours).append(':')
.append(minutes).append(" ").append(timeSet).toString();
output.setText(aTime);
}
I make it like this
public void alertDialog(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View alerdialogV = inflater.inflate(R.layout.alert_layout, null);
builder.setView(alerdialogV);
builder.setTitle("1st aletdialog");
final TextView timeset = (TextView) alerdialogV.findViewById(R.id.timepicker);
final TextView timeset1 = (TextView) alerdialogV.findViewById(R.id.timepicker2);
timeset.setOnClickListener(getL(timeset));
timeset1.setOnClickListener(getL(timeset1));
builder.show();
here is method
#NonNull
private View.OnClickListener getL(final TextView t) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int hour = c.getTime().getHours();
int minut = c.getTime().getMinutes();
MyTimePicker tpd = new MyTimePicker(ctx, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
t.setText(hourOfDay + ":" + minute);
}
}, hour,minut, is24HrView);
tpd.show();
}
};
}
and this is mycustom Timepicker
public class MyTimePicker extends TimePickerDialog {
private final static int TIME_PICKER_INTERVAL = 5;
private TimePicker timePicker;
private final OnTimeSetListener callback;
public MyTimePicker(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
super(context, TimePickerDialog.THEME_HOLO_DARK, callBack, hourOfDay, minute / TIME_PICKER_INTERVAL, is24HourView);
this.callback = callBack;
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (callback != null && timePicker != null) {
timePicker.clearFocus();
callback.onTimeSet(timePicker, timePicker.getCurrentHour(),
timePicker.getCurrentMinute() * TIME_PICKER_INTERVAL);
}
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
try {
Class<?> classForid = Class.forName("com.android.internal.R$id");
Field timePickerField = classForid.getField("timePicker");
this.timePicker = (TimePicker) findViewById(timePickerField
.getInt(null));
Field field = classForid.getField("minute");
NumberPicker mMinuteSpinner = (NumberPicker) timePicker
.findViewById(field.getInt(null));
mMinuteSpinner.setMinValue(0);
mMinuteSpinner.setMaxValue((60 / TIME_PICKER_INTERVAL) - 1);
List<String> displayedValues = new ArrayList<String>();
for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
displayedValues.add(String.format("%02d", i));
}
mMinuteSpinner.setDisplayedValues(displayedValues
.toArray(new String[0]));
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to restrict user to set date based on other date from date picker in android

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 {
}

Categories