Cannot create file in external storage - android

I'm trying to create a file in the external storage directory of the Nougat emulator. using the following code:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test987689");
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}try {
if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
file.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
Permissons:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And I'm getting the following error:
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:958)
W/System.err: at com.vibhinna.sreni.SplashActivity.onCreate(SplashActivity.java:41)
W/System.err: at android.app.Activity.performCreate(Activity.java:6658)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2584)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2692)
W/System.err: at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1445)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6044)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
What am I doing wrong?

If your targetSdk is 23 or higher, you should request permissions dynamically.
to know more : Requesting Permissions at Run Time

to get File path you can use Context.getExternalFilesDir()/Context.getExternalCacheDir()
for example
String path=Context.getExternalCacheDir()+"file.text";
File file=new File(path)
it doesnt need permission if the filepath is "Android/data/app package/file name"

Related

Android app, http request to ip address fails

I have simple "gadget" based on Arduino. It is connected to the wlan of my house and sending web requests to it turns on/off a red LED indicating that I'm busy/free in my room. This works fine when called from a browser or from my small winforms application. It is called synchronous, it is just enough, no need for async calls.
But, I tried to create a android app that sends the same requests, no success. I have read many topics, tried different ways etc. The app has this row in manifest file:
android:networkSecurityConfig="#xml/network_security_config"
Maybe something is still missing. This might be very very basic, but I haven't been able to get it working. Code:
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OkHttpClient client = new OkHttpClient();
String url = "http://192.168.100.12/LED=ON";
Request req = new Request.Builder()
.url(url)
.build();
try {
client.newCall(req).execute();
} catch (IOException | RuntimeException e) {
e.printStackTrace();
}
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
}
It fails on execute call. The app enters the catch section, but there's no understandable description in e. And of course, my mobile phone is connected to the same wlan.
Stack trace:
I/System.out: port:80
W/System.err: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err: at java.net.Socket.connect(Socket.java:631)
W/System.err: at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.kt:63)
W/System.err: at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:295)
W/System.err: at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:207)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:226)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:106)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:74)
W/System.err: at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:255)
W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
W/System.err: at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
W/System.err: at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
W/System.err: at com.example.donotdisturb.FirstFragment$1.onClick(FirstFragment.java:52)
W/System.err: at android.view.View.performClick(View.java:6603)
W/System.err: at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
W/System.err: at android.view.View.performClickInternal(View.java:6576)
W/System.err: at android.view.View.access$3100(View.java:780)
W/System.err: at android.view.View$PerformClick.run(View.java:26088)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6705)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911)

Android Studio - java.io.FileNotFoundException: /abc.csv open failed: EACCES (Permission denied)

