Add the following permission to your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
....
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
.....
</application>
Create the provider-paths.xml
file under res/xml
and put the following code in it:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_file_path" path="." />
</paths>
You can create a file and then write the jsonobject to it i.e.
StringBuilder stringBuilder = new StringBuilder();
File tempFolder = new File(MainActivity.this.getFilesDir(), "temp");
if (!tempFolder.exists()) {
tempFolder.mkdir();
}
JSONObject export = new JSONObject();
try {
export.put("name", "my-name");
export.put("age", "20");
} catch (JSONException e) {
e.printStackTrace();
}
File file = null;
try {
Writer wrt = null;
file = new File(tempFolder, "myJsonFile.json");
wrt = new BufferedWriter(new FileWriter(file));
wrt.write(export.toString());
wrt.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("file/text/plain");
Uri fileUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",
file);
shareIntent.putExtra(Intent.EXTRA_TEXT, "THE CONTENT IS " + export.toString());
shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "Send the object via"));
try {
File f = new File(MainActivity.this.getFilesDir() + "/temp/myJsonFile.json");
InputStream inputStream = new DataInputStream(new FileInputStream(f));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
str = bufferedReader.readLine();
stringBuilder.append(str);
tvAccountName.setText(stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
//then delete the file or you can delete the tempFolder instead;
if(file!=null)file.delete();
The intent is opening in my case and is sharing in my apps e.g. Whatsapp and Telegram. To explain it a bit, Android no longer allows file://
to be attached to Intents, check this. Therefore, you need to use File provider to achieve this as is documented in their website.