I am working on a simple application that passes a parcelable from one activity to another. In MainActivity, I have a LinkedList that holds the information taken from the parcelable. However, each time i return to MainActivity, the Object previously stored in the LinkedList (Parcelable) is deleted. What am I doing wrong? I have spent literally the past 3 days trying to figure out why it isn't saving anything but the logic looks solid. So I updated to use startActivityForResult and now the Parcelable in MainActivity is NULL.
public class MainActivity extends Activity {
int tasks;
final static String TASK_KEY = "newTask";
final static String INDEX_KEY = "LLIndex";
Task t;
ScrollView scrollView;
LinearLayout taskHolder;
LinkedList<Task> taskList = new LinkedList<Task>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d("In onCreate", "here");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvCounter = (TextView) findViewById(R.id.textView1);
taskHolder = (LinearLayout) findViewById(R.id.linearScroll);
//Checks for parcelable
if(getIntent().hasExtra(Create.TASK_KEY)){
Log.d("Task", "You've got mail!");
Task t = (Task)getIntent().getExtras().getParcelable(Create.TASK_KEY);
taskList.add(t);
addNewTask(t);
}
Log.d("LL size", Integer.toString(tasks));
tasks = taskList.size();
tvCounter.setText(Integer.toString(tasks) + " " + getApplicationContext().getResources().getString(R.string.tv_task));
Button plusButton = (Button) findViewById(R.id.button1);
plusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Create.class);
startActivity(i);
}
});
}
void addNewTask(Task t) {
tasks++;
Log.d("In addNewTask method", t.toString());
LinearLayout newTaskLayout = new LinearLayout(getApplicationContext());
newTaskLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newTaskLayout.setLayoutParams(params);
//int bottom = (int) getResources().getDimension(R.dimen.margin_bottom);
//int left = (int) getResources().getDimension(R.dimen.margin_left);
//params.setMargins(left, 0, 0, bottom);
TextView tvTitle = new TextView(getApplicationContext());
TextView tvDate = new TextView(getApplicationContext());
TextView tvTime = new TextView(getApplicationContext());
tvTitle.setTextColor(Color.BLACK);
tvDate.setTextColor(Color.BLACK);
tvTime.setTextColor(Color.BLACK);
tvTitle.setTypeface(tvTitle.getTypeface(), Typeface.BOLD);
tvTitle.setText(t.getName());
tvDate.setText(t.getDate());
tvTime.setText(t.getTime());
newTaskLayout.addView(tvTitle);
newTaskLayout.addView(tvDate);
newTaskLayout.addView(tvTime);
//params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//params.setMargins(0, 0, 0, 0);
//tvDate.setLayoutParams(params);
//tvTime.setLayoutParams(params);
//tvTitle.setTextSize(getResources().getDimension(R.dimen.size_of_text));
taskHolder.addView(newTaskLayout);
final int index = ((ViewGroup) newTaskLayout.getParent()).indexOfChild(newTaskLayout);
newTaskLayout.setOnClickListener(new View.OnClickListener() {//bind listener
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,Display.class);
i.putExtra(TASK_KEY, taskList.get(index));
i.putExtra(INDEX_KEY, index);
startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==1){
Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
Log.d("Task", "You've got mail!");
if(getIntent().hasExtra(Create.TASK_KEY)){
Task t = (Task)getIntent().getExtras().getParcelable(Create.TASK_KEY);
taskList.add(t);
addNewTask(t);
}
Log.d("LL size", Integer.toString(tasks));
tasks = taskList.size();
tvCounter.setText(Integer.toString(tasks) + " " + getApplicationContext().getResources().getString(R.string.tv_task));
}
else{
Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
}
}
}
Create Class:
public class Create extends Activity{
private int year;
private int month;
private int day;
private String name, date, time, priority;
final static String TASK_KEY = "newTask";
static final int PICK_CONTACT_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
final Calendar cal = Calendar.getInstance();
//Current Date
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
final EditText etTitle = (EditText) findViewById(R.id.editText1);
final EditText etDate = (EditText) findViewById(R.id.editText2);
final EditText etTime = (EditText) findViewById(R.id.editText3);
final RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
//int selectedId = rg.getCheckedRadioButtonId();
//final RadioButton radioSelected = (RadioButton) findViewById(selectedId);
Button save = (Button) findViewById(R.id.button1);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get checked radio button
RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
// TODO Auto-generated method stub
name = etTitle.getText().toString();
date = etDate.getText().toString();
time = etTime.getText().toString();
priority = (String) rb.getTag();
Task t = new Task(name, date, time, priority);
Log.d("task", t.toString());
Intent i = new Intent(Create.this, MainActivity.class);
i.putExtra(TASK_KEY, t); //Puts new Task object into Intent to send
setResult(1,i);
finish();
}
});
etDate.setKeyListener(null);
etTime.setKeyListener(null);
final DatePickerDialog.OnDateSetListener datePick = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
private void updateLabel() {
// TODO Auto-generated method stub
String myFormat = "MM/dd/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
etDate.setText(sdf.format(cal.getTime()));
}
};
etDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Do whatever
new DatePickerDialog(Create.this, datePick, cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
etTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar curTime = Calendar.getInstance();
int hour = curTime.get(Calendar.HOUR_OF_DAY);
int minute = curTime.get(Calendar.MINUTE);
TimePickerDialog tp;
tp = new TimePickerDialog(Create.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String am_pm;
String minuteStr;
Log.d("hour", Integer.toString(selectedHour));
if (selectedHour == 0){
selectedHour = 12;
am_pm = "AM";
}else if(selectedHour == 12){
selectedHour = 12;
am_pm = "PM";
}else if(selectedHour > 12) {
selectedHour -= 12;
am_pm = "PM";
}else{
am_pm = "AM";
}
if(selectedMinute < 10){
minuteStr = "0" + Integer.toString(selectedMinute);
}else{
minuteStr = Integer.toString(selectedMinute);
}
etTime.setText( selectedHour + ":" + minuteStr + " " + am_pm);
}
}, hour, minute, false);//Yes 24 hour time
tp.setTitle("Set Time");
tp.show();
}
});
}
}
If I understand the question correctly, you have a list of messages in MainActivity, and you're starting the Create intent to create a new message. Then, on save, you're starting a new MainActivity with the new message to add to the list.
The problem with this approach is that a new MainActivity instance will be created each time, with a new (empty) LinkedList in it.
I would look at using startActivityForResult() to run the Create activity, and use setResult() and finish() within Create to return the new message.
You should also look at saving the contents of the list within 'onSaveInstanceState', to handle the destruction and recreation of your MainActivity (e.g. when the user rotates their device).
Related
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.
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();
}
}
}
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 {
}
Is there any way to save the state of the application because the application calls onCreate() everytime the android phone is locked. When I unlocked it, the app calls the onCreate() method and start again.. BTW my app is like text twist. When I unlock the screen a new word is shown, instead of the current one.. The score is also reset as well as the time.. How can I work on this? Please help.. It's still unanswered..
This is the whole code of my activity..
public class friend extends Activity {
//score
ScoreHandler scHandler;
Score sc;
int totalScore;
//words
//DatabaseHelper dbHelp;
DBHelper dbHelp;
public String randomWord;
//speech
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
//shake
private SensorManager mSensorManager;
private ShakeEventListener mSensorListener;
//timer
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private TextView timeText;
private final long startTime = 180 * 1000;
private final long interval = 1 * 1000;
private long timeLeft;
private int gameScore;
private TextView shuffleView;
TextView scoreView;
//Animation
Animation myFadeInAnimation;
Animation myFadeOutAnimation;
Animation leftToRight;
//sliding
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
Context context;
static final String STATE_SCORE = "currentScore";
static final String STATE_WORD = "currentWord";
static final String STATE_TIME = "currentTime";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
} else {
// Probably initialize members with default values for a new instance
}
setContentView(R.layout.friend);
leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);
ImageButton next = (ImageButton) findViewById(R.id.nextround_game);
next.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, friend1.class);
startActivity(intent);
}
});
ImageButton giveUp = (ImageButton) findViewById(R.id.surrender_game);
giveUp.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setClass(friend.this, GameOverActivity.class);
startActivity(intent);
}
});
//score
//timer
timeText = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
timeText.setText(timeText.getText() + String.valueOf(startTime/1000));
countDownTimer.start();
timerHasStarted = true;
this.removeAll();
dbHelp = new DBHelper(this);
randomWord = dbHelp.random();
System.out.println(randomWord);
String wordCaps = randomWord.toUpperCase();
final String finalWord = shuffle(wordCaps);
shuffleView = (TextView) findViewById(R.id.jumble);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/American Captain.ttf");
shuffleView.setTypeface(type);
shuffleView.setText(finalWord);
//shake
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
public void onShake() {
//String str = (String) stringList.remove(selectedWord);
String wordOutput = shuffle(finalWord);
TextView tv = (TextView) findViewById(R.id.jumble);
tv.setText(wordOutput);
}
});
//speech
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timeText.setText("0:00");
playSound(R.raw.clock_whistle);
ImageView timeIsUp = (ImageView) findViewById(R.id.time_is_up);
timeIsUp.startAnimation(leftToRight);
}
#Override
public void onTick(long millisUntilFinished) {
long minutes = (millisUntilFinished / (1000*60)) % 60;
long seconds = (millisUntilFinished / 1000) % 60 ;
timeLeft = millisUntilFinished/1000;
timeText.setText("" + minutes + ":" + seconds );
if (timeLeft <= 10) {
playSound(R.raw.clock_beep);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
System.out.println(""+text.get(0));
String spoken = text.get(0);
if(dbHelp.exists(spoken)){
if(dbHelp.isLongest(spoken)){
Toast.makeText(getApplicationContext(), "You have guessed the longest word! ", Toast.LENGTH_SHORT).show();
}
gameScore = text.get(0).length()*10;
scoreView = (TextView) findViewById(R.id.scoreView);
scoreView.setText(""+gameScore);
scHandler = new ScoreHandler(this);
scHandler.addScore(new Score(1,gameScore));
int cumulativeScore = scHandler.accumulateScores();
scoreView.setText(""+cumulativeScore);
playSound(R.raw.correct);
WordGuessedHandler guessedWord = new WordGuessedHandler(this);
guessedWord.addGuessedWord(new Words(1,spoken));
ImageView img = (ImageView) findViewById(R.id.awesome);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
img.startAnimation(myFadeInAnimation);
img.startAnimation(myFadeOutAnimation);
}else{
playSound(R.raw.poweng);
ImageView image = (ImageView) findViewById(R.id.wrong);
myFadeInAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_in);
myFadeOutAnimation = AnimationUtils.loadAnimation(this, R.layout.fade_out);
image.startAnimation(myFadeInAnimation);
image.startAnimation(myFadeOutAnimation);
}
}
}
}
}
public String shuffle(String input){
List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
System.out.println(output.toString());
return output.toString();
}
#Override
public void onBackPressed()
{
Intent inMain=new Intent(friend.this, MainActivity.class);
inMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(inMain);
countDownTimer.cancel();
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE,gameScore);
savedInstanceState.putLong(STATE_TIME,timeLeft);
savedInstanceState.putString(STATE_TIME,randomWord);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
gameScore = savedInstanceState.getInt(STATE_SCORE);
timeLeft = savedInstanceState.getLong(STATE_TIME);
randomWord = savedInstanceState.getString(STATE_WORD);
}
//sliding menu onChange
#Override
public void onContentChanged()
{
super.onContentChanged();
mOpenButton = (Button) findViewById( R.id.button_open );
mDrawer = (MultiDirectionSlidingDrawer) findViewById( R.id.drawer);
/* GridView gridView;
ArrayList ArrayofName = new ArrayList();
WordHandler db = new WordHandler(this);*/
TextView txt = (TextView) findViewById(R.id.text);
txt.setText("Hello There!");
GridView gridview = (GridView) findViewById(R.id.gridView1);
WordGuessedHandler guessed = new WordGuessedHandler(this);
List <WordGuessed> guessedList = guessed.getAllWordGuessed();
List<String> wordsList = new ArrayList<String>();
for(WordGuessed wg:guessedList){
wordsList.add(wg.getWord());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, wordsList);
gridview.setAdapter(adapter);
}
public void playSound(int sound) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.setLooping(false);
mp.setVolume(1,1);
mp.start();
}
public void removeAll()
{
ScoreHandler scHandler = new ScoreHandler(this);
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = scHandler.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
db.delete("scores_table", null, null);
db.close();
}
}
This question answers your question.
https://developer.android.com/training/basics/activity-lifecycle/index.html
Please use the onPause() and onResume() methods in your main Activity to solve this problem. If both method aren't defined, your app will go to the next methods in the lifecycle, which will be onCreate() and other methods. Read more here.
It is also possible to save your current instance by using onSaveInstance(Bundle b) and onRestoreInstance(Bundle b)
PS: someone has asked it earlier, and wrote a small example to use the onSaveInstance and onRestoreInstance (if you want to use it) here.
I have a TimePicker which I'd like to use to determine a length of time a user can stay connected. Lets say the time now is 10:00 if the user selects 11:00 - I'd like the source code below to determine that there are 60 minutes between the current time - and the time selected and set that to a string/long (minutes) which I then have displayed as a textview.
I've coded everything as I thought it should be - however the textview never seems to update with minutes value. Everytime I attempt to view the data - I get a value of 0 not matter what the timepicker is set to.
Anyone have any suggestions? I'm stumped at the moment and I'm not sure what else to try.
ADDEDITDEVICE.JAVA (where the timepicker and minutes determination takes place)
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Date date = new Date();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
date.setMinutes(tp.getCurrentMinute());
date.setHours(tp.getCurrentHour());
Long.toString(minutes);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
}
long minutes = ((new Date()).getTime() - date.getTime()) / (1000 * 60);
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
Long.toString(minutes),
ssidTextView.getText().toString());
}
}
}
VIEW COUNTRY.JAVA (where the minutes data set by the timepicker should be visible)
public class ViewCountry extends NfcBeamWriterActivity {
private static final String TAG = ViewCountry.class.getName();
protected Message message;
NfcAdapter mNfcAdapter;
private static final int MESSAGE_SENT = 1;
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView timeTv;
private TextView ssidTv;
private TextView combined;
private TextView minutes;
//String timetest = "300";
// String a="\"";
// String b="\"";
// String message1 = a + ssidTv.getText().toString() +"," +
// capTv.getText().toString()+b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("name", true);
editor.putBoolean("cap", true);
editor.putBoolean("code", true);
editor.putBoolean("time", true);
editor.putBoolean("ssid",true);
editor.putBoolean("minutes",true);
editor.putBoolean("timetest",true);
editor.commit();
setDetecting(true);
startPushing();
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
timeTv = (TextView) findViewById(R.id.timeEdit);
codeTv = (TextView) findViewById(R.id.codeText);
ssidTv = (TextView) findViewById(R.id.wifiSSID);
minutes = (TextView) findViewById(R.id.Minutes);
}
#Override
protected void onResume() {
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params) {
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result) {
super.onPostExecute(result);
result.moveToFirst();
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int timeIndex = result.getColumnIndex("time");
int ssidIndex = result.getColumnIndex("ssid");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
timeTv.setText(result.getString(timeIndex));
codeTv.setText(result.getString(codeIndex));
ssidTv.setText(result.getString(ssidIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.editItem:
Intent addEditContact = new Intent(this, AddEditDevice.class);
// addEditContact.putExtra(CountryList.ROW_ID, rowID);
// addEditContact.putExtra("name", nameTv.getText());
// addEditContact.putExtra("cap", capTv.getText());
// addEditContact.putExtra("code", codeTv.getText());
startActivity(addEditContact);
return true;
case R.id.user1SettingsSave:
Intent Tap = new Intent(this, Tap.class);
startActivity(Tap);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact() {
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector dbConnector = new DatabaseConnector(
ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(Long... params) {
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result) {
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
});
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":" + timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
minutes,
Long.toString(minutes),
ssidTextView.getText().toString());
You have that code to add a contact, BUT in your database conector you have:
public void insertContact(String name,
String cap,
String code,
String time,
long minutes,
String ssid,
String string){
I think that don't match, so this is why don't insert correctly.
BTW i can't comment at the moment because i need 50 reputation.
Regards
USE CREATE TABLE IF NOT EXISTS T/N then your problem wil be solved.
otherwise it will override the current table at the same time all the data will be lost.