Damastah
Damastah

Reputation: 55

Can someone help me understand calling an Intent to select a file?

I have this code that I have semi working. I want it to pull up a file selector and then return the file chosen into a manipulable format. Maybe File or String.

I read the Android Documentation on how to call this and I still don't understand intents and how to use them.

I'm used to calling a function and then setting the return to a variable and working from there.

I don't know how to set this up in order to do it. I know about some users possibly not having a file explorer, but all my users will.

So how do I get this code to function? When it returns, it does nothing at the moment.

chooseFileButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            EditText enterZipEditText = (EditText) findViewById(R.id.enterZipEditText);
            Intent intent = new Intent();  
            intent.setType("zip/*");  
            intent.setAction(Intent.ACTION_GET_CONTENT);  
            startActivityForResult(Intent.createChooser(intent, "Choose File"), REQUEST_CODE);
        }
    });

Upvotes: 1

Views: 265

Answers (2)

Brian
Brian

Reputation: 799

If you're looking to handle the returned filename, you might want to add the callback:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            // Do Stuff
            String file = data.getData().getPath();
        }
    }
}

Upvotes: 2

0gravity
0gravity

Reputation: 2762

You can try something like:

@Override
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("zip/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
     } catch (android.content.ActivityNotFoundException ex) {
        //Handle error.
     }
    }
});

see if that works. You can find more info on this SO question that I found.

Upvotes: 0

Related Questions