I am building an application in which when a user press "Browse" button on the application I want to show folders from phone where user will select the file/image. Once the attachment is selected, application will show the file name in the attachments. What I am looking for is how the file attachment mechanism work in android so any code example or snippet in much appreciated.
Thanks in advance.
What you actually want to do is execute Intent.ACTION_GET_CONTENT. If you specify type to be "file/*"
then the file picker will allow you to select file of any type from the file system.
Here are a couple of reads:
- Android documentation on ACTION_GET_CONTENT
- A working example
This is the extracted source from the blog (courtesy of Android-er):
public class AndroidPick_a_File extends Activity {
TextView textFile;
private static final int PICKFILE_RESULT_CODE = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPick = (Button)findViewById(R.id.buttonpick);
textFile = (TextView)findViewById(R.id.textfile);
buttonPick.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
String FilePath = data.getData().getPath();
textFile.setText(FilePath);
}
break;
}
}
}
After acquiring path to the selected file it is up to you on how are you going to handle it: store path in a database, display it on screen, etc.
If you want to open the file with a default application, follow advices in this blog. Again, I extracted the code (courtesy of Hello World Codes):
First way:
String path="File Path";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
intent.setData(Uri.fromFile(file));
startActivity(intent);
Second way:
String path="File Path";
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext=file.getName().substring(file.getName().indexOf(".")+1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file),type);
startActivity(intent);
Please remember to leave thanks to the guys who deserve it (-.
- http://android-er.blogspot.co.uk/2011/03/pick-file-using-intentactiongetcontent.html
- http://helloworldcodes.blogspot.co.uk/2011/10/android-open-folder-with-default.html