Reputation: 1566
I am giving file browser to user to select file. On onActivityResult I am getting file path as - /file/sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt. When I try to create file object on this I am not able to create. When I remove /file/ and create file object on sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt its getting created. But I cant hardcode to remove /file/ from filepath as on other device it will be giving some other path. below is the code
private void readContactFromFile(String path) {
StringBuilder text = new StringBuilder();
try {
String st = "/file/sdcard/Android/data/com.coca_cola.android.conferenceapp/cache/Conference/export.txt";
File file = new File(st);
if (file.exists()) {
Log.v("TTT", "file exist");
}
Log.v("TTT", file.toString());
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : " + text + " : end");
text.append('\n');
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
and I am getting path on OnActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_PICK_FILE:
Uri uri = data.getData();
String path = data.getData().getPath();
Log.v("PATH", path);
readContactFromFile(path);
break;
}
}
}
And this is how I am calling for opening file browser
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*"); //all files
//intent.setType("text/xml"); //XML file only
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), REQUEST_PICK_FILE);
} 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();
}
How can I get the perfect path or How can I remove this issue? Thanks in Advance
Upvotes: 0
Views: 75
Reputation: 323
Instead of using hardcoded string path get the path using Environment class
File file=new File(String.valueOf(Environment.getExternalStorageDirectory())+"YOUR_REQUIRED_FILE_PATH");
It will not defer from device to device. Hope this helps :)
Upvotes: 0
Reputation: 189
Because of the circumstance that the path differs on different devices you should use the frameworks api to retrieve the appropiate path for you.
Have a look at the Environment class.
Upvotes: 1