0

I found this file picker online, which the developer said that people could use if they wanted to. Since I thought the code was easy to understand - I decided to use it and change it a bit for my application. All credit goes to the original developer (https://github.com/mburman/Android-File-Explore)

        loadFileList();

    showDialog(DIALOG_LOAD_FILE);
    Log.d(TAG, path.getAbsolutePath());

}

private void loadFileList() {
    try {
        path.mkdirs();
    } catch (SecurityException e) {
        Log.e(TAG, "unable to write on the sd card ");
    }

    // Checks whether path exists
    if (path.exists()) {
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                // Filters based on whether the file is hidden or not
                return (sel.isFile() || sel.isDirectory())
                        && !sel.isHidden();

            }
        };

        String[] fList = path.list(filter);
        fileList = new Item[fList.length];
        for (int i = 0; i < fList.length; i++) {
            fileList[i] = new Item(fList[i], R.drawable.file_icon);

            // Convert into file path
            File sel = new File(path, fList[i]);

            // Set drawables
            if (sel.isDirectory()) {
                fileList[i].icon = R.drawable.directory_icon;
                Log.d("DIRECTORY", fileList[i].file);
            } else {
                Log.d("FILE", fileList[i].file);
            }
        }

        if (!firstLvl) {
            Item temp[] = new Item[fileList.length + 1];
            for (int i = 0; i < fileList.length; i++) {
                temp[i + 1] = fileList[i];
            }
            temp[0] = new Item("Up", R.drawable.directory_up);
            fileList = temp;
        }
    } else {
        Log.e(TAG, "path does not exist");
    }

    adapter = new ArrayAdapter<Item>(this,
            android.R.layout.select_dialog_item, android.R.id.text1,
            fileList) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // creates view
            View view = super.getView(position, convertView, parent);
            TextView textView = (TextView) view
                    .findViewById(android.R.id.text1);

            // put the image on the text view
            textView.setCompoundDrawablesWithIntrinsicBounds(
                    fileList[position].icon, 0, 0, 0);

            // add margin between image and text (support various screen
            // densities)
            int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
            textView.setCompoundDrawablePadding(dp5);

            return view;
        }
    };

}

private class Item {
    public String file;
    public int icon;

    public Item(String file, Integer icon) {
        this.file = file;
        this.icon = icon;
    }

    @Override
    public String toString() {
        return file;
    }
}

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    AlertDialog.Builder builder = new Builder(this);

    if (fileList == null) {
        Log.e(TAG, "No files loaded");
        dialog = builder.create();
        return dialog;
    }

    switch (id) {
    case DIALOG_LOAD_FILE:
        builder.setTitle("Choose your file");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                chosenFile = fileList[which].file;
                File sel = new File(path + "/" + chosenFile);
                if (sel.isDirectory()) {
                    firstLvl = false;

                    // Adds chosen directory to list
                    str.add(chosenFile);
                    fileList = null;
                    path = new File(sel + "");

                    loadFileList();

                    removeDialog(DIALOG_LOAD_FILE);
                    showDialog(DIALOG_LOAD_FILE);
                    Log.d(TAG, path.getAbsolutePath());



                }

                // Checks if 'up' was clicked
                else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {

                    // present directory removed from list
                    String s = str.remove(str.size() - 1);

                    // path modified to exclude present directory
                    path = new File(path.toString().substring(0,
                            path.toString().lastIndexOf(s)));
                    fileList = null;

                    // if there are no more directories in the list, then
                    // its the first level
                    if (str.isEmpty()) {
                        firstLvl = true;
                    }
                    loadFileList();

                    removeDialog(DIALOG_LOAD_FILE);
                    showDialog(DIALOG_LOAD_FILE);
                    Log.d(TAG, path.getAbsolutePath());

                }

                // File picked
                else {
                    chosenFile = fileList[which].file;
                    File test = new File(path + "/" + chosenFile);

                    sendback(test);

                }
            }
        });
        break;
    }
    dialog = builder.show();
    return dialog;
}

Sorry, if it's a bit too long. But that's the entire file picker which is in the onCreate(). I open it by using this code:

Bundle b = new Bundle();
            b.putInt("tallet", 1);
            Intent i = new Intent(getApplicationContext(), FileExplore.class);
            i.putExtras(b);
            startActivityForResult(i, 0);

The code works perfectly. But when I press "back" (onBackPressed), it gives me blank (black) screen if I say finish(); . Right now I'm using this code:

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

    Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
     startActivity(backIntent); 
} 

Which actually works, but it gives me black screen if I press back once, and then the menu, when I hit the back button again. EDIT: it goes INTO the onBackPressed code on second back-press, not the first.

