Ad

Unable To Get URI Of A Text File

- 1 answer

I am trying to make an app in which I can take text input from the user store it in a text file and then upload that file to firebase so that I can retrieve it later.

The issue is that I am unable to get the correct URI of the file. Please help me get the URI.

Here is the code

public class TextUpload extends AppCompatActivity {

    private void writeToFile(String data, Context context) throws FileNotFoundException {
        mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        if (!mediaFile.exists()) {
            mediaFile.mkdir();
        }
        byte[] data2 = data.getBytes();

        FileOutputStream f = new FileOutputStream(new File(mediaFile, "textfile.txt"));
        try {
            f.write(data2);
            f.flush();
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileUri =  Uri.fromFile(mediaFile);
        Log.d("TAHH" , "URI = "+fileUri);
    }
}

This is the value I'm getting stored at fileUri

URI = file:///storage/emulated/0

[roid]

Please help me get the URI of the highlighted file.

Ad

Answer

Main problem is that you are reading the path of mediaFile which is a directory (not the file itself). mediaFile is the parent directory of the file that you want.

So, change to this:

mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());


if (!mediaFile.exists()) {
    mediaFile.mkdir();
}
byte[] data2 = data.getBytes();

// Hold the reference to the file that you are writting
File txtFile = new File(mediaFile, "textfile.txt")
FileOutputStream f = new FileOutputStream(txtFile );

try {
    f.write(data2);
    f.flush();
    f.close();
} catch (IOException e) {
    e.printStackTrace();
}

// Here, use txtFile instead of mediaFile
fileUri =  Uri.fromFile(txtFile);
Log.d("TAHH" , "URI = "+fileUri);
Ad
source: stackoverflow.com
Ad