5

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?

OBX
  • 6,044
  • 7
  • 33
  • 77
  • Possible duplicate of [How to fix android.os.DeadObjectException android X](https://stackoverflow.com/questions/1573557/how-to-fix-android-os-deadobjectexception-android-x) – Reaz Murshed Oct 04 '17 at 03:17
  • @ReazMurshed the stack trace is different, hence the reason for the crash might be different too. – Roman Samoilenko May 14 '20 at 11:20

0 Answers0