I'm trying to open up file selector in my Android Program, like this:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
Now inside onActivityResult
, I'm doing:
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
path = MainActivity.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
try {
//readFile(uri.toString())
readFile(path);
} catch (Exception e) {
e.printStackTrace();
}
And inside read file I'm just trying to read it's content, which is giving me nullPointerException.
private static void readFile(String path) throws Exception {
Log.d(TAG,"inside readFile -->> "+path);
String data=MainActivity.getStringFromFile(path);
Log.d(TAG,"data "+data);
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
fin.close();
return ret;
}
How can I resolve this ?
Even I have taked external storage permission, although I don't have one.
Path looks something like this : /storage/emulated/0/CodeRead/springboot-react-chatroom-master/springboot-react-chatroom-master/README.md
And the URI : content://com.mi.android.globalFileexplorer.myprovider/external_files/CodeRead/springboot-react-chatroom-master/springboot-react-chatroom-master/README.md
Trace :
2020-04-01 17:26:00.502 22327-22327/com.org.orgcodereader W/System.err: at com.org.orgcodereader.activity.MainActivity.getStringFromFile(MainActivity.java:165)
2020-04-01 17:26:00.502 22327-22327/com.org.orgcodereader W/System.err: at com.org.orgcodereader.activity.MainActivity.readFile(MainActivity.java:147)
2020-04-01 17:26:00.502 22327-22327/com.org.orgcodereader W/System.err: at com.org.orgcodereader.activity.MainActivity.onActivityResult(MainActivity.java:135)
2020-04-01 17:26:00.503 22327-22327/com.org.orgcodereader W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6864)
2020-04-01 17:26:00.503 22327-22327/com.org.orgcodereader W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I noticed sometimes MainActivity.getStringFromFile(path);
is producing null
, so this happens. And there is special reason behind that I guess, if I select on recent or other options, but if I select FileManager
it works fine.
When I select other method the URI looks something just like this :
content://com.android.externalstorage.documents/document/primary%3APictures%2FInstagram%2FIMG_20200305_214854_891.jpg