Android: How to select a file

0 Comments

An often useful feature is the ability to choose a file to fiddle with, may it be a photo, a music file or a text file.

To kick it off, we need to start an activity with an intent of ACTION_GET_CONTENT.

01.public class ActivityTestActivity extends Activity {
02.  final int ACTIVITY_CHOOSE_FILE = 1;
03. 
04.  @Override
05.  public void onCreate(Bundle savedInstanceState) {
06.    super.onCreate(savedInstanceState);
07.    setContentView(R.layout.main);
08. 
09.    Button btn = (Button) this.findViewById(R.id.Button01);
10.    btn.setOnClickListener(new OnClickListener() {
11.      @Override
12.      public void onClick(View v) {
13.        Intent chooseFile;
14.        Intent intent;
15.        chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
16.        chooseFile.setType("file/*");
17.        intent = Intent.createChooser(chooseFile, "Choose a file");
18.        startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
19.      }
20.    });
21.  }
22. 
23.  @Override
24.  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
25.    switch(requestCode) {
26.      case ACTIVITY_CHOOSE_FILE: {
27.        if (resultCode == RESULT_OK){
28.          Uri uri = data.getData();
29.          String filePath = uri.getPath();
30.        }
31.      }
32.    }
33.  }
34.}

NOTE: If you're constantly getting "No applications can perform this action", even with FileExpert or ASTRO installed, then you need to give your emulator some space in "/sdcard" to work with.

So what this code does is:

  • Creates an intent to get some content.
  • Gives the choose a title of "Choose a file"
  • Kicks off the file chooser activity with the ID of ACTIVITY_CHOOSE_FILE (1).
  • When the activity returns with a result, we need to check if it was a valid result with RESULT_OK.
  • After you get the filePath out of data.getData().getPath() and you can begin working with the file.

WmVjM

Keep rollin' speed-demon!

Source: choose a file from device and upload it to page loaded in the webview
 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog