I am created file and put some data inside file using media store. after uninstall application and again install the application then unable to retrieve file and it's data.
private void createFile() {
byte[] data = "test".getBytes();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "customstore"); //file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain"); //file extension, will automatically add to file
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS + "/Sooraj/"); //end "/" is not mandatory
Uri uri = getContentResolver().insert(MediaStore.Files.getContentUri("external"), values); //important!
text2.setText("Created test");
try {
OutputStream outputStream = getContentResolver().openOutputStream(uri);
if (outputStream != null) {
outputStream.write(data);
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void readFile() {
Uri contentUri = MediaStore.Files.getContentUri("external");
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] projection = new String[]{"_id"};
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS + "/Sooraj/"};
Cursor cursor = getContentResolver().query(contentUri, null, selection, selectionArgs, null);
Uri uri = null;
if (cursor.getCount() == 0) {
Toast.makeText(MainActivity.this, "No file found in \"" + Environment.DIRECTORY_DOCUMENTS + "/Sooraj/\"", Toast.LENGTH_LONG).show();
} else {
while (cursor.moveToNext()) {
@SuppressLint("Range") String fileName = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
if (fileName.equals("customstore.txt")) {
@SuppressLint("Range") long id = cursor.getLong(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
uri = ContentUris.withAppendedId(contentUri, id);
break;
}
}
if (uri == null) {
Toast.makeText(MainActivity.this, "\"customstore.txt\" not found", Toast.LENGTH_SHORT).show();
} else {
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
int size = inputStream.available();
byte[] bytes = new byte[size];
inputStream.read(bytes);
inputStream.close();
String jsonString = new String(bytes, StandardCharsets.UTF_8);
text3.setText(jsonString);
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Fail to read file", Toast.LENGTH_SHORT).show();
}
}
}
}
using this i have create file. re-install app then i am unable to retrive file and it's data. please help me. only show toast below code.
Toast.makeText(MainActivity.this, "No file found in "" + Environment.DIRECTORY_DOCUMENTS + "/Sooraj/"", Toast.LENGTH_LONG).show();
I tested your code
Maybe you miss this code:
I also set up in Android Manifest
MANAGE_EXTERNAL_STORAGE used the most in app type File Manager , and with this permission , your app often get ignored by CH PLAY STORE. If your app not type of File Manager
Just edit some code of your like name of folder
Comment If you still get error