Suraj nayi
Suraj nayi

Reputation: 21

how to retrieved file and it's data in android? which i have store using mediastore

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();

Upvotes: 1

Views: 126

Answers (1)

Nguyễn Minh Khoa
Nguyễn Minh Khoa

Reputation: 125

I tested your code

Maybe you miss this code:

android:requestLegacyExternalStorage="true"

I also set up in Android Manifest

 <uses-permission
        android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
 <uses-permission
        android:name="android.permission.READ_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
 <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />

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

 private fun createFile() {
        val data = "nguyen minh khoa tested for you".toByteArray()
        val values = 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 + "/TestByKhoa/"
        ) //end "/" is not mandatory
        val uri =
            contentResolver.insert(MediaStore.Files.getContentUri("external"), values) //important!
        binding.text2.text = "Created test"
        try {
            val outputStream = contentResolver.openOutputStream(uri!!)
            if (outputStream != null) {
                outputStream.write(data)
                outputStream.close()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun readFile() {
        val contentUri = MediaStore.Files.getContentUri("external")
        val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
        val projection = arrayOf("_id")
        val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS + "/TestByKhoa/")
        val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null)
        var uri: Uri? = null
        if (cursor!!.count == 0) {
            Toast.makeText(
                this@MainActivity,
                "No file found in \"" + Environment.DIRECTORY_DOCUMENTS + "/TestByKhoa/\"",
                Toast.LENGTH_LONG
            ).show()
        } else {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") val fileName = cursor.getString(
                    cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                )
                if (fileName == "customstore.txt") {
                    @SuppressLint("Range") val id = cursor.getLong(
                        cursor.getColumnIndex(MediaStore.MediaColumns._ID)
                    )
                    uri = ContentUris.withAppendedId(contentUri, id)
                    break
                }
            }
            if (uri == null) {
                Toast.makeText(
                    this@MainActivity,
                    "\"customstore.txt\" not found",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                try {
                    val inputStream = contentResolver.openInputStream(uri)
                    val size = inputStream!!.available()
                    val bytes = ByteArray(size)
                    inputStream.read(bytes)
                    inputStream.close()
                    val jsonString = String(bytes, StandardCharsets.UTF_8)
                    binding.text3.text = jsonString
                } catch (e: IOException) {
                    Toast.makeText(this@MainActivity, "Fail to read file", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        }
    }

Here is result. You want ?

Comment If you still get error

Upvotes: 0

Related Questions