【问题标题】:How can I get URI from a text file?如何从文本文件中获取 URI?
【发布时间】:2018-06-27 04:14:52
【问题描述】:

我这样做是为了获取并显示图像的路径,但我想知道如何对文本文件执行相同操作。

val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
intent.type = "image/*"
startActivityForResult(intent, SELECT_IMAGE)

【问题讨论】:

    标签: android android-intent kotlin uri mediastore


    【解决方案1】:

    我觉得你可以试试

     Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
     intent.setType("text/*");
     startActivityForResult(intent,PICKFILE_RESULT_CODE);
    

    如下获取uri

     @Override
     protected void onActivityResult(..., Intent data) {
     //do your validation
    
     switch (requestCode) {
            case PICKFILE_RESULT_CODE:
            ...
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            try {
                  Log.d(TAG, "File path: " + getPath(this, uri));
              } catch (URISyntaxException e) {
                  e.printStackTrace();
              }
            //do your work
            ...
            break;
        }
    }
    

    添加工具

    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;
    }
    

    【讨论】:

    • 现在之后我怎么能做一个 getPath(uri:Uri):String 的方法
    • 当我做 val projection = arrayOf(MediaStore.Images.Media.DATA)
    • val colmn_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
    • cursor.moveToFirtst()
    • 最后返回 cursor.getString(column_index)
    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2011-09-25
    • 2011-06-16
    • 1970-01-01
    • 2012-10-27
    • 2014-06-06
    • 2013-12-08
    相关资源
    最近更新 更多