android file chooser,Android file chooser - Stack Overflow

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.

ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

intent.setType("*/*");

intent.addCategory(Intent.CATEGORY_OPENABLE);

try {

startActivityForResult(

Intent.createChooser(intent, "Select a File to Upload"),

FILE_SELECT_CODE);

} catch (android.content.ActivityNotFoundException ex) {

// Potentially direct the user to the Market with a Dialog

Toast.makeText(this, "Please install a File Manager.",

Toast.LENGTH_SHORT).show();

}

}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

switch (requestCode) {

case FILE_SELECT_CODE:

if (resultCode == RESULT_OK) {

// Get the Uri of the selected file

Uri uri = data.getData();

Log.d(TAG, "File Uri: " + uri.toString());

// Get the path

String path = FileUtils.getPath(this, uri);

Log.d(TAG, "File Path: " + path);

// Get the file instance

// File file = new File(path);

// Initiate the upload

}

break;

}

super.onActivityResult(requestCode, resultCode, data);

}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {

if ("content".equalsIgnoreCase(uri.getScheme())) {

String[] projection = { "_data" };

Cursor cursor = null;

try {

cursor = context.getContentResolver().query(uri, projection, null, null, null);

int column_index = cursor.getColumnIndexOrThrow("_data");

if (cursor.moveToFirst()) {

return cursor.getString(column_index);

}

} catch (Exception e) {

// Eat it

}

}

else if ("file".equalsIgnoreCase(uri.getScheme())) {

return uri.getPath();

}

return null;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值