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.
Related
I am building an app where I am suppose to view my call log in a list and make a call when pressing an item in the list.
What is the best option for this?
I wanna try to make a custom adapter but I am unsure if it is the right way to do or if there is an easier way?
Thanks for any help!
For the moment I am using a text view and a string buffer to populate the list with my call log.
public class LastCallActivity extends Activity {
private List<LastCallModel> wlistCalls;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_call);
if (ContextCompat.checkSelfPermission(LastCallActivity.this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(LastCallActivity.this, Manifest.permission.READ_CALL_LOG)) {
ActivityCompat.requestPermissions(LastCallActivity.this, new String[]{Manifest.permission.READ_CALL_LOG}, 1);
} else {
ActivityCompat.requestPermissions(LastCallActivity.this, new String[]{Manifest.permission.READ_CALL_LOG}, 1);
}
} else {
// do stuff
TextView textView = (TextView) findViewById(R.id.textViewen);
textView.setText(getCallDetails());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(LastCallActivity.this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted!", Toast.LENGTH_SHORT).show();
TextView textView = (TextView) findViewById(R.id.textViewen);
textView.setText(getCallDetails());
}
} else {
Toast.makeText(this, "No permission GRANTED!", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
private String getCallDetails() {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details:\n\n");
while (managedCursor.moveToNext()) {
String phName = managedCursor.getString(name);
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
if (phName != null && phNumber != null) {
wlistCalls.add(new LastCallModel(phName, phNumber));
}
Date callDayTime = new Date(Long.valueOf(callDate));
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm");
String dateString = formatter.format(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nName: " + phName + "\nPhone Number: " + phNumber + " \nCallType: " + dir + "\nCall Date: " + dateString + "\nCall Duration: " + callDuration);
sb.append("\n-------------");
sb.append("\n*************");
sb.append("\n*************");
}
managedCursor.close();
return sb.toString();
}
}
I solved it by using a RecyclerView with an custom adapter!
This is my custom adapter.
public class LastCallAdapter extends RecyclerView.Adapter<LastCallAdapter.ViewHolder> {
private LayoutInflater layoutInflater;
private Context mContext;
private ArrayList<String> phoneNumber;
public LastCallAdapter(Context mContext, ArrayList<String> phoneNumber) {
this.mContext = mContext;
this.phoneNumber = phoneNumber;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = layoutInflater.from(parent.getContext()).inflate(R.layout.items_contacts, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.number.setText(phoneNumber.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callDial = new Intent(Intent.ACTION_DIAL);
callDial = callDial.setData(Uri.parse("tel:"+phoneNumber.get(position)));
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
mContext.startActivity(callDial);
return;
}
Toast.makeText(mContext, phoneNumber.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return phoneNumber.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView number;
LinearLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
number = itemView.findViewById(R.id.contact_number);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
And this method in the main activity for starting the adapter
private void startAdapter(){
RecyclerView recyclerView = findViewById(R.id.recyclerViewen);
LastCallAdapter lastCallAdapter = new LastCallAdapter(this, phoneNumbers);
recyclerView.setAdapter(lastCallAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
I am trying to get a ListView to appear in a new activity. I can see the record ID in the logcat, and I can see that the proper ID is being selected in debug view, but when I go to the new activity the list array is empty.
This is what I am seeing in debug view:
In the logcat I see this:
2018-10-07 11:39:09.286 12624-12624/ca.rvogl.tpbcui D/SAVEDLEAGUEID_VAL: 1
2018-10-07 11:39:09.286 12624-12624/ca.rvogl.tpbcui D/LEAGUEID_VAL: android.support.v7.widget.AppCompatTextView{e67a170 G.ED..... ......I. 0,0-0,0 #7f080112 app:id/tvLeagueId}
2018-10-07 11:39:09.293 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-SQL: SQL used = >>>>SELECT * FROM bowlers WHERE league_id = '1' ORDER BY timestamp DESC<<<<
2018-10-07 11:39:09.298 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-CNT: Number of rows retrieved = 0
2018-10-07 11:39:09.299 12624-12624/ca.rvogl.tpbcui D/GETALLBOWLERS-CNT: Number of elements in bowlerslist = 0
As you can see from the logcat the savedLeagueId is being passed to the SQLite Query that is suppose to be getting the list of Bowlers for the listview. However the number of elements in the bowlerslist is 0.
I have gone through the code over and over again but I am unable to isolate where the issue is.
LeagueAdapter.java
public class LeagueAdapter extends RecyclerView.Adapter<LeagueAdapter.MyViewHolder> {
private Context context;
private List<League> leaguesList;
public void notifyDatasetChanged(List<League> newleagueslist) {
leaguesList.clear();
leaguesList.addAll(newleagueslist);
super.notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView basescore;
public TextView basescorepercentage;
public TextView id;
public TextView wins;
public TextView losses;
public TextView timestamp;
public TextView buttonViewOption;
public MyViewHolder(View view) {
super(view);
id = view.findViewById( R.id.tvLeagueId);
name = view.findViewById(R.id.tvSeriesName );
basescore = view.findViewById(R.id.tvBaseScore );
basescorepercentage = view.findViewById(R.id.tvBaseScorePercentage );
wins = view.findViewById(R.id.tvLeagueWins );
losses = view.findViewById(R.id.tvLeagueLosses );
timestamp = view.findViewById(R.id.timestamp);
buttonViewOption = (TextView) view.findViewById(R.id.buttonViewOptions);
}
}
public LeagueAdapter(Context context, List<League> leaguesList) {
this.context = context;
this.leaguesList = leaguesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.listview_league, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
League league = leaguesList.get(position);
int id = league.getId();
Log.d("id", String.valueOf(id));
int leagueId = id;
Log.d("leagueId", String.valueOf(leagueId));
holder.id.setText(String.valueOf(leagueId));
holder.name.setText(league.getName());
holder.basescore.setText(league.getBaseScore());
holder.basescorepercentage.setText(league.getBaseScorePercentage());
holder.wins.setText(league.getWins());
holder.losses.setText(league.getLosses());
/*if (league.getAverage() != "") {
holder.leagueAverage.setText(String.format("League Avg: %s", league.getAverage()));
} else {
holder.leagueAverage.setText(String.format("League Avg: %s", "0"));
}*/
//Formatting And Displaying Timestamp
holder.timestamp.setText(formatDate(league.getTimestamp()));
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(context, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.league_options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.profile:
Log.d("leagueId", String.valueOf(position));
int leagueId = league.getId();
String savedLeagueId = String.valueOf(id);
Intent myIntent = new Intent(context, LeagueProfileViewActivity.class);
myIntent.putExtra("leagueId", leagueId);
context.startActivity(myIntent);
break;
case R.id.delete:
((MainActivity) context).deleteLeague(position);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String leagueId = String.valueOf(leaguesList.get(position).getId());
int leagueId = league.getId();
String savedLeagueId = String.valueOf(id);
Log.d("leagueId", String.valueOf(position));
Intent myIntent = new Intent(context, BowlerActivity.class);
myIntent.putExtra("leagueId", savedLeagueId);
context.startActivity(myIntent);
}
});
}
#Override
public int getItemCount() {
return leaguesList.size();
}
//Formatting TimeStamp to 'EEE MMM dd yyyy (HH:mm:ss)'
//Input : 2018-05-23 9:59:01
//Output : Wed May 23 2018 (9:59:01)
private String formatDate(String dateStr) {
try {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse(dateStr);
SimpleDateFormat fmtOut = new SimpleDateFormat("EEE MMM dd yyyy (HH:mm:ss)");
return fmtOut.format(date);
} catch (ParseException e) {
}
return "";
}
}
I am moving to the BowlerActivity using holder.name, where I am passing the League ID using an intent.
BowlerActivity.java
public class BowlerActivity extends AppCompatActivity {
private BowlerAdapter mAdapter;
private final List<Bowler> bowlersList = new ArrayList<>();
private TextView noBowlersView;
private DatabaseHelper db;
private TextView leagueId;
private String savedLeagueId;
/*private TextView seriesleagueId;
private String seriesLeagueId;
private TextView bowlerAverage;
private TextView bowlerHandicap;
private String savedBowlerAverage;*/
private static final String PREFS_NAME = "prefs";
private static final String PREF_BLUE_THEME = "blue_theme";
private static final String PREF_GREEN_THEME = "green_theme";
private static final String PREF_ORANGE_THEME = "purple_theme";
private static final String PREF_RED_THEME = "red_theme";
private static final String PREF_YELLOW_THEME = "yellow_theme";
#Override protected void onResume() {
super.onResume();
db = new DatabaseHelper( this );
mAdapter.notifyDatasetChanged( db.getAllBowlers(savedLeagueId ) );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
//Use Chosen Theme
SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
boolean useBlueTheme = preferences.getBoolean( PREF_BLUE_THEME, false );
if (useBlueTheme) {
setTheme( R.style.AppTheme_Blue_NoActionBar );
}
boolean useGreenTheme = preferences.getBoolean( PREF_GREEN_THEME, false );
if (useGreenTheme) {
setTheme( R.style.AppTheme_Green_NoActionBar );
}
boolean useOrangeTheme = preferences.getBoolean( PREF_ORANGE_THEME, false );
if (useOrangeTheme) {
setTheme( R.style.AppTheme_Orange_NoActionBar );
}
boolean useRedTheme = preferences.getBoolean( PREF_RED_THEME, false );
if (useRedTheme) {
setTheme( R.style.AppTheme_Red_NoActionBar );
}
boolean useYellowTheme = preferences.getBoolean( PREF_YELLOW_THEME, false );
if (useYellowTheme) {
setTheme( R.style.AppTheme_Yellow_NoActionBar );
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bowler);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull( getSupportActionBar() ).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
overridePendingTransition(0, 0);
}
});
savedLeagueId = String.valueOf(getIntent().getStringExtra("leagueId"));
leagueId = findViewById(R.id.tvLeagueId);
Log.d("SAVEDLEAGUEID_VAL", String.valueOf(savedLeagueId));
Log.d("LEAGUEID_VAL", String.valueOf(leagueId));
/*bowlerAverage = (TextView) findViewById(R.id.tvBowlerAverage);
bowlerHandicap = (TextView) findViewById(R.id.tvBowlerHandicap);*/
CoordinatorLayout coordinatorLayout = findViewById( R.id.coordinator_layout );
RecyclerView recyclerView = findViewById( R.id.recycler_view );
noBowlersView = findViewById(R.id.empty_bowlers_view);
db = new DatabaseHelper(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_bowler_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//showBowlerDialog(false, null, -1);
boolean shouldUpdate = false;
int bowlerId = -1;
String leagueId = String.valueOf(savedLeagueId);
Intent intent = new Intent(getApplicationContext(), BowlerProfileEditActivity.class);
intent.putExtra("shouldUpdate", shouldUpdate);
intent.putExtra("leagueId", leagueId);
intent.putExtra("bowlerId", bowlerId);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
}
});
mAdapter = new BowlerAdapter(this, bowlersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
toggleEmptyBowlers();
}
//Inserting New Bowler In The Database And Refreshing The List
private void createBowler(String leagueId, String bowlerName) {
String bowlerAverage = "0";
//Inserting Bowler In The Database And Getting Newly Inserted Bowler Id
long id = db.insertBowler(savedLeagueId, bowlerName, bowlerAverage);
//Get The Newly Inserted Bowler From The Database
Bowler n = db.getBowler(savedLeagueId);
if (n != null) {
//Adding New Bowler To The Array List At Position 0
bowlersList.add( 0, n );
//Refreshing The List
mAdapter.notifyDatasetChanged(db.getAllBowlers(savedLeagueId));
//mAdapter.notifyDataSetChanged();
toggleEmptyBowlers();
}
}
//Updating Bowler In The Database And Updating The Item In The List By Its Position
private void updateBowler(String bowlerName, int position) {
Bowler n = bowlersList.get(position);
//Updating Bowler Text
n.setLeagueId(savedLeagueId);
n.setName(bowlerName);
//Updating The Bowler In The Database
db.updateBowler(n);
//Refreshing The List
bowlersList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyBowlers();
}
//Deleting Bowler From SQLite Database And Removing The Bowler Item From The List By Its Position
public void deleteBowler(int position) {
Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Series will be deleted.", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.YELLOW)
.setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View v) {
//Deleting The Bowler From The Database
db.deleteBowler(bowlersList.get(position));
//Removing The Bowler From The List
bowlersList.remove(position);
mAdapter.notifyItemRemoved(position);
//db.leagueAverageScore(savedLeagueId);
toggleEmptyBowlers();
}
});
snackbar.show();
}
//Toggling List And Empty Bowler View
private void toggleEmptyBowlers() {
//You Can Check bowlerList.size() > 0
if (db.getBowlersCount() > 0) {
noBowlersView.setVisibility( View.GONE);
} else {
noBowlersView.setVisibility( View.VISIBLE);
}
}
#Override
public void onRestart() {
super.onRestart();
//When BACK BUTTON is pressed, the activity on the stack is restarted
//Do what you want on the refresh procedure here
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate( R.menu.menu_main, menu );
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
overridePendingTransition(0, 0);
return true;
}
return super.onOptionsItemSelected( item );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
//Check If Request Code Is The Same As What Is Passed - Here It Is 1
if(requestCode==1)
{
String savedLeagueId=data.getStringExtra("seriesLeagueId");
String seriesBowlerId=data.getStringExtra("seriesBowlerId");
bowlersList.addAll(db.getAllBowlers(savedLeagueId));
}
}
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
overridePendingTransition(0, 0);
}
}
Bowler Methods in DatabaseHelper.java
public long insertBowler(String leagueId, String bowlerName, String bowlerAverage) {
String bowlerHandicap ="0";
//Get Writable Database That We Want To Write Data Too
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//`id` and `timestamp` Will Be Inserted Automatically
values.put(Bowler.COLUMN_LEAGUE_ID, leagueId);
values.put(Bowler.COLUMN_NAME, bowlerName);
values.put(Bowler.COLUMN_BOWLER_AVERAGE, bowlerAverage);
values.put(Bowler.COLUMN_BOWLER_HANDICAP, bowlerHandicap);
//Insert Row
//long id = db.insert(Bowler.TABLE_NAME, null, values);
long id = db.insertOrThrow( Bowler.TABLE_NAME, null, values );
Log.d("INSERTBOWLER","Number of bowlers in db = " + String.valueOf( DatabaseUtils.queryNumEntries(db,Bowler.TABLE_NAME)));
//Close Database Connection
db.close();
//Return Newly Inserted Row Id
return id;
}
public Bowler getBowler(String leagueId) {
//Get Readable Database If We Are Not Inserting Anything
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query( Bowler.TABLE_NAME,
new String[]{Bowler.COLUMN_ID, Bowler.COLUMN_LEAGUE_ID, Bowler.COLUMN_NAME, Bowler.COLUMN_BOWLER_AVERAGE, Bowler.COLUMN_BOWLER_HANDICAP, Bowler.COLUMN_TIMESTAMP},
Bowler.COLUMN_LEAGUE_ID + "=?",
new String[]{String.valueOf(leagueId)}, null, null, null, null);
Bowler bowler = null;
if (cursor.moveToFirst()) {
//Prepare Bowler Object
bowler = new Bowler(
cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)),
cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
//Close Database Connection
cursor.close();
return bowler;
} else {
return bowler;
}
}
public List<Bowler> getAllBowlers(String leagueId) {
List<Bowler> bowlers = new ArrayList<>();
//Select All Query
String selectQuery = "SELECT * FROM " + Bowler.TABLE_NAME + " WHERE " + Bowler.COLUMN_LEAGUE_ID + " = '" + leagueId + "'" + " ORDER BY " +
Bowler.COLUMN_TIMESTAMP + " DESC";
Log.d("GETALLBOWLERS-SQL","SQL used = >>>>" +selectQuery + "<<<<");
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
Log.d("GETALLBOWLERS-CNT","Number of rows retrieved = " + String.valueOf(cursor.getCount()));
//Looping Through All Rows And Adding To The List
if (cursor.moveToFirst()) {
do {
Bowler bowler = new Bowler();
bowler.setId(cursor.getInt(cursor.getColumnIndex(Bowler.COLUMN_ID)));
bowler.setLeagueId(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_LEAGUE_ID)));
bowler.setName(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_NAME)));
bowler.setAverage(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_AVERAGE)));
bowler.setHandicap(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_BOWLER_HANDICAP)));
bowler.setTimestamp(cursor.getString(cursor.getColumnIndex(Bowler.COLUMN_TIMESTAMP)));
bowlers.add(bowler);
} while (cursor.moveToNext());
}
cursor.close();
//Close Database Connection
db.close();
Log.d("GETALLBOWLERS-CNT","Number of elements in bowlerslist = " + String.valueOf(bowlers.size()));
//Return Bowlers List
return bowlers;
}
public int getBowlersCount() {
String countQuery = "SELECT * FROM " + Bowler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
//Return The Count
return count;
}
public int updateBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Bowler.COLUMN_LEAGUE_ID, bowler.getLeagueId());
values.put(Bowler.COLUMN_NAME, bowler.getName());
values.put(Bowler.COLUMN_BOWLER_AVERAGE, bowler.getAverage());
//Updating Row
return db.update(Bowler.TABLE_NAME, values, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf(bowler.getId())});
}
public void deleteBowler(Bowler bowler) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete( Bowler.TABLE_NAME, Bowler.COLUMN_ID + " = ?",
new String[]{String.valueOf( bowler.getId())});
db.close();
}
I am hoping that someone will be able to point out what I am doing incorrectly in order to fix this issue.
If any additional information is need please let me know and I will post it.
I have figured out why all my new bowler entries have an id of 2. In my edit Bowler Profile Activity I have the following : leagueId = String.valueOf(getIntent().getIntExtra("leagueId",2)); The default value is 2 and because I was not grabbing the information being passed to the new Activity in the proper manner the app was always using 2 as the BowlerId.
I changed the code that was capturing the information from the intent to the following:
Intent intent = getIntent();
leagueId = intent.getStringExtra("leagueId");
With this change I was able to capture all the bowlers that belong to a particular league. I only realized that I was passing the information incorrectly after reading through the following post:
Pass a String from one Activity to another Activity in Android
I have a problem with creating two tables in sqlite and display them in RecyclerView and more specifically with one table. I add to the question a screenshot of the application so that you can understand what the problem is.
I have 3 activities: FirstActivity, in which there are two buttons (Monday and Tuesday) -> from this activity we go to MainActivity, on the button selection (Monday) -> save data in table_MON and after selection button (Tuesday) in the table_Tue. The problem is that everything works correctly, when we press the button (Monday) we can save the training, edit and delete it. However, when we go to the button (Tuesday) we can only add training, but we can't edit or delete them. However, I have no idea why? I am already looking at this problem for a week and I have no idea what is going on, maybe a fresh look will help solve the problem.
My database consists of two tables: tableMon and tableTue, but I use the same columns in it (exercises, weight etc ..), and separate _id, and I do not know if this can be a problem. Perhaps the problem is that I use MainActivity in both cases?
Screenshot App:
FirstActivity
enter image description here
Click button Monday --> MainActivity.class
enter image description here
Click button Tuesday --> MainActivity.class
enter image description here
Button Tuesday --> DetailActivity and her is the problem I can't update and delete training.
enter image description here
FirstActivity.class
public class FirstActivity extends AppCompatActivity {
Button buttonMon, buttonTue;
public static final String BUTTON_KEY1 = "BUTTON_KEY";
public static final String BUTTON_KEY2 = "BUTTON_KEY2";
public static final String BUTTON_VALUE = "1";
public static final String BUTTON_VALUE2 = "2";
public static boolean WAS_RUNNING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
buttonMon = (Button) findViewById(R.id.buttonMonday);
buttonTue = (Button) findViewById(R.id.buttonTuesday);
WAS_RUNNING = false;
//OPEN THE SAME MAINACTIVITY
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
//OPEN THE SAME MAINACTIVITY
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WAS_RUNNING = true;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private ArrayList<Training> trainingArrayList = new ArrayList<Training>();
private EditText editTextExercise, editTextWeight, editTextRepeat, editTextSeries;
private Button buttonSave, buttonBack;
private Dialog dialog;
private String value;
private String value2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();}});
if(bundle == null)
{return;}
value = bundle.getString(FirstActivity.BUTTON_KEY1);
value2 = bundle.getString(FirstActivity.BUTTON_KEY2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
if(value != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh MON TABLE
refreshMonTable();
}else if(value2 != null) {
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
myAdapter = new MyAdapter(this, trainingArrayList);
//Refresh TUE TABLE
refreshTueTable(); }}
public void showDialog()
{
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_layout);
editTextExercise = (EditText) dialog.findViewById(editTextExerciseDialog);
editTextWeight = (EditText) dialog.findViewById(editTextWeightDialog);
editTextRepeat = (EditText) dialog.findViewById(editTextRepeatDialog);
editTextSeries = (EditText) dialog.findViewById(editTextSeriesDialog);
buttonSave = (Button) dialog.findViewById(buttonSaveDialog);
buttonBack = (Button) dialog.findViewById(buttonBackDialog);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();}});
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(value != null) {
saveDataMon(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
} else if(value2 != null) {
saveDataTue(editTextExercise.getText().toString(),
String.valueOf(editTextWeight.getText().toString()),
String.valueOf(editTextRepeat.getText().toString()),
String.valueOf(editTextSeries.getText().toString()));
}}});
dialog.show();}
private void saveDataMon(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addMon(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();}
adapter.closeDB();
refreshMonTable();}
private void saveDataTue(String exercise, String weight, String repeat, String series)
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
long result = adapter.addTue(exercise, weight, repeat, series);
if (result > 0) {
editTextExercise.setText("");
editTextWeight.setText("");
editTextRepeat.setText("");
editTextSeries.setText("");
dialog.dismiss();
} else {
Snackbar.make(editTextExercise, "Unable to save!", Snackbar.LENGTH_SHORT).show();
}
adapter.closeDB();
refreshTueTable();}
private void refreshMonTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningMon();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String cwiczenie = cursor.getString(1);
String ciezar = cursor.getString(2);
String powtorzenia = cursor.getString(3);
String serie = cursor.getString(4);
Training training = new Training(id, cwiczenie, ciezar, powtorzenia, serie);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB(); }
private void refreshTueTable()
{
DBAdapter adapter = new DBAdapter(this);
adapter.openDatabase();
trainingArrayList.clear();
Cursor cursor = adapter.getAllTreningTue();
if(cursor != null)
{ if(cursor.moveToFirst())
{
do {
int id = cursor.getInt(0);
String exercise = cursor.getString(1);
String weight = cursor.getString(2);
String repeat = cursor.getString(3);
String series = cursor.getString(4);
Training training = new Training(id, exercise, weight, repeat, series);
trainingArrayList.add(training);
}while (cursor.moveToNext());}}
recyclerView.setAdapter(myAdapter);
adapter.closeDB();
}
#Override
protected void onResume() {
super.onResume();
if(value != null) {
//REFRESH
refreshMonTable();
} else if(value2 != null) {
refreshTueTable();}}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Exit?")
.setMessage("Do you want to exit?")
.setNegativeButton("No", null)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.super.onBackPressed();
}
}).create().show();}}
DetailActivity.class
public class DetailActivity extends AppCompatActivity {
private EditText editTextExerciseDetail, editTextWeightDetail, editTextRepeatDetail, editTextSeriesDetail;
private Button buttonUpdate;
private Button buttonDelete;
String mon;
String tue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Bundle intent = getIntent().getExtras();
if(intent == null)
{return;}
mon = intent.getString(MyAdapter.KEY_MON);
tue = intent.getString(MyAdapter.KEY_TUE);
final int idT = intent.getInt("id");
String cwiczenie = intent.getString("exercise");
String ciezar = intent.getString("weight");
String powtorzenia = intent.getString("repeat");
String serie = intent.getString("series");
editTextExerciseDetail = (EditText) findViewById(R.id.exerciseEditTxtDetail);
editTextWeightDetail = (EditText) findViewById(R.id.weightEditTextDetail);
editTextRepeatDetail = (EditText) findViewById(R.id.repeatEditTextDetail);
editTextSeriesDetail = (EditText) findViewById(R.id.seriesEditTextDetail);
buttonUpdate = (Button) findViewById(R.id.updateBtn);
buttonDelete = (Button) findViewById(R.id.deleteBtn);
editTextExerciseDetail.setText(cwiczenie);
editTextWeightDetail.setText(ciezar);
editTextRepeatDetail.setText(powtorzenia);
editTextSeriesDetail.setText(serie);
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mon != null) {
updateMon(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());
} else if(tue != null) {
updateTue(idT, editTextExerciseDetail.getText().toString(),
editTextWeightDetail.getText().toString(),
editTextRepeatDetail.getText().toString(),
editTextSeriesDetail.getText().toString());}}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setMessage("Do you want delete this training?")
.setTitle("Delete")
.create();
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mon != null) {
deleteMon(idT);
}else if(tue != null){
deleteTue(idT);}}});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}});
builder.show();}});}
//Update MON TABLE
private void updateMon(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateMon(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//Update TUE TABLE
private void updateTue(int id, String newExercise, String newWeight, String newRepeat, String newSeries)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.updateTue(id, newExercise, newWeight, newRepeat, newSeries);
if(result > 0)
{
editTextExerciseDetail.setText(newExercise);
editTextWeightDetail.setText(newWeight);
editTextRepeatDetail.setText(newRepeat);
editTextSeriesDetail.setText(newSeries);
this.finish();
Snackbar.make(editTextExerciseDetail, "Updated Succesfully", Snackbar.LENGTH_SHORT).show();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to updated", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
//DELETE MON TABLE
private void deleteMon(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteMon(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();
}
//DELETE TUE TABLE
private void deleteTue(int id)
{
DBAdapter dbAdapter = new DBAdapter(this);
dbAdapter.openDatabase();
long result = dbAdapter.deleteTue(id);
if(result>0)
{
this.finish();
}else
{
Snackbar.make(editTextExerciseDetail, "Unable to deleted", Snackbar.LENGTH_SHORT).show();
}
dbAdapter.closeDB();}
#Override
protected void onResume() {
super.onResume();}
#Override
protected void onRestart() {
super.onRestart();}}
DBHelper.class
public class DBHelper extends SQLiteOpenHelper {
//DB
static final String DB_NAME = "training_db";
static final int DB_VERSION = '1';
//TABLES
static final String TB_NAME_MON = "training_tb_mon";
static final String TB_NAME_TUE = "training_tb_tue";
//COLUMNS
static final String ROW_ID_MON = "id_Mon";
static final String ROW_ID_TUE = "id_Tue";
//ROW
static final String EXERCISE = "exercise";
static final String WEIGHT = "weight";
static final String REPEAT = "repeat";
static final String SERIES = "series";
static final String CREATE_TB_MON = "CREATE TABLE training_tb_mon (id_Mon INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
static final String CREATE_TB_TUE = "CREATE TABLE training_tb_tue (id_Tue INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "exercise TEXT NOT NULL, weight TEXT NOT NULL, repeat TEXT NOT NULL, series TEXT NOT NULL);";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TB_MON);
db.execSQL(CREATE_TB_TUE);
}catch (Exception e) {
e.printStackTrace();
}}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_MON);
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME_TUE);
onCreate(db);
}}
DBAdapter.class
public class DBAdapter {
Context c;
DBHelper dbHelper;
SQLiteDatabase db;
public DBAdapter(Context c) {
this.c = c;
dbHelper = new DBHelper(c);
}
//OPEN DATABASE
public DBAdapter openDatabase() {
try {
db = dbHelper.getWritableDatabase();
}catch (SQLiteException e) {
e.printStackTrace();
}
return this;
}
//CLOSE DATABASE
public void closeDB()
{
try{
dbHelper.close();
}catch (SQLiteException e){
e.printStackTrace();
}}
//Add training Mon
public long addMon(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON, contentValues);
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;}
//Add training Tue
public long addTue(String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
return db.insert(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE, contentValues);
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//REFRESH TABLE MON
public long updateMon(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_MON, id);
return db.update(DBHelper.TB_NAME_MON, contentValues, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace(); }
return 0;
}
//REFRESH TABLE TUE
public long updateTue(int id, String exercise, String weight, String repeat, String series)
{
try{
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.EXERCISE, exercise);
contentValues.put(DBHelper.WEIGHT, weight);
contentValues.put(DBHelper.REPEAT, repeat);
contentValues.put(DBHelper.SERIES, series);
contentValues.put(DBHelper.ROW_ID_TUE, id);
return db.update(DBHelper.TB_NAME_TUE, contentValues, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0;
}
//DELETE ROW TABLE MON
public long deleteMon(int id)
{
try{
return db.delete(DBHelper.TB_NAME_MON, DBHelper.ROW_ID_MON + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();
}
return 0; }
//DELETE ROW TABLE TUE
public long deleteTue(int id)
{
try{
return db.delete(DBHelper.TB_NAME_TUE, DBHelper.ROW_ID_TUE + " =?", new String[]{String.valueOf(id)});
}catch (SQLiteException e) {
e.printStackTrace();}
return 0;}
//ALL TRAINING TABLE MON
public Cursor getAllTreningMon() {
try{
String[] columns = {DBHelper.ROW_ID_MON, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_MON, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;
}
//ALL TRAINING TABLE TUE
public Cursor getAllTreningTue() {
try{
String[] columns = {DBHelper.ROW_ID_TUE, DBHelper.EXERCISE, DBHelper.WEIGHT, DBHelper.REPEAT, DBHelper.SERIES};
return db.query(DBHelper.TB_NAME_TUE, columns, null, null, null, null, null);
}catch (SQLiteException e)
{
e.printStackTrace();
}
return null;}}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<Training> training;
public static String KEY_MON = "KEY_MON";
public static String KEY_TUE = "KEY_TUE";
public static String VALUE_MON = "10";
public static String VALUE_TUE = "20";
public <T extends Training> MyAdapter(Context c, ArrayList<Training> training) {
this.c = c;
this.training = training;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(c).inflate(R.layout.card_view_model, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
#Override
public int getItemCount() {
return training.size();}}
Training.class
public class Training {
int id;
String exercise;
String weight;
String repeat;
String series;
public Training(int id, String exercise, String weight, String repeat, String series) {
this.id = id;
this.exercise = exercise;
this.weight = weight;
this.repeat = repeat;
this.series = series;
}
public int getId() {return id;}
public void setId(int id) { this.id = id;}
public String getExercise() {return exercise; }
public void setExercise(String exercise) {this.exercise = exercise;}
public String getWeight() {return weight;}
public void setWeight(String weight) {this.weight = weight; }
public String getRepeat() {return repeat;}
public void setRepeat(String repeat) { this.repeat = repeat;}
public String getSeries() {return series;}
public void setSeries(String series) {this.series = series;}}
In your MyAdapter class, in the onItemClick method, within the onBindViewHolder method, the second check, for Tue processing, would never run.
You have :-
if (FirstActivity.WAS_RUNNING) {
.......
} else if (FirstActivity.WAS_RUNNING) {
.......
}
i.e. you are saying if FirstActivity was not running and the FirstActivity was running then do your stuff.
i.e. the else will only be entered if FirstActivity were not running, in which case the if (FirstActivity.WAS_RUNNING) would never be true.
Perhaps have 2 booleans MONDAY_WAS_RUNNING and TUESDAY_WAS RUNNING (you could use just the existing boolean by setting that to false in the buttonTue listener doing the Tuesday processing in the else (without an if) ).
e.g. :-
FirstActivity class :-
public static boolean MONDAY_WAS_RUNNING;
public static boolean TUESDAY_WAS_RUNNING;
..........
buttonMon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MONDAY_WAS_RUNNING = true;
TUESDAY_WAS_RUNNING = false;
Intent intent = new Intent(FirstActivity.this, MainActivity.class);
intent.putExtra(BUTTON_KEY1, BUTTON_VALUE);
startActivity(intent);
} });
buttonTue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TUESDAY_WAS_RUNNING = true;
MONDAY_WAS_RUNNING = false;
Intent i = new Intent(FirstActivity.this, MainActivity.class);
i.putExtra(BUTTON_KEY2, BUTTON_VALUE2);
startActivity(i);
} });}}
MyAdapter :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
if (FirstActivity.MONDAY_WAS_RUNNING)
{Intent intent = new Intent(c, DetailActivity.class);
intent.putExtra(KEY_MON, VALUE_MON);
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
} else if (FirstActivity.TUESDAY_WAS_RUNNING)
{Intent intent2 = new Intent(c, DetailActivity.class);
intent2.putExtra(KEY_TUE, VALUE_TUE);
intent2.putExtra("id", training.get(position).getId());
intent2.putExtra("exercise", training.get(position).getExercise());
intent2.putExtra("weight", training.get(position).getWeight());
intent2.putExtra("repeat", training.get(position).getRepeat());
intent2.putExtra("series", training.get(position).getSeries());
c.startActivity(intent2);
}}});}
However I'd probably go for :-
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
holder.textViewModel.setText(training.get(position).getExercise());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v) {
Intent intent = new Intent(c, DetailActivity.class);
if (FirstActivity.MONDAY_WAS_RUNNING) {
intent.putExtra(KEY_MON, VALUE_MON);
} else {
intent.putExtra(KEY_TUE, VALUE_TUE);
}
intent.putExtra("id", training.get(position).getId());
intent.putExtra("exercise", training.get(position).getExercise());
intent.putExtra("weight", training.get(position).getWeight());
intent.putExtra("repeat", training.get(position).getRepeat());
intent.putExtra("series", training.get(position).getSeries());
c.startActivity(intent);
});
}
Note! the above code has not been checked, rather it is in-principle code
I am trying to display entire Downloads directory inside a ListView in an Activity. However, the app works sometime, other time crashes with a log :
E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 420)
java.lang.RuntimeException: Adding window failed
at android.view.ViewRootImpl.setView(ViewRootImpl.java:543)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:503)
at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:746)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:531)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3169)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here's the source code to the same Activity:
public class DownloadsActivity extends AppCompatActivity
{
private ListView listView = null;
//private EditText editText;
private DbAdapter_Files db;
private SimpleCursorAdapter adapter;
private SharedPreferences sharedPref;
//private TextView listBar;
private class_CustomViewPager viewPager;
private int top;
private int index;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloads);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.edit().putString("files_startFolder",
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()).apply();
//editText = (EditText) getActivity().findViewById(R.id.editText);
//listBar = (TextView)findViewById(R.id.listBar);
listView = (ListView)findViewById(R.id.listDownloads);
//viewPager = (class_CustomViewPager) getActivity().findViewById(R.id.viewpager);
//calling Notes_DbAdapter
db = new DbAdapter_Files(this);
db.open();
setFilesList();
}
private void setTitle () {
/*if (sharedPref.getString("sortDBF", "title").equals("title")) {
listBar.setText(getString(R.string.app_title_downloads) + " | " + getString(R.string.sort_title));
} else if (sharedPref.getString("sortDBF", "title").equals("file_date")) {
listBar.setText(getString(R.string.app_title_downloads) + " | " + getString(R.string.sort_date));
} else {
listBar.setText(getString(R.string.app_title_downloads) + " | " + getString(R.string.sort_extension));
}*/
Log.e("title","method called");
}
private void isEdited () {
index = listView.getFirstVisiblePosition();
View v = listView.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
}
private void setFilesList() {
deleteDatabase("files_DB_v01.db");
String path = sharedPref.getString("files_startFolder",
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
File f = new File(path);
final File[] files = f.listFiles();
// looping through all items <item>
if (files.length == 0) {
Snackbar.make(listView, R.string.toast_files, Snackbar.LENGTH_LONG).show();
}
for (File file : files) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String file_Name = file.getName();
String file_Size = getReadableFileSize(file.length());
String file_date = formatter.format(new Date(file.lastModified()));
String file_path = file.getAbsolutePath();
String file_ext;
if (file.isDirectory()) {
file_ext = ".";
} else {
try {
file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("."));
} catch (Exception e)
{
Log.e("Crash","1");
file_ext = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
}
}
db.open();
if(db.isExist(helper_main.secString(file_Name))) {
Log.i(TAG, "Entry exists" + file_Name);
} else {
db.insert(helper_main.secString(file_Name), file_Size, helper_main.secString(file_ext), helper_main.secString(file_path), file_date);
}
}
try {
db.insert("...", "", "", "", "");
} catch (Exception e)
{
Log.e("Crash","2");
Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
}
//display data
final int layoutstyle=R.layout.list_item;
int[] xml_id = new int[] {
R.id.textView_title_notes,
R.id.textView_des_notes,
R.id.textView_create_notes
};
String[] column = new String[] {
"files_title",
"files_content",
"files_creation"
};
final Cursor row = db.fetchAllData(DownloadsActivity.this);
adapter = new SimpleCursorAdapter(DownloadsActivity.this, layoutstyle,row,column, xml_id, 0) {
#Override
public View getView (final int position, View convertView, ViewGroup parent) {
Cursor row = (Cursor) listView.getItemAtPosition(position);
final String files_icon = row.getString(row.getColumnIndexOrThrow("files_icon"));
final String files_attachment = row.getString(row.getColumnIndexOrThrow("files_attachment"));
View v = super.getView(position, convertView, parent);
final ImageView iv = (ImageView) v.findViewById(R.id.icon_notes);
final ImageView iv2 = (ImageView) v.findViewById(R.id.icon_notes2);
iv.setVisibility(View.VISIBLE);
Uri uri = Uri.fromFile(new File(files_attachment));
if (files_icon.matches("")) {
iv.setVisibility(View.INVISIBLE);
iv2.setVisibility(View.VISIBLE);
iv.setImageResource(R.drawable.arrow_up_dark);
} else if (files_icon.matches("(.)")) {
iv.setImageResource(R.drawable.folder);
} else if (files_icon.matches("(.m3u8|.mp3|.wma|.midi|.wav|.aac|.aif|.amp3|.weba|.ogg)")) {
iv.setImageResource(R.drawable.file_music);
} else if (files_icon.matches("(.mpeg|.mp4|.webm|.qt|.3gp|.3g2|.avi|.flv|.h261|.h263|.h264|.asf|.wmv)")) {
iv.setImageResource(R.drawable.file_video);
} else if(files_icon.matches("(.gif|.bmp|.tiff|.svg|.png|.jpg|.JPG|.jpeg)")) {
try {
iv2.setVisibility(View.INVISIBLE);
Picasso.with(DownloadsActivity.this).load(uri).resize(76, 76).centerCrop().memoryPolicy(MemoryPolicy.NO_CACHE).into(iv);
} catch (Exception e)
{
Log.e("Crash","3");
Log.w("Browser", "Error load thumbnail", e);
iv.setImageResource(R.drawable.file_image);
}
} else if (files_icon.matches("(.vcs|.vcf|.css|.ics|.conf|.config|.java|.html)")) {
iv.setImageResource(R.drawable.file_xml);
} else if (files_icon.matches("(.apk)")) {
iv.setImageResource(R.drawable.android);
} else if (files_icon.matches("(.pdf)")) {
iv.setImageResource(R.drawable.file_pdf);
} else if (files_icon.matches("(.rtf|.csv|.txt|.doc|.xls|.ppt|.docx|.pptx|.xlsx|.odt|.ods|.odp)")) {
iv.setImageResource(R.drawable.file_document);
} else if (files_icon.matches("(.zip|.rar)")) {
iv.setImageResource(R.drawable.zip_box);
} else {
iv.setImageResource(R.drawable.file);
}
return v;
}
};
//display data by filter
final String note_search = sharedPref.getString("filter_filesBY", "files_title");
sharedPref.edit().putString("filter_filesBY", "files_title").apply();
/* editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
});*/
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchDataByFilter(constraint.toString(),note_search);
}
});
listView.setAdapter(adapter);
listView.setSelectionFromTop(index, top);
//onClick function
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
Cursor row2 = (Cursor) listView.getItemAtPosition(position);
final String files_icon = row2.getString(row2.getColumnIndexOrThrow("files_icon"));
final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));
final File pathFile = new File(files_attachment);
if(pathFile.isDirectory()) {
try {
sharedPref.edit().putString("files_startFolder", files_attachment).apply();
setFilesList();
} catch (Exception e)
{
Log.e("Crash","4");
Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
}
} else if(files_attachment.equals("")) {
try {
final File pathActual = new File(sharedPref.getString("files_startFolder",
Environment.getExternalStorageDirectory().getPath()));
sharedPref.edit().putString("files_startFolder", pathActual.getParent()).apply();
setFilesList();
} catch (Exception e)
{
Log.e("Crash","5");
Snackbar.make(listView, R.string.toast_directory, Snackbar.LENGTH_LONG).show();
}
} else {
helper_main.open(files_icon, DownloadsActivity.this, pathFile, listView);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
isEdited();
Cursor row2 = (Cursor) listView.getItemAtPosition(position);
final String files_title = row2.getString(row2.getColumnIndexOrThrow("files_title"));
final String files_attachment = row2.getString(row2.getColumnIndexOrThrow("files_attachment"));
final File pathFile = new File(files_attachment);
if (pathFile.isDirectory()) {
Snackbar snackbar = Snackbar
.make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG)
.setAction(R.string.toast_yes, new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPref.edit().putString("files_startFolder", pathFile.getParent()).apply();
deleteRecursive(pathFile);
setFilesList();
}
});
snackbar.show();
} else {
final CharSequence[] options = {
getString(R.string.choose_menu_2),
getString(R.string.choose_menu_3),
getString(R.string.choose_menu_4)};
final AlertDialog.Builder dialog = new AlertDialog.Builder(DownloadsActivity.this);
dialog.setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
dialog.setItems(options, new DialogInterface.OnClickListener() {
#SuppressWarnings("ResultOfMethodCallIgnored")
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals(getString(R.string.choose_menu_2))) {
if (pathFile.exists()) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, files_title);
sharingIntent.putExtra(Intent.EXTRA_TEXT, files_title);
Uri bmpUri = Uri.fromFile(pathFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_file))));
}
}
if (options[item].equals(getString(R.string.choose_menu_4))) {
Snackbar snackbar = Snackbar
.make(listView, R.string.bookmark_remove_confirmation, Snackbar.LENGTH_LONG)
.setAction(R.string.toast_yes, new View.OnClickListener() {
#Override
public void onClick(View view) {
pathFile.delete();
setFilesList();
}
});
snackbar.show();
}
if (options[item].equals(getString(R.string.choose_menu_3))) {
sharedPref.edit().putString("pathFile", files_attachment).apply();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 2, files_title, getString(R.string.bookmark_edit_title));
}
}
});
dialog.show();
}
return true;
}
});
}
#SuppressWarnings("ResultOfMethodCallIgnored")
private void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
deleteRecursive(child);
}
}
fileOrDirectory.delete();
}
private static String getReadableFileSize(long size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return valueOf(dec.format(fileSize) + suffix);
}
public void doBack() {
//BackPressed in activity will call this;
Snackbar snackbar = Snackbar
.make(listView, getString(R.string.toast_exit), Snackbar.LENGTH_SHORT)
.setAction(getString(R.string.toast_yes), new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadsActivity.this.finish();
}
});
snackbar.show();
}
public void fragmentAction () {
setTitle();
setFilesList();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.filter_title:
sharedPref.edit().putString("filter_filesBY", "files_title").apply();
setFilesList();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 1, "", getString(R.string.action_filter_title));
return true;
case R.id.filter_url:
sharedPref.edit().putString("filter_filesBY", "files_icon").apply();
setFilesList();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 1, "", getString(R.string.action_filter_url));
return true;
case R.id.filter_today:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal = Calendar.getInstance();
final String search = dateFormat.format(cal.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_today));
return true;
case R.id.filter_yesterday:
DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, -1);
final String search2 = dateFormat2.format(cal2.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search2);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_yesterday));
return true;
case R.id.filter_before:
DateFormat dateFormat3 = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal3 = Calendar.getInstance();
cal3.add(Calendar.DATE, -2);
final String search3 = dateFormat3.format(cal3.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search3);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_before));
return true;
case R.id.filter_month:
DateFormat dateFormat4 = new SimpleDateFormat("yyyy-MM", Locale.getDefault());
Calendar cal4 = Calendar.getInstance();
final String search4 = dateFormat4.format(cal4.getTime());
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setText(search4);
//listBar.setText(getString(R.string.app_title_bookmarks) + " | " + getString(R.string.filter_month));
return true;
case R.id.filter_own:
sharedPref.edit().putString("filter_filesBY", "files_creation").apply();
setFilesList();
//editText.setVisibility(View.VISIBLE);
//helper_editText.showKeyboard(getActivity(), editText, 1, "", getString(R.string.action_filter_create));
return true;
case R.id.filter_clear:
//editText.setVisibility(View.GONE);
setTitle();
//helper_editText.hideKeyboard(getActivity(), editText, 0, getString(R.string.app_title_history), getString(R.string.app_search_hint));
setFilesList();
return true;
case R.id.action_save_bookmark:
final File pathFile = new File(sharedPref.getString("pathFile", ""));
String inputTag = "";
File dir = pathFile.getParentFile();
File to = new File(dir,inputTag);
if(db.isExist(helper_main.secString(inputTag))){
Snackbar.make(listView, getString(R.string.toast_newTitle), Snackbar.LENGTH_LONG).show();
} else {
pathFile.renameTo(to);
pathFile.delete();
Snackbar.make(listView, R.string.bookmark_added, Snackbar.LENGTH_SHORT).show();
//editText.setVisibility(View.GONE);
setTitle();
//helper_editText.hideKeyboard(getActivity(), editText, 0, getString(R.string.app_title_bookmarks), getString(R.string.app_search_hint));
setFilesList();
}
return true;
case R.id.action_cancel:
//editText.setVisibility(View.GONE);
setTitle();
//helper_editText.hideKeyboard(getActivity(), editText, 0, getString(R.string.app_title_bookmarks), getString(R.string.app_search_hint));
setFilesList();
return true;
case R.id.sort_title:
sharedPref.edit().putString("sortDBF", "title").apply();
setFilesList();
setTitle();
return true;
case R.id.sort_extension:
sharedPref.edit().putString("sortDBF", "file_ext").apply();
setFilesList();
setTitle();
return true;
case R.id.sort_date:
sharedPref.edit().putString("sortDBF", "file_date").apply();
setFilesList();
setTitle();
return true;
case android.R.id.home:
viewPager.setCurrentItem(sharedPref.getInt("tab", 0));
return true;
}
return super.onOptionsItemSelected(item);
}
}
What could possibly be causing this exception, and what's the effective way to resolve this issue?
I am doing an app that lets you write activities to do.
On the main activity, there's a ListView, which shows the activities according to the date especified in a DatePicker inside a DialogFragment.
I'm using SQLite to save the activities, and so far there's no problem saving them.
If you long press an item of the ListView, a context menu appears with a single option "Delete Activity", calling the method removeActivity, which deletes the activity from the static ArrayList System.activities, that stores every activity created, AND should delete the activity from the database, using the activity's attribute cod, which is unique for every instance of an activity.
public class Main extends FragmentActivity {
int mDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int mMonth = Calendar.getInstance().get(Calendar.MONTH); // August, month
// starts from 0
int mYear = Calendar.getInstance().get(Calendar.YEAR);
ArrayList<String> listNames = new ArrayList<String>();
List<ActivityToDo> acts = System.activities;
boolean listHasItems = false;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
removeActivitesBeforeCurrentDate();
ToDoSQLiteHelper actdb = new ToDoSQLiteHelper(this, "db", null, 1);
SQLiteDatabase db = actdb.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM Activities", null);
System.activities.clear();
if (c.moveToFirst()) {
do {
ActivityToDo act = new ActivityToDo(c.getString(1),
c.getString(2), c.getString(3));
act.setDate(Integer.parseInt(c.getString(4)),
Integer.parseInt(c.getString(5)),
Integer.parseInt(c.getString(6)));
System.activities.add(act);
} while (c.moveToNext());
}
db.close();
setContentView(R.layout.main);
final Button btnNewAct = (Button) findViewById(R.id.btnNewAct);
final TextView txtV = (TextView) findViewById(R.id.txtPickDate);
final ListView listview = (ListView) findViewById(R.id.listview);
listNames.add("Pick date to search activity.");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listNames);
listview.setAdapter(adapter);
registerForContextMenu(listview);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (listHasItems) {
ActivityToDo a = acts.get(position);
String[] datosAct = new String[6];
datosAct[0] = a.getName();
datosAct[1] = a.getDescr();
datosAct[2] = a.getPriority();
datosAct[3] = Integer.toString(a.getDay());
datosAct[4] = Integer.toString(a.getMonth());
datosAct[5] = Integer.toString(a.getYear());
Intent i = new Intent();
i.setClass(getApplicationContext(), ShowActivity.class);
i.putExtra("datos", datosAct);
startActivity(i);
}
}
});
final Handler mHandler = new Handler() {
// This handles the message send from DatePickerDialogFragment on
// setting date
#Override
public void handleMessage(Message m) {
Bundle b = m.getData();
mDay = b.getInt("set_day");
mMonth = b.getInt("set_month");
mYear = b.getInt("set_year");
String date = "";
if (mDay < 10) {
date += "0" + mDay + "/";
} else {
date += mDay + "/";
}
int mes = mMonth + 1;
if (mes < 10) {
date += "0" + mes + "/";
} else {
date += mes + "/";
}
date += mYear;
txtV.setText(date);
buildList(mDay, mMonth + 1, mYear);
}
};
OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
Bundle b = new Bundle();
b.putInt("set_day", mDay);
b.putInt("set_month", mMonth);
b.putInt("set_year", mYear);
DatePickerDialogFragment datePicker = new DatePickerDialogFragment(
mHandler);
datePicker.setArguments(b);
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(datePicker, "date_picker");
// Opening the DatePicker fragment
ft.commit();
}
};
txtV.setOnClickListener(listener);
btnNewAct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(getApplicationContext(), NewActivity.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected void buildList(int d, int m, int y) {
acts = System.searchByDate(d, m, y);
listNames.clear();
if (acts != null && acts.size() != 0) {
for (int i = 0; i < acts.size(); i++) {
listNames.add(acts.get(i).getName());
}
listHasItems = true;
} else {
listHasItems = false;
listNames.add("No activities for that date.");
}
ListView listview = (ListView) findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listNames);
listview.setAdapter(adapter);
}
public void mostrarToast(String txt) {
Toast toast = Toast.makeText(getApplicationContext(), txt,
Toast.LENGTH_SHORT);
toast.show();
}
private void removeActivitesBeforeCurrentDate() {
ToDoSQLiteHelper actdb = new ToDoSQLiteHelper(getApplicationContext(),
"db", null, 1);
SQLiteDatabase db = actdb.getWritableDatabase();
ActivityToDo aux;
Cursor c = db.rawQuery("SELECT * FROM Activities", null);
if (System.activities.size() != 0 && c.moveToFirst()) {
for (int i = 0; i < System.activities.size(); i++) {
aux = System.activities.get(i);
if (aux.getYear() < Calendar.getInstance().get(Calendar.YEAR)
&& aux.getMonth() - 1 < Calendar.getInstance().get(
Calendar.MONTH)
&& aux.getDay() < Calendar.getInstance().get(
Calendar.DAY_OF_MONTH)) {
System.activities.remove(i);
int cod = aux.getCod();
db.execSQL("DELETE FROM Activities WHERE cod=" + cod);
}
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (listHasItems) {
MenuInflater inflater = getMenuInflater();
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
position = info.position;
inflater.inflate(R.menu.menulistitem, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
removeActivity(position);
buildList(mDay, mMonth + 1, mYear);
return true;
}
private void removeActivity(int pos) {
ToDoSQLiteHelper actdb = new ToDoSQLiteHelper(getApplicationContext(),
"db", null, 1);
SQLiteDatabase db = actdb.getWritableDatabase();
ActivityToDo aux;
Cursor c = db.rawQuery("SELECT * FROM Activities", null);
if (System.activities.size() != 0 && c.moveToFirst()) {
aux = System.activities.get(pos);
System.activities.remove(pos);
int cod = aux.getCod();
db.execSQL("DELETE FROM Activities WHERE cod=" + cod);
}
c.close();
}
#Override
protected void onPause() {
super.onPause();
this.finish();
}
}
But the db.execSQL("DELETE FROM Activities WHERE cod=" + cod); doesn't seem to work for the last activity that remains in the database. Example: I pick a date, there's two activities for the day, I delete both of them, the ListView shows the text "No activity for that date", which is what should happen, but when I start the app again, the activity that was supposingly deleted at last, appears there. Same if there's only one activity for that date, that's why I say that it doesn't seem to delete an activity if it's the last thing in the database.
Any idea why? Thanks in advance.
My SQLite class:
public class ToDoSQLiteHelper extends SQLiteOpenHelper {
// crear tabla de usuario
// agregar DATE
String sqlCreate = "CREATE TABLE Activities (cod INTEGER, name TEXT, descr TEXT, priority TEXT, day TEXT, month TEXT, year TEXT)";
public ToDoSQLiteHelper(Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sqlCreate);
}
#Override
public void onUpgrade(SQLiteDatabase db, int versionAnterior,
int versionNueva) {
db.execSQL("DROP TABLE IF EXISTS Activities");
db.execSQL(sqlCreate);
}
}