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?
Related
I'm tried to manage a set of push notifications.
1. My first problem is that only last notification set up receive my smartphone. I believe that it hasn't create new instance but it overwrite the unique istance. How can I solve it?
2. My second problem is that i want that from app, the user can delete a schedule of a determinate notification.
This is my code in MovieAdapter.java (main methods are getNotification, scheduleNotification and deleteNotification ):
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder>{
private PendingIntent pendingIntent = null;
private Context context;
private List<Movie> movies;
private View itemView;
private RecyclerView rv;
//per la data
private EditText fromDateEtxt;
private EditText eReminderTime;
private boolean active = false;
private int mese = (Calendar.getInstance().getTime().getMonth())+1;
private int anno = (Calendar.getInstance().getTime().getYear())+1900 ;
private int giorno = Calendar.getInstance().getTime().getDate();
private int ora;
private int minuti;
private int secondi;
private boolean modify = false;
private Date datatime;
private static String tipo = "NOTIFY";
//non sono ancora sicuro se metterlo qui
private WorkManager mWorkManager;
static MoviesFragment fragmentInstance;
static SectionsPageAdapter spa;
public MoviesAdapter(Context context, List<Movie> movies, MoviesFragment fragment) {
this.context = context;
this.movies = movies;
this.fragmentInstance = fragment;
this.spa = null;
}
public MoviesAdapter(Context context, List<Movie> movies, SectionsPageAdapter spa) {
this.context = context;
this.movies = movies;
this.spa = spa;
this.fragmentInstance = null;
}
#Override
public MoviesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
/*if(getTipo().equals("Suggested"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Watched"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie_watched, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Notify"))
{*/
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
//}
//return null;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
mWorkManager = WorkManager.getInstance();
final Movie movie = movies.get(position);
Glide.with(context)
.load(movie.getPosterUrl())
.placeholder(R.drawable.poster_placeholder)
.into(holder.posterView);
holder.title_movie.setText(movie.getTitle());
// prende solo la data + anno
String yourString = String.valueOf(movie.getReleaseDate());
String date = yourString.substring(0, 10);
String year = yourString.substring(yourString.length()-5,yourString.length());
//per fare il testo bold
final SpannableStringBuilder sb = new SpannableStringBuilder("Release: "+date+year);
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan nss = new StyleSpan(Typeface.NORMAL); //Span to make text italic
sb.setSpan(bss, 0, 7, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb.setSpan(nss, 7, sb.length()-1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
holder.release_date.setText(sb);
if(getTipo().equals("NOTIFY")) {
Toast.makeText(context, "Notify", Toast.LENGTH_LONG).show();
holder.movie_notify.setVisibility(View.VISIBLE);
holder.notifyButton.setVisibility(View.GONE);
holder.changeDateTimeButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
holder.removeButton.setVisibility(View.VISIBLE);
String yourString1 = String.valueOf(movie.getNotifyDate());
Log.i("STRINGA",yourString1);
if(!(yourString1.equals("null"))) {
date = yourString1.substring(0, 16);
year = yourString1.substring(yourString1.length() - 5, yourString1.length());
//per fare il testo bold
final SpannableStringBuilder sb1 = new SpannableStringBuilder("Notify: " + date + year);
final StyleSpan bss1 = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
final StyleSpan nss1 = new StyleSpan(Typeface.NORMAL); //Span to make text normal
sb1.setSpan(bss1, 0, 6, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold
sb1.setSpan(nss1, 6, sb.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make last 2 characters Italic
holder.movie_notify.setText(sb1);
}
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDatabase md = new MovieDatabase(context);
md.deleteMovie(movies.get(position).getId());
deleteNotify(pendingIntent);
refreshLists();
}
});
holder.changeDateTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertFormElements(position, true);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(),null);
MovieDatabase.updateMovieType(movies.get(position).getId(), 2,MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
refreshLists();
}
});
}
//solo se è di tipo suggested
if(getTipo().equals("SUGGESTED")) {
//disabilitare bottone remove
holder.movie_notify.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
holder.changeDateTimeButton.setVisibility(View.GONE);
Toast.makeText(context,"Suggested", Toast.LENGTH_LONG).show();
holder.notifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertFormElements(position, false);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(),null);
MovieDatabase.insertMovie(mdm, 2, MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
refreshLists();
}
});
}
if (getTipo().equals("WATCHED")) {
holder.movie_notify.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
holder.changeDateTimeButton.setVisibility(View.GONE);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MovieDatabase md = new MovieDatabase(context);
md.deleteMovie(movies.get(position).getId());
refreshLists();
}
});
Toast.makeText(context,"WATCHED", Toast.LENGTH_LONG).show();
}
}
//nuovo codice riguardo l'alerDialog
public final void alertFormElements(final int position, final boolean modify) {
/*
* Inflate the XML view. activity_main is in
* res/layout/form_elements.xml
*/
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.form_elements,
null, false);
// You have to list down your form elements
/*final CheckBox myCheckBox = (CheckBox) formElementsView
.findViewById(R.id.myCheckBox);*/
final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
.findViewById(R.id.NotifyAlertRadioGroup);
//nuovo codice
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.OneDayRadioButton:
actv(false);
break;
case R.id.ReleaseDayRadioButton:
actv(false);
break;
case R.id.OnRadioButton:
actv(true);
break;
}
}
});
//questo sarà sostituito con un calendario.
/*final EditText nameEditText = (EditText) formElementsView
.findViewById(R.id.nameEditText);*/
//parte data
fromDateEtxt = (EditText) formElementsView.findViewById(R.id.nameEditText);
fromDateEtxt.setEnabled(active);
fromDateEtxt.setClickable(active);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//metodo data
//setDateTimeField();
//fromDatePickerDialog.show();
//Calendario ci servirà dopo per inserire i dati nel DB
fromDateEtxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog( context ,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
fromDateEtxt.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
anno = year;
giorno = dayOfMonth;
mese = monthOfYear + 1;
}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
});
//parte orario
ora = 9;
minuti = 30;
eReminderTime = (EditText) formElementsView.findViewById(R.id.timeEditText);
eReminderTime.setText( ora + ":" + minuti);
eReminderTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
eReminderTime.setText( selectedHour + ":" + selectedMinute);
ora = selectedHour;
minuti = selectedMinute;
}
//}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
// the alert dialog
new AlertDialog.Builder(context).setView(formElementsView)
.setTitle(movies.get(position).getTitle()+" Notify")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
//fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
String toastString = "";
String titleMovie = movies.get(position).getTitle();
String releaseDate = String.valueOf(movies.get(position).getReleaseDate());
String date = releaseDate.substring(0, 10);
String year = releaseDate.substring(releaseDate.length()-5,releaseDate.length());
releaseDate = date+year;
toastString = toastString + titleMovie + "\n" + releaseDate +"\n";
/*
* Detecting whether the checkbox is checked or not.
*/
/*if (myCheckBox.isChecked()) {
toastString += "Happy is checked!\n";
} else {
toastString += "Happy IS NOT checked.\n";
}*/
/*
* Getting the value of selected RadioButton.
*/
// get selected radio button from radioGroup
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton selectedRadioButton = (RadioButton) formElementsView
.findViewById(selectedId);
Date datatime = null;
if(selectedRadioButton.getId() == R.id.ReleaseDayRadioButton) {
toastString += "Selected radio button is: " + selectedRadioButton.getText() +"!\n";
Date release = movies.get(position).getReleaseDate();
release.setHours(ora);
release.setMinutes(minuti);
release.setSeconds(secondi);
datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
}
else if(selectedRadioButton.getId() == R.id.OneDayRadioButton) {
toastString += "Selected radio button is: "
+ selectedRadioButton.getText() + "!\n";
Date release = movies.get(position).getReleaseDate();
release.setHours(ora);
release.setMinutes(minuti);
release.setSeconds(secondi);
datatime = new Date (anno-1900,mese-1,giorno-1,release.getHours(),release.getMinutes(), release.getSeconds());
}
else if(selectedRadioButton.getId() == R.id.OnRadioButton) {
toastString += "Selected radio button is: " + fromDateEtxt.getText() +"!\n";
datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
}
setDataTime(datatime);
toastString += eReminderTime.getText();
//Date(int year, int month, int date, int hrs, int min, int sec)
//Date datatime = new Date (anno-1900,mese-1,giorno,ora, minuti, secondi);
//ora scriviamo tutta questa roba sulla base di dati
/*String testo = movies.get(position).getTitle()+ "\n" + "I WATCH IT";
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
if(modify == false) {
// public MovieDBModel(int id, String title, String overview, String posterUrl, String backdropUrl, String trailerUrl,
// Date releaseDate, float rating, boolean adult, date datatime){
//Log.i("DATATIME", datatime.toString());
MovieDBModel mdm2 = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult(), datatime);
MovieDatabase.insertMovie(mdm2, 1, MainActivity.getMovieDatabase());
//notifyRequestID= scheduleNotify(datatime,position);
pendingIntent=scheduleNotification(getNotification(movies.get(position).getTitle()),datatime,movies.get(position).getId());
refreshLists();
}
else {
// provare la base di dati
MovieDatabase md = new MovieDatabase(context);
Log.i("DATATIME","ID"+ movies.get(position).getId() +"DATATIME: "+ datatime);
md.updateNotifyDate(movies.get(position).getId(),datatime);
//deleteNotify(notifyRequestID);
//inserire funzione deleteNotify
deleteNotify(pendingIntent);
pendingIntent=scheduleNotification(getNotification(movies.get(position).getTitle()),datatime, movies.get(position).getId());
refreshLists();
}
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
/*
* Getting the value of an EditText.
*/
/*toastString += "Name is: " + nameEditText.getText()
+ "!\n";*/
Toast toast = Toast.makeText(context, toastString, Toast.LENGTH_LONG);
toast.show();
dialog.cancel();
}
}).show();
}
//nuovo codice
/*#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_movie, null);
holder = new ViewHolder();
holder.title_movie = (TextView) convertView.findViewById(R.id.movie_title);
holder.release_date = (TextView) convertView
.findViewById(R.id.movie_release_date);
Movie row_pos = movies.get(position);
//holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.title_movie.setText(row_pos.getTitle());
holder.release_date.setText((CharSequence) row_pos.getReleaseDate());
//holder.contactType.setText(row_pos.getContactType());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}*/
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
Glide.clear(holder.posterView);
}
#Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.poster)
public ImageView posterView;
#BindView(R.id.movie_title)
public TextView title_movie;
#BindView(R.id.movie_release_date)
public TextView release_date;
#BindView(R.id.movie_time_notify)
public TextView movie_notify;
#BindView(R.id.editNotify)
public Button notifyButton;
#BindView(R.id.iWatchItMovie)
public Button watchedButton;
#BindView(R.id.remove)
public Button removeButton;
#BindView(R.id.change)
public Button changeDateTimeButton;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
//parte per attivare/disattivare l'editText
private void actv(final boolean active)
{
fromDateEtxt.setEnabled(active);
if (active)
{
fromDateEtxt.requestFocus();
fromDateEtxt.setText(giorno+"-"+mese+"-"+anno);
}
}
public static void setTipo(String tipo) {
MoviesAdapter.tipo = tipo;
}
public static void setFragment(MoviesFragment fragment) {
MoviesAdapter.fragmentInstance = fragment;
}
public static String getTipo() {
return tipo;
}
public Date getDatatime() {
return datatime;
}
public void setDataTime(Date datatime) {
this.datatime = datatime;
}
private Data createInputDataForUri(Movie movie) {
Data.Builder builder = new Data.Builder();
if (movie != null) {
builder.putString(KEY_MOVIE,movie.getTitle());
}
return builder.build();
}
private PendingIntent scheduleNotification(Notification notification, /*int delay*/Date d, int id) {
Intent notificationIntent = new Intent(context, NotificationPublisher.class);
//
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, id);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP,d.getTime(), pendingIntent);
return pendingIntent;
}
public void deleteNotify(PendingIntent p)
{
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(p);//cancel the alarm manager of the pending intent
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("WARNING!!! REMEMBER MOVIE: ");
builder.setContentText(content);
builder.setDefaults(DEFAULT_ALL);
builder.setSmallIcon(R.drawable.ic_launcher_foreground);
return builder.build();
}
public void refreshLists(){
if(fragmentInstance!= null){
fragmentInstance.onRefresh();
}else{
MoviesFragment mf1 = (MoviesFragment)spa.getItem(0);
mf1.setArgFragType(MoviesFragment.Type.NOTIFY);
mf1.onRefresh();
MoviesFragment mf2 = (MoviesFragment)spa.getItem(1);
mf2.setArgFragType(MoviesFragment.Type.SUGGESTED);
mf2.onRefresh();
MoviesFragment mf3 = (MoviesFragment)spa.getItem(2);
mf3.setArgFragType(MoviesFragment.Type.WATCHED);
mf3.onRefresh();
}
}
}
NotificationPublisher.java
package com.example.msnma.movienotifier.notify;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationPublisher extends BroadcastReceiver
{
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Change this line
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
To
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT); //Here 0 is the intent requestcode.
Make sure intent request code is unique in order to differentiate intents.
In my project I download all the data of my project from a json.I download title and description as text and also download my icon and the file of games.
I can download them and also save in database and show in listview easily.
My QUESTION is about how to save that my file for game is beinng download or not?
I have two buttons. first is download button when user click it , it starts to download file.when download finish, my download button disappear and my play button appears.
I want to save this, when user for second time run the application,i save for example my second position downloaded before. and I have just my play button.
my database:
public class DatabaseHandler extends SQLiteOpenHelper {
public SQLiteDatabase sqLiteDatabase;
int tedad;
public DatabaseHandler(Context context) {
super(context, "EmployeeDatabase.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tableEmp = "create table emp(PersianTitle text,Description text,icon text,downloadlink text,dl integer)";
db.execSQL(tableEmp);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertData(ArrayList<String> id, ArrayList<String> name, ArrayList<String> salary, ArrayList<String> roms,String
dl) {
int size = id.size();
tedad = size;
sqLiteDatabase = this.getWritableDatabase();
try {
for (int i = 0; i < size; i++) {
ContentValues values = new ContentValues();
values.put("PersianTitle", id.get(i));
values.put("Description", name.get(i));
values.put("icon", salary.get(i));
values.put("downloadlink", roms.get(i));
values.put("dl", "0");
sqLiteDatabase.insert("emp", null, values);
}
} catch (Exception e) {
Log.e("Problem", e + " ");
}
}
public ArrayList<String> Game_Info (int row, int field) {
String fetchdata = "select * from emp";
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
ArrayList<String> stringArrayList = new ArrayList<String>();
Cursor cu = sqLiteDatabase.rawQuery(fetchdata, null);
for (int i = 0; i < row + 1; i++) {
cu.moveToPosition(i);
String s = cu.getString(field);
stringArrayList.add(s);
}
return stringArrayList;
}
}
and this is my main code:
public class MainActivity2 extends Activity {
Boolean done_game = false;
ProgressDialog progressDialog;
private boolean _init = false;
ListView listView;
DatabaseHandler database;
BaseAdapter adapter;
public String path_image;
JSONObject jsonObject;
Game_Counter_Store Game_Counter_Store;
int game_counter_store;
ArrayList<String> name_array = new ArrayList<String>();
ArrayList<String> des_array = new ArrayList<String>();
ArrayList<String> icon_array = new ArrayList<String>();
ArrayList<String> roms_array = new ArrayList<String>();
ArrayList<String> fav_array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main2);
init();
System.gc();
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");//make a direction
path_image = mediaStorageDir.getAbsolutePath(); // here is tha path
listView = (ListView) findViewById(R.id.listView);
database = new DatabaseHandler(MainActivity2.this);
database.getWritableDatabase();
Game_Counter_Store = new Game_Counter_Store("Games_Number", this); // number of game in first run is 0
game_counter_store = Game_Counter_Store.get_count();
if (game_counter_store == 0) {
Log.i("mhs", "game_counter_store is 0");
DownloadGames();
} else {
Log.i("mhs", "there are some games");
for (int i = 0; i < game_counter_store; i++) {
name_array = database.Game_Info(i, 0);
des_array = database.Game_Info(i, 1);
icon_array = database.Game_Info(i, 2);
roms_array = database.Game_Info(i, 3);
fav_array = database.Game_Info(i, 4);
}
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
}
public void DownloadGames() {
//here we download name, des, icon
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
Game_Counter_Store counter_store = new Game_Counter_Store("Games_Number", MainActivity2.this); // get numbrr of games
counter_store.set_count(res.size()); // store the games number
for (int i = 0; i < res.size(); i++) {
jsonObject = new JSONObject(res.get(i)); //get all the jsons
//get all the data to store in database
name_array.add(jsonObject.getString("PersianTitle"));
des_array.add(jsonObject.getString("Description"));
icon_array.add(jsonObject.getString("icon"));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("icon")), jsonObject.getString("icon").toString(), null); // download the image
GetFileCallBack Image_callback = new GetFileCallBack() {
#Override
public void onStart() {
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(long l, long l1) {
// Toast.makeText(getApplicationContext(),"onProgress",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess() {
// Toast.makeText(getApplicationContext(),"YES",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure() {
// Toast.makeText(getApplicationContext(),"NO",Toast.LENGTH_LONG).show();
}
};
if (!fd.DoesFileExist()) {
fd.Start(Image_callback); // get the data
}
//set data in adapter to show in listview
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
//store dada in database (name , des , icon , bin file(roms) , state)
database.insertData(name_array, des_array, icon_array, roms_array,"0");
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(this, makeDocCallBack);
}
public static String getFileName(String url) {
String temp = url.substring(url.lastIndexOf('/') + 1, url.length());
if (temp.contains("?"))
temp = temp.substring(0, temp.indexOf("?"));
return temp;
}
public class MyBaseAdapter extends BaseAdapter {
private Activity activity;
private ArrayList title, desc, icon, roms,fav;
private LayoutInflater inflater = null;
public MyBaseAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f) {
activity = a;
this.title = b;
this.desc = c;
this.icon = d;
this.roms = e;
this.fav=f;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_item, null);
TextView title2 = (TextView) vi.findViewById(R.id.game_name); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.game_des); // desc
String song2 = desc.get(position).toString();
title22.setText(song2);
File imageFile = new File("/storage/emulated/0/MyDirName/" + getFileName(icon_array.get(position)));
ImageView imageView = (ImageView) vi.findViewById(R.id.icon); // icon
imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
TextView title222 = (TextView) vi.findViewById(R.id.game_roms); // desc
String song22 = roms.get(position).toString();
title222.setText(song22);
final Button dl_btn = (Button) vi.findViewById(R.id.dl_btn); // desc
final Button run_btn = (Button) vi.findViewById(R.id.play_btn); // desc
run_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Preferences.DEFAULT_GAME_FILENAME = getFileName(roms_array.get(position));
Intent myIntent = new Intent(MainActivity2.this, FileChooser.class);
myIntent.putExtra(FileChooser.EXTRA_START_DIR, Preferences.getRomDir(MainActivity2.this));
Log.i("mhsnnn", Preferences.getTempDir(MainActivity2.this));
final int result = Preferences.MENU_ROM_SELECT;
startActivityForResult(myIntent, result);
}
});
dl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
jsonObject = new JSONObject(res.get(position));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd1 = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("downloadlink")), jsonObject.getString("downloadlink").toString(),null); //download the bin file
GetFileCallBack roms_callback = new GetFileCallBack() {
#Override
public void onStart() {
}
#Override
public void onProgress(long l, long l1) {
Log.i("nsr", "onProgress");
}
#Override
public void onSuccess() {
Log.i("nsr", "onSuccess");
dl_btn.setVisibility(View.GONE);
run_btn.setVisibility(View.VISIBLE);
}
#Override
public void onFailure() {
Log.i("nsr", "onFailure");
}
};
if (!fd1.DoesFileExist()) {
fd1.Start(roms_callback);
}
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(MainActivity2.this, makeDocCallBack);
}
});
return vi;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean verifyExternalStorage() {
// check for sd card first
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// rw access
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// r access
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// no access
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
// if we do not have storage warn user with dialog
if (!mExternalStorageAvailable || !mExternalStorageWriteable) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name) + " Error")
.setMessage("External Storage not mounted, are you in disk mode?")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
init();
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.show();
return false;
}
return true;
}
private void init() {
if (verifyExternalStorage() && !_init) {
// always try and make application dirs
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Log.i("nsrrr1", extStorageDirectory);
// /storage/emulated/0
File myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR);
Log.i("nsrrr2", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR_ROMS);
Log.i("nsrrr3", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(Preferences.DEFAULT_DIR_GAME);
Log.i("nsrrr3", files + "");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(Preferences.DEFAULT_DIR_GAME + "/" + filename);
File outFile = new File(myNewFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
// do first run welcome screen
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean firstRun = preferences.getBoolean(Preferences.PREF_FIRST_RUN, true);
if (firstRun) {
// remove first run flag
Editor edit = preferences.edit();
edit.putBoolean(Preferences.PREF_FIRST_RUN, false);
// default input
edit.putBoolean(Preferences.PREF_USE_DEFAULT_INPUT, true);
edit.commit();
}
// generate APK path for the native side
ApplicationInfo appInfo = null;
PackageManager packMgmr = this.getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(getString(R.string.package_name), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String _apkPath = appInfo.sourceDir;
// init the emulator
Emulator.init(_apkPath);
Log.i("rrrr", _apkPath);
// set the paths
Emulator.setPaths(extStorageDirectory + Preferences.DEFAULT_DIR,
extStorageDirectory + Preferences.DEFAULT_DIR_ROMS,
"",
"",
"");
// load up prefs now, never again unless they change
//PreferenceFacade.loadPrefs(this, getApplicationContext());
// load gui
// Log.d(LOG_TAG, "Done init()");
setContentView(R.layout.activity_main2);
// set title
super.setTitle(getString(R.string.app_name));
_init = true;
// Log.d(LOG_TAG, "Done onCreate()");
}
}
private void copyFile(InputStream in, OutputStream out) {
byte[] buffer = new byte[1024];
int read;
try {
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
how to make method in my database to do this?
If I understood you properly, you can add a table, user_games for example with User ID, Game ID and Status, then you can update status whenever an action is completed.
For example Status 1 for downloading, status 2 for Downloaded or Finished and you can even add statuses like download failed, to add a re-download button...
you can do something like
public void update_status(UserID,GameID) {
String update = "UPDATE games set status = 1 where id="+Game_ID+" and UserID = " + UserID);
db.rawQuery(update, null);
}
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.
I am creating an android application in which having one listview, inside that listview having expandable listview. When I run the application I'm getting the uncaught remote exception in logcat. Can any one tell me why this error occurs, what I have done wrong in following code?
ListAdapter:
public class Daybook_adapter extends BaseAdapter {
Context context;
private ArrayList<Daybook> entriesdaybook;
private ArrayList<Daybooklist> daybooklists = new ArrayList<Daybooklist>();
private boolean isListScrolling;
private LayoutInflater inflater;
public Daybook_adapter(Context context, ArrayList<Daybook> entriesdaybook) {
this.context = context;
this.entriesdaybook = entriesdaybook;
}
#Override
public int getCount() {
return entriesdaybook.size();
}
#Override
public Object getItem(int i) {
return entriesdaybook.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.model_daybook, null);
final TextView tv_date = (TextView) convertView.findViewById(R.id.tv_daybook_date);
final TextView tv_cashin = (TextView) convertView.findViewById(R.id.tv_daybook_cashin);
final TextView tv_cashout = (TextView) convertView.findViewById(R.id.tv_daybook_cashout);
final TextView tv_totalamt = (TextView) convertView.findViewById(R.id.daybook_total_amt);
final ImageView img_pdf = (ImageView) convertView.findViewById(R.id.img_printpdf);
LinearLayout emptyy = (LinearLayout) convertView.findViewById(R.id.empty);
ExpandableHeightListView daybookdetailviewlist = (ExpandableHeightListView) convertView.findViewById(R.id.detaillist_daybook);
final Daybook m = entriesdaybook.get(position);
String s = m.getDate();
String[] spiliter = s.split("-");
String year = spiliter[0];
String month = spiliter[1];
String date = spiliter[2];
if (month.startsWith("01")) {
tv_date.setText(date + "Jan" + year);
} else if (month.startsWith("02")) {
tv_date.setText(date + "Feb" + year);
} else if (month.startsWith("03")) {
tv_date.setText(date + "Mar" + year);
} else if (month.startsWith("04")) {
tv_date.setText(date + "Apr" + year);
} else if (month.startsWith("05")) {
tv_date.setText(date + "May" + year);
} else if (month.startsWith("06")) {
tv_date.setText(date + "Jun" + year);
} else if (month.startsWith("07")) {
tv_date.setText(date + "Jul" + year);
} else if (month.startsWith("08")) {
tv_date.setText(date + "Aug" + year);
} else if (month.startsWith("09")) {
tv_date.setText(date + "Sep" + year);
} else if (month.startsWith("10")) {
tv_date.setText(date + "Oct" + year);
} else if (month.startsWith("11")) {
tv_date.setText(date + "Nov" + year);
} else if (month.startsWith("12")) {
tv_date.setText(date + "Dec" + year);
}
tv_cashin.setText("\u20B9" + m.getCashin());
tv_cashout.setText("\u20B9" + m.getCashout());
double one = Double.parseDouble(m.getCashin());
double two = Double.parseDouble(m.getCashout());
double three = one + two;
tv_totalamt.setText("\u20B9" + String.valueOf(three));
DatabaseHandler databaseHandler = new DatabaseHandler(context);
daybooklists = databaseHandler.getAllDaywisedaybookdetails(s);
for (int i = 0; i < daybooklists.size(); i++) {
try {
Daybooklist_adapter adapter = new Daybooklist_adapter(context, daybooklists);
if (adapter != null) {
if (adapter.getCount() > 0) {
emptyy.setVisibility(View.GONE);
daybookdetailviewlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
} else {
daybookdetailviewlist.setEmptyView(emptyy);
}
daybookdetailviewlist.setExpanded(true);
daybookdetailviewlist.setFastScrollEnabled(true);
if (!isListScrolling) {
img_pdf.setEnabled(false);
adapter.isScrolling(true);
} else {
img_pdf.setEnabled(true);
adapter.isScrolling(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
img_pdf.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage("Click yes to Print Report for : " + m.getDate())
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
Intent pdfreport = new Intent(context, Activity_Daybookpdf.class);
pdfreport.putExtra("date", m.getDate());
context.startActivity(pdfreport);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Button nbutton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
nbutton.setTextColor(context.getResources().getColor(R.color.colorAccent));
Button pbutton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
pbutton.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));
pbutton.setPadding(0, 10, 10, 0);
pbutton.setTextColor(Color.WHITE);
return false;
}
});
return convertView;
}
public void setTransactionList(ArrayList<Daybook> newList) {
entriesdaybook = newList;
notifyDataSetChanged();
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("scrollcheck", String.valueOf(isListScrolling));
}
}
Expandable ListAdapter:
public class Daybooklist_adapter extends BaseAdapter {
Context context;
private LayoutInflater inflater;
private ArrayList<Daybooklist> daybooklists;
DatabaseHandler databaseHandler;
boolean isListScrolling;
public Daybooklist_adapter(Context context, ArrayList<Daybooklist> daybooklists) {
this.context = context;
this.daybooklists = daybooklists;
}
#Override
public int getCount() {
return daybooklists.size();
}
#Override
public Object getItem(int i) {
return daybooklists.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewGroup) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertview == null)
convertview = inflater.inflate(R.layout.model_daybook_listentry, null);
final TextView day_name = (TextView) convertview.findViewById(R.id.tv_daybook_name);
final TextView day_description = (TextView) convertview.findViewById(R.id.tv_daybook_description);
final TextView day_type = (TextView) convertview.findViewById(R.id.tv_daybook_type);
final TextView day_amount = (TextView) convertview.findViewById(R.id.tv_daybook_amount);
final TextView day_usertype = (TextView) convertview.findViewById(R.id.tv_usertype);
final TextView day_time = (TextView) convertview.findViewById(R.id.tv_daybook_time);
final ImageView day_check = (ImageView) convertview.findViewById(R.id.img_doneall);
final TextView daybook_location = (TextView) convertview.findViewById(R.id.tv_daybook_location);
databaseHandler = new DatabaseHandler(context);
final Daybooklist m = daybooklists.get(position);
if (m.getUsertype() != null && !m.getUsertype().isEmpty()) {
if (m.getUsertype().startsWith("farmer") | m.getUsertype().startsWith("singleworker") | m.getUsertype().startsWith("groupworker") | m.getUsertype().startsWith("payvehicle")) {
if (m.getUsertype().startsWith("farmer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
String locat = String.valueOf(databaseHandler.getfarmerlocation(m.getMobileno()));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
day_type.setText(m.getType());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + m.getExtraamt());
if (m.getAmountout().startsWith("0.0") | m.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(m.getCtime());
} else {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
daybook_location.setText(m.getType());
day_type.setText(m.getType());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
day_amount.setText("\u20B9" + m.getExtraamt());
if (m.getAmountout().startsWith("0.0") | m.getAmountout().startsWith("0")) {
// day_amount.setTextColor(activity.getResources().getColor(R.color.green));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.INVISIBLE);
} else {
// day_amount.setTextColor(activity.getResources().getColor(R.color.album_title));
Log.e("Amountout", m.getAmountout());
day_check.setVisibility(View.VISIBLE);
}
day_time.setText(m.getCtime());
}
} else if (m.getUsertype().startsWith("advancefarmer") | m.getUsertype().startsWith("workeradvance") | m.getUsertype().startsWith("kgroupadvance") | m.getUsertype().startsWith("otherexpense") | m.getUsertype().startsWith("vehicle")) {
if (m.getUsertype().startsWith("advancefarmer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
day_type.setText(m.getType());
String locat = String.valueOf(databaseHandler.getfarmerlocation(m.getMobileno()));
locat = locat.replaceAll("\\[", "").replaceAll("\\]", "");
Log.e("farmerlocation", locat);
daybook_location.setText(locat);
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", m.getAmountout());
day_amount.setText("\u20B9" + m.getAmountout());
day_time.setText(m.getCtime());
} else {
day_name.setText(m.getName());
day_description.setText(m.getType());
day_type.setText(m.getType());
daybook_location.setText(m.getDescription());
if (m.getName() != null && m.getName().startsWith("no")) {
day_name.setText(" ");
} else if (m.getDescription() != null && m.getDescription().startsWith("no")) {
day_description.setText(" ");
}
Log.e("amountout", m.getAmountout());
day_amount.setText("\u20B9" + m.getAmountout());
day_time.setText(m.getCtime());
}
} else if (m.getUsertype().startsWith("buyer")) {
day_name.setText(m.getName());
day_description.setText(m.getDescription());
day_amount.setText("\u20B9" + m.getAmountin());
day_type.setText(" ");
day_time.setText(m.getCtime());
daybook_location.setText(m.getType());
}
if (m.getUsertype().startsWith("farmer")) {
day_usertype.setText("F");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (m.getUsertype().startsWith("advancefarmer")) {
day_usertype.setText("FA");
day_usertype.setBackgroundResource(R.drawable.textview_farmer);
} else if (m.getUsertype().startsWith("singleworker")) {
day_usertype.setText("W");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("workeradvance")) {
day_usertype.setText("WA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("groupworker")) {
day_usertype.setText("G");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("kgroupadvance")) {
day_usertype.setText("GA");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("otherexpense")) {
day_usertype.setText("E");
day_usertype.setBackgroundResource(R.drawable.textview_otherexpense);
} else if (m.getUsertype().startsWith("vehicle")) {
day_usertype.setText("V");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (m.getUsertype().startsWith("gsalary")) {
day_usertype.setText("GS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("isalary")) {
day_usertype.setText("WS");
day_usertype.setBackgroundResource(R.drawable.textview_worker);
} else if (m.getUsertype().startsWith("payvehicle")) {
day_usertype.setText("VP");
day_usertype.setBackgroundResource(R.drawable.textview_vehicle);
} else if (m.getUsertype().startsWith("buyer")) {
day_usertype.setText("B");
day_usertype.setBackgroundResource(R.drawable.textview_buyer);
}
}
return convertview;
}
public void isScrolling(boolean isScroll) {
isListScrolling = isScroll;
Log.e("Innerscrollcheck", String.valueOf(isListScrolling));
}
}
Exception:
Uncaught remote exception! (Exceptions are not yet supported across
processes.)
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.android.internal.os.BatteryStatsImpl.updateAllPhoneStateLocked(BatteryStatsImpl.java:3321)
at com.android.internal.os.BatteryStatsImpl.notePhoneSignalStrengthLocked(BatteryStatsImpl.java:3351)
at com.android.server.am.BatteryStatsService.notePhoneSignalStrength(BatteryStatsService.java:395)
at com.android.server.TelephonyRegistry.broadcastSignalStrengthChanged(TelephonyRegistry.java:1448)
at com.android.server.TelephonyRegistry.notifySignalStrengthForSubscriber(TelephonyRegistry.java:869)
at com.android.internal.telephony.ITelephonyRegistry$Stub.onTransact(ITelephonyRegistry.java:184)
at android.os.Binder.execTransact(Binder.java:451)
Thanks in advance.
I'm trying to make a reminder app and I used the phones internal storage to store the data being inputted. How do I read the file from the internal storage and place the strings in title in the listview of ReminderListActivity.java?
ReminderListActivity.java
public class ReminderListActivity extends ListActivity {
private static final int ACTIVITY_CREATE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_reminder_list);
String[] items = new String[]{"Title"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.reminder_row, R.id.text1, items);
setListAdapter(adapter);
registerForContextMenu(getListView());
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, ReminderEditActivity.class);
i.putExtra("RowId", id);
startActivity(i);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.list_menu, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_insert:
createReminder();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createReminder() {
Intent i = new Intent(this, ReminderEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
return true;
}
return super.onContextItemSelected(item);
}
public void onClickSave(View view) {
Intent f = new Intent(this, ReminderEditActivity.class);
startActivity(f);
}
}
Heres the Activity I used to save the strings into the json file in the internal storage
ReminderEditActivity.java
public class ReminderEditActivity extends Activity {
private Button mDateButton;
private Button mTimeButton;
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
private Calendar mCalendar;
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String TIME_FORMAT = "kk:m";
private static final String FILENAME = "hello.json";
private EditText TitleEditText;
private EditText BodyEditText;
private Button EditTime;
private Button EditDate;
private ArrayList<Data> data =
new ArrayList<Data>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_reminder_edit);
mCalendar = Calendar.getInstance();
mDateButton = (Button) findViewById(R.id.reminder_date);
mTimeButton = (Button) findViewById(R.id.reminder_time);
TitleEditText = (EditText) findViewById(R.id.title);
BodyEditText = (EditText) findViewById(R.id.body);
EditTime = (Button) findViewById(R.id.reminder_time);
EditDate = (Button) findViewById(R.id.reminder_date);
if (getIntent() != null) {
Bundle extras = getIntent().getExtras();
int rowId = extras != null ? extras.getInt("RowId") : -1;
registerButtonListenersAndSetDefaultText();
}
readData();
}
public void readData() {
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
JsonReader jsonReader = new JsonReader(isr);
String title = "";
String body = "";
String time = "";
String date = "";
jsonReader.beginArray(); // [
while (jsonReader.hasNext()) {
jsonReader.beginObject(); // {
while (jsonReader.hasNext()) {
String key = jsonReader.nextName();
if (key.equals("Title")) {
title = jsonReader.nextString();
} else if (key.equals("Body")) {
body = jsonReader.nextString();
} else if (key.equals("Date")) {
date = jsonReader.nextString();
} else if (key.equals("Time")) {
time = jsonReader.nextString();
}
}
jsonReader.endObject(); // }
Data content = new Data(
title, body, date, time
);
data.add(content);
}
jsonReader.endArray();
jsonReader.close();
} catch (IOException ex) {
Toast.makeText(this, "cannot read file", Toast.LENGTH_SHORT).show();
}
}
public void addFile(View view) {
String title = TitleEditText.getText().toString();
String body = BodyEditText.getText().toString();
String time = EditTime.getText().toString();
String date = EditDate.getText().toString();
Toast.makeText(this, "File written", Toast.LENGTH_SHORT).show();
Data content = new Data(
title, body, date, time
);
data.add(content);
writeAllData();
}
public void writeAllData() {
try {
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
JsonWriter jsonWriter = new JsonWriter(osw);
jsonWriter.setIndent(" ");
jsonWriter.beginArray();
for (int i = 0; i < data.size(); i++) {
Data con = data.get(i);
jsonWriter.beginObject();
jsonWriter.name("Title").value(con.GetTitle());
jsonWriter.name("Body").value(con.GetBody());
jsonWriter.name("Date").value(con.GetDate());
jsonWriter.name("Time").value(con.GetTime());
jsonWriter.endObject();
}
jsonWriter.endArray();
jsonWriter.close();
} catch (IOException ex) {
Toast.makeText(this, "Cant write file", Toast.LENGTH_LONG).show();
}
}
private void registerButtonListenersAndSetDefaultText() {
mTimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(TIME_PICKER_DIALOG);
}
});
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_DIALOG);
}
});
updateDateButtonText();
updateTimeButtonText();
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_DIALOG:
return showDatePicker();
case TIME_PICKER_DIALOG:
return showTimePicker();
}
return super.onCreateDialog(id);
}
private DatePickerDialog showDatePicker() {
DatePickerDialog datePicker = new DatePickerDialog(ReminderEditActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateButtonText();
}
}, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
return datePicker;
}
private TimePickerDialog showTimePicker() {
TimePickerDialog timePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mCalendar.set(Calendar.MINUTE, minute);
updateTimeButtonText();
}
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
return timePicker;
}
private void updateDateButtonText() {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
String dateForButton = dateFormat.format(mCalendar.getTime());
mDateButton.setText(dateForButton);
}
private void updateTimeButtonText() {
SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
String timeForButton = timeFormat.format(mCalendar.getTime());
mTimeButton.setText(timeForButton);
}
}