Here's my onActivityResult code in PhotosActivity (it's a tablayout - photosactivity is just one of the screens):

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        //  Bundle b = getIntent().getExtras();

        if (resultCode == -1) 
        {
         Bundle b =  data.getBundleExtra("FiletoPhoto");

                int knappen = b.getInt("number");
            String titlen = b.getString("title");
                        {
                            Listofsounds los = new Listofsounds();
                        String shortname    = los.puttextonit(titlen, knappen);

                    putnameinit(shortname,knappen);
                        }
        }
        else if (resultCode == 0)
        {
            //If I press "back" i've made the resultCode to be 0 in the onBackPressed. What should I do here then?
        }

    }  

What should I do so I could just press it once and get back to the menu?

Rad
  • 830
  • 1
  • 12
  • 24

1 Answers1

0

The issue is that when you use this code:

 Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
 startActivity(backIntent);

You are basically creating and starting a new activity of AndroidTabLayoutActivity which already exists, so now there will be two copies of this activity running simultaneously. However, the original activity will be expecting a result as you've called startActivityForResult(). I think the solution to your problem is probably to do a check if the resultCode you are getting back as a onActivityResult is RESULT_OK or whatever successful resultCode you are setting in setResult(...) in FileExplore.

This is really strange because in all of my apps I don't override onBackPressed and yet, I am able to finish the activity without causing any weird side effects.

A Random Android Dev
  • 2,691
  • 1
  • 18
  • 17
  • Sorry for the late reply. I do not quite understand this. So I should make an onActivityResult in FileExplore - in that method check if resultCode is equal 0 (or what?). and then what? – Rad Aug 24 '12 at 11:35
  • i changed it to dialog.cancel(); now in the onBackPressed(). But it still goes black screen first and then goes back to the mainscreen. – Rad Aug 24 '12 at 14:24
  • Did you understand the fact that if you use startActivity(backIntent) you will be creating two instances of the same activity(the activity being AndroidTabLayoutActivity)? One which already existed and another that will be created by the backIntent call to startActivity. No need to call dialog.cancel() in onBackPressed. When I mentioned startActivityForResult I was referring to the AndroidTabLayoutActivity and not FileExplore, I am assuming you do have an onActivityResult() method in AndroidTabLayoutActivity because you are using this code (continued in next comment) – A Random Android Dev Aug 24 '12 at 14:43
  • Intent i = new Intent(getApplicationContext()FileExplore.class);i.putExtras(b); startActivityForResult(i, 0); Since you are calling startActivityForResult you should check if the result being returned from FileExplore is RESULT_OK (you have to manually set the result in FileExplore class using setResult(RESULT_OK, intenttosendtoAndroiTabLayouActivity); Please read about onActivityResult() method in Android first. Basically onActivityResult allows you to get a result back and you can check if the result code is RESULT_OK and only then do something. – A Random Android Dev Aug 24 '12 at 14:47
  • Oh, of course. I do have onActivityResult. And that part works fine, when I choose a file. But not when onBackPressed. The thing that works the best right now is when i call dialog.cancel(); - it doesn't create new intent and it "works". But it still gives me black screen first - and then on second click it gives me the screen i want. *Edited my question with my onActivityResult code* – Rad Aug 24 '12 at 15:38
  • Well, so when you click back once, it takes you to an activity which is dead/doesn't have a layout and when you click it again it takes you back to the AndroidTabLayoutActivity which is what you want. So I'd advise you to avoid using startActivity(backIntent) completely and just use dialog.cancel or this.finish() in your onBackPressed(). What happens when you just call this.finish(). Let me know – A Random Android Dev Aug 24 '12 at 21:34
  • Just tried it. It does exactly the same as dialog.cancel(); One click - black screen - second click - AndroidTabLayoutActivity. Just so we're clear. I stopped using the startActivity(backIntent). Screenshot of my code in FileExplore. http://img1.uploadscreenshot.com/images/orig/8/23610394722-orig.jpg It's weird, cause it goes into the onBackPressed on second click, and not on the first. – Rad Aug 24 '12 at 23:59
  • And it of course still goes into the onActivityResult in PhotosActivity. What should I write in the "else if (resultCode == 0) (if back is pressed) ? – Rad Aug 25 '12 at 00:13
  • Try calling super.onBackPressed() after this.finish(); – A Random Android Dev Aug 25 '12 at 00:52
  • Nope, still the same. Don't know - I guess I have to debug every line in the code. I just don't understand why it goes down in the onBackPressed method on second click and not first. The Logcat doesn't look helpful either. http://img1.uploadscreenshot.com/images/main/8/23621553467.jpg The two marked lines are my clicks. – Rad Aug 25 '12 at 11:15
  • Just debugged - the debugger doesn't go ANYWHERE, when backbutton is hit the first time. – Rad Aug 25 '12 at 11:29
  • My file picker doesn't have an Layout-xml, but is made in the actual (FileExpore) code. Is it still the correct way to open with intent? Sorry for all these ideas. But it's just weird. – Rad Aug 25 '12 at 13:59