Android - open file from phone memory using intent

守給你的承諾、 提交于 2020-01-02 00:24:07

问题


I am working on an app that takes the .txt file from a phone as input and prints it on the TextView,

public class MainActivity extends AppCompatActivity {
Button button;
Intent intent;private StringBuilder text = new StringBuilder();



private InputStream getResources(String s) {
    return null;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.btn);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("text/plain");
            startActivityForResult(intent, 7);
            Log.v("###", "parent "  + getParent());
        }

    });
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String Fpath = data.getDataString();
  //  final String fileName = ""+Fpath;
    Log.v("###", "yo " +Fpath);

    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case 7:

            if (resultCode == RESULT_OK) {
                setContentView(R.layout.activity_main);


                Log.v("###", "hellow");
                setContentView(R.layout.activity_main);
                BufferedReader reader = null;

                try {

                    reader = new BufferedReader(

             new InputStreamReader(getAssets().open("filename.txt")));
                    //change code
                    // do reading
                    String mLine;
                    while ((mLine = reader.readLine()) != null) {
                        text.append(mLine);
                        text.append('\n');
                    }
                } catch (IOException e) {
                    String PathHolder = data.getData().getPath();
                    Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                } finally {


                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            //log the exception
                        }
                    }

                    TextView output = (TextView) findViewById(R.id.Txt);
                    output.setText((CharSequence) text);

                }
            }
    }
}
}

everything is good but the line

new InputStreamReader(getAssets().open("filename.txt")));

Taking the file from Assets folder, Help me to get the file from My phone,

The file from Assets folder opening properly but I want it to be select from my phone


回答1:


You can get file path in onActivityResult which you selected from file manager.

 Uri PathHolder = data.getData();

UPDATE

Above line give you uri of file which you selected from storage. Then You can get File from that Uri easily.

Just forgot about getAssets Use Following method to read from file.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri PathHolder = data.getData();
    FileInputStream fileInputStream = null;
    StringBuilder text = new StringBuilder();
    try {
        InputStream inputStream = getContentResolver().openInputStream(PathHolder);
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        String mLine;
        while ((mLine = r.readLine()) != null) {
            text.append(mLine);
            text.append('\n');
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}



回答2:


You can try this approach:

 public static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

 public static Uri getFileUri(String filePath) {
    Uri fileUri = null;
    File file = new File(filePath);
    try {
        if (Build.VERSION.SDK_INT >= 24) {
            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        }
        fileUri = Uri.fromFile(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileUri;
}

and for the intent:

if (path.endsWith(".txt") || path.endsWith(".TXT")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(getFileUri(path.trim()), getMimeType(path.trim()));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        } else
            Toast.makeText(context, "There is no application available to handle your request!!", Toast.LENGTH_SHORT).show();

    } 



回答3:


There is a slight change in your onActivityResult First paste this code in your activity.

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

            final boolean isKitKat = true;

            // DocumentProvider
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{
                            split[1]
                    };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            return null;
        }
  public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
 public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
  public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

now change your onActivityResult to this.

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
//                String pickedImage = data.getData().getPath();
                String dataString = getPath(this, Uri.parse(data.getDataString()));
                Log.i(TAG, "onActivityResult: pathholder " + dataString);
                File file = new File(dataString);//
                FileInputStream fis = null;
                Log.i(TAG, "onActivityResult: file " + file.getName());
/**if you get the uri(path) then add this following code that i given below*/
                try {
                    fis = new FileInputStream(file.getAbsolutePath());
                    InputStreamReader isr = new InputStreamReader(fis);
                    BufferedReader bufferedReader = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line).append("\n");

                    }
                    Log.i(TAG, "onActivityResult: pathholder " + sb.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }
        }
    }


来源:https://stackoverflow.com/questions/52713245/android-open-file-from-phone-memory-using-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!