Android: How to select a file

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.

public class ActivityTestActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button btn = (Button) this.findViewById(R.id.Button01);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("file/*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK){
Uri uri = data.getData();
String filePath = uri.getPath();
}
}
}
}
}

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