I am trying to read a CSV file, load its content to a spinner. I have given relevant permissions MANAGE_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE to read a file from external storage. I have placed the CSV file in a directory requested permission on runtime. Also the file.exists() function return true but still unable to read csv file. Where am I going wrong?
Here is the error log:
022-02-27 18:03:32.457 13080-13080/com.example.locationfetcher_v2 W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Khidmah/input.csv: open failed: EACCES (Permission denied)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.IoBridge.open(IoBridge.java:492)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:160)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:115)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.io.FileReader.<init>(FileReader.java:58)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at com.example.locationfetcher_v2.MainActivity.onCreate(MainActivity.java:157)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.Activity.performCreate(Activity.java:8157)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.Activity.performCreate(Activity.java:8129)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3494)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3693)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2135)
2022-02-27 18:03:32.461 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.os.Handler.dispatchMessage(Handler.java:106)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.os.Looper.loop(Looper.java:236)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread.main(ActivityThread.java:8059)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:656)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:967)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.Linux.open(Native Method)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7932)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
2022-02-27 18:03:32.462 13080-13080/com.example.locationfetcher_v2 W/System.err: ... 19 more
Below is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Using Dexter Library
Dexter.withContext(this)
.withPermissions(
Manifest.permission.MANAGE_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA
).withListener(new MultiplePermissionsListener() {
#Override public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */}
#Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */}
}).check();
MultiplePermissionsListener dialogMultiplePermissionsListener =
DialogOnAnyDeniedMultiplePermissionsListener.Builder
.withContext(this)
.withTitle("Camera, Storage and Location permission")
.withMessage("All Camera, Storage and Location permission are required for this application")
.withButtonText(android.R.string.ok)
.build();
//// Read data from CSV file
List<String> addresses = new ArrayList<String>();
Spinner address_spinner = findViewById(R.id.spinnerAddress);
// File file = new File(Environment.getExternalStorageDirectory() + "/Khidmah/", "input.csv");
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "input.csv");
show_notification(file.getPath());
show_notification(new Boolean(file.exists()).toString());
FileInputStream fis = null;
try {
if (file.exists()){
show_notification("can read - " + new Boolean(file.canRead()).toString());
CSVReader reader = new CSVReader(new FileReader(file.toURI().toString()));
show_notification("successfully read file...");
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
// System.out.println(nextLine[0] + nextLine[1] + nextLine[2]);
addresses.add(nextLine[0] + nextLine[1] + nextLine[2]);
show_notification(nextLine[0] + nextLine[1] + nextLine[2]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item,addresses);
address_spinner.setAdapter(adapter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (CsvValidationException e) {
e.printStackTrace();
}
}
Here is AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationfetcher_v2">
<!-- Always include this permission -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Include only if your app benefits from precise location access. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.LocationFetcher_v2"
android:foregroundServiceType="location">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
UPDATE
I am now using Dexter Library to grant permissions. I have added additional permission MANAGE_EXTERNAL_STORAGE and place the input.csv file in Public Directory i.e. Downloads folder. However now it's giving following error:
open failed: ENOENT (No such file or directory)
After File.exists() use File.canRead() before you act on the file.
This csv file is not created by your app.
Hence on Android 11 you are not the owner and although your app can check if the file exists it discovers with File.canRead() that the file is not accessable.
With MANAGE_EXTERNAL_STORAGE and the right runtime code your app can obtain access.
The right code would start an intent for Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION.

Gluon, Android 10 Black screen issue

Code is working fine for Android 8 and 9, this issue only in Android 10. We can run in Android 10 by using the command adb shell settings put global hidden_api_policy 1. But this is again only device or Emulator specific. Is there any general solution to fix this issue for Android 10.
W/System.err: java.lang.reflect.InvocationTargetException
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at javafxports.android.DalvikLauncher$1.run(DalvikLauncher.java:188)
W/System.err: at java.lang.Thread.run(Thread.java:923)
W/System.err: Caused by: java.lang.RuntimeException: Exception in Application start method
W/System.err: at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
W/System.err: at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$138(LauncherImpl.java:182)
W/System.err: at com.sun.javafx.application.LauncherImpl.access$lambda$1(Unknown Source:8)
W/System.err: at com.sun.javafx.application.LauncherImpl$$Lambda$2.run(Unknown Source:13)
W/System.err: ... 1 more
W/System.err: Caused by: java.lang.NoSuchMethodError: No static method getLogger(Ljava/lang/String;)Lsun/util/logging/PlatformLogger; in class Lsun/util/logging/PlatformLogger; or its super classes (declaration of 'sun.util.logging.PlatformLogger' appears in /apex/com.android.art/javalib/core-oj.jar)
W/System.err: at com.sun.javafx.util.Logging.getCSSLogger(Logging.java:98)
W/System.err: at com.sun.javafx.css.parser.CSSParser.<clinit>(CSSParser.java:164)
W/System.err: at com.sun.javafx.css.StyleManager.loadStylesheetUnPrivileged(StyleManager.java:1079)
W/System.err: at com.sun.javafx.css.StyleManager.loadStylesheet(StyleManager.java:910)
W/System.err: at com.sun.javafx.css.StyleManager._addUserAgentStylesheet(StyleManager.java:1263)
W/System.err: at com.sun.javafx.css.StyleManager.setUserAgentStylesheets(StyleManager.java:1204)
W/System.err: at com.sun.javafx.application.PlatformImpl.lambda$_setPlatformUserAgentStylesheet$165(PlatformImpl.java:698)
W/System.err: at com.sun.javafx.application.PlatformImpl.access$lambda$13(Unknown Source:2)
W/System.err: at com.sun.javafx.application.PlatformImpl$$Lambda$14.run(Unknown Source:4)
W/System.err: at java.security.AccessController.doPrivileged(AccessController.java:43)
W/System.err: at com.sun.javafx.application.PlatformImpl._setPlatformUserAgentStylesheet(PlatformImpl.java:697)
W/System.err: at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:548)
W/System.err: at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:512)
W/System.err: at javafx.scene.control.Control.<clinit>(Control.java:86)
W/System.err: at com.gluonhq.charm.glisten.application.MobileApplication.start(SourceFile:202)
W/System.err: at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$145(LauncherImpl.java:863)
W/System.err: at com.sun.javafx.application.LauncherImpl.access$lambda$8(Unknown Source:4)
W/System.err: at com.sun.javafx.application.LauncherImpl$$Lambda$9.run(Unknown Source:7)
W/System.err: at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$158(PlatformImpl.java:326)
W/System.err: at com.sun.javafx.application.PlatformImpl.access$lambda$6(Unknown Source:4)
W/System.err: at com.sun.javafx.application.PlatformImpl$$Lambda$7.run(Unknown Source:7)
W/System.err: at com.sun.javafx.application.PlatformImpl.lambda$null$156(PlatformImpl.java:295)
W/System.err: at com.sun.javafx.application.PlatformImpl.access$lambda$18(Unknown Source:2)
W/System.err: at com.sun.javafx.application.PlatformImpl$$Lambda$19.run(Unknown Source:4)
W/System.err: at java.security.AccessController.doPrivileged(AccessController.java:59)
W/System.err: at com.sun.javafx.application.PlatformImpl.lambda$runLater$157(PlatformImpl.java:294)
W/System.err: at com.sun.javafx.application.PlatformImpl.access$lambda$5(Unknown Source:4)
W/System.err: at com.sun.javafx.application.PlatformImpl$$Lambda$6.run(Unknown Source:7)
W/System.err: at com.sun.glass.ui.monocle.RunnableProcessor.runLoop(RunnableProcessor.java:93)
W/System.err: at com.sun.glass.ui.monocle.RunnableProcessor.run(RunnableProcessor.java:52)
Below is the gradle file code of application, have added the dependency and configuration and per document.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.javafxports:jfxmobile-plugin:1.3.12'
}
}
apply plugin: 'org.javafxports.jfxmobile'
repositories {
jcenter()
maven {
url 'https://nexus.gluonhq.com/nexus/content/repositories/releases'
}
}
mainClassName = 'com.gluonapplication.Sample'
dependencies {
compile 'com.gluonhq:charm:5.0.0'
}
jfxmobile {
downConfig {
version = '3.8.0'
// Do not edit the line below. Use Gluon Mobile Settings in your project context menu instead
plugins 'display', 'lifecycle', 'statusbar', 'storage'
}
android {
manifest = 'src/android/AndroidManifest.xml'
}
ios {
infoPList = file('src/ios/Default-Info.plist')
forceLinkClasses = [
'com.gluonhq.**.*',
'javax.annotations.**.*',
'javax.inject.**.*',
'javax.json.**.*',
'org.glassfish.json.**.*'
]
}
}
I used com.gluonhq.charm.down.common.PlatformFactory package insteed of com.gluonhq.attach.util.Platform for jfxmobile-plugin 1x versions. works fine

Permission denied error while Creating new File | Android

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)
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.

Android : error when copying asset sqlite database to database director

I want to use a pre fill database in my app so I found this code.
DB_NAME = "urg1718.sqlite"
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
String path = dbFile.getAbsolutePath();
Log.i("path", "openDatabase: " + path);
if (!dbFile.exists()) {
try {
//the file doesn't exist yet so this function is called
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
//check if the database is present in the folder
Log.i("database", "openDatabase: " + dbFile.exists());
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDatabase(File dbFile) throws IOException {
//pre fil database
InputStream is = context.getAssets().open(DB_NAME);
try {
//where the error occurs
OutputStream os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
}
}
The "OutputStream os = new FileOutputStream" catch the following error.
java.io.FileNotFoundException: /data/data/jle.urgdegarde17_18/databases/urg1718: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:456)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:87)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:127)
W/System.err: at java.io.FileOutputStream.(FileOutputStream.java:116)
W/System.err: at jle.urgdegarde17_18.AssetDatabaseOpenHelper.copyDatabase(AssetDatabaseOpenHelper.java:49)
W/System.err: at jle.urgdegarde17_18.AssetDatabaseOpenHelper.openDatabase(AssetDatabaseOpenHelper.java:35)
W/System.err: at jle.urgdegarde17_18.Chargement.isStoragePermissionGranted(Chargement.java:40)
W/System.err: at jle.urgdegarde17_18.Chargement.onCreate(Chargement.java:18)
W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:135)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
W/System.err: ... 20 more
I tried to use getDatabasePath(), getDatabasePath().getAbsolutePath() and directly put the string returned by those functions into FileOutputStream
I also tried to remove the ".sqlite" from the database name.
I don't understand what i'm doing wrong ...
Thank's.

Categories

Resources