Reputation: 3088
I am trying to create a image file to external storage to share it. but while trying following code I am having some error
var icon: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.namelogo)
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "image/*"
val bytes = ByteArrayOutputStream()
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
val path = File.separator + "temporary_file.jpg"
val f = File(Environment.getExternalStorageDirectory().toString(), path)
try {
if (!f.parentFile.exists())
f.parentFile.mkdirs()
if (!f.exists())
f.createNewFile()
f.createNewFile()
val fo = FileOutputStream(f)
fo.write(bytes.toByteArray())
} catch (e: IOException) {
Log.e("path = ", "+ $path " + e.toString())
e.printStackTrace()
}
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/IronyBalls/temporary_file.jpg"));
startActivity(Intent.createChooser(shareIntent, "Share Image"))
Till now I found solutions only to use
if (!f.parentFile.exists())
f.parentFile.mkdirs()
if (!f.exists())
f.createNewFile()
and
to set permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
that I have already used.But still gettig error as below in Error Tab
E/path =: + /temporary_file.jpg java.io.IOException: Permission denied
and in info tab
W/System.err: java.io.IOException: Permission denied
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err: at java.io.File.createNewFile(File.java:948) W/System.err: at com.irony.balls.MainActivity$onCreate$8.onClick(MainActivity.kt:277)
W/System.err: at android.view.View.performClick(View.java:5611)
10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at android.view.View$PerformClick.run(View.java:22276) 10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at android.os.Handler.handleCallback(Handler.java:751) 10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95) 10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at android.os.Looper.loop(Looper.java:154) 10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6195) 10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at java.lang.reflect.Method.invoke(Native Method) 10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874)
10-15 20:33:17.912 29759-29759/com.irony.balls W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)
Upvotes: 1
Views: 3423
Reputation: 529
If your device is working on Android 6 or higher have you already requested runtime permissions?
See https://developer.android.com/training/permissions/requesting.html for more details.
Upvotes: 1