why I can't read json file in kotlin android project - android

val jsonString_ = File("C:/Users/admin/Document/sample.json").readText()
System.out.println(jsonString_)
//or this
val jsonString = applicationContext.assets.open("../res/sample.json")
.bufferedReader()
.use { it.readText() }
System.out.println(jsonString)
I tried both codes but I get "No such file or directory" or "java.io.FileNotFoundException" errors.I tried Intellij, it worked but it doesn't work on android
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:requestLegacyExternalStorage="true"/>
I added them to the manifest file,nothing changed.

Related

OS Error: Operation not permitted, errno = 1) even with MANAGE_EXTERNAL_STORAGE

I have an application that generates some PDFs and CSV files and at the moment I am saving these files into the files folder in the application directory of the Android phone. Then the user needs to manually move the files to another folder (for example Documents or Downloads).
I would like to save the file to the Documents or Download folder (one of the two, is the same) automatically at runtime, after the files are generated by the app. The target devices has Android 11 so I have any kind of problems with managing the external storage.
Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.example">
<!-- PERMISSIONS -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
...
...
Permissions requested at startup:
requestPermissions() async {
try {
await [
Permission.storage,
Permission.manageExternalStorage,
].request();
} catch (e) {
LoggerService().error("PERMISSIONS REQUEST ERROR", e.toString());
}
}
Method that saves the files:
Future<String> export(Uint8List pdf, {String? fileName}) async {
Directory dir = Directory(EnvironmentService.documentsPath);
String path = "${dir.path}/${fileName ?? "${uuid.v4()}.pdf"}";
File file = File(path);
await file.writeAsBytes(pdf);
return path;
}
Path where I am trying to save the files:
static const String documentsPath = "/storage/emulated/0/Documents";
When saving the file I always get OS Error: Operation not permitted, errno = 1) error, even if I have granted the MANAGE_EXTERNAL_STORAGE permission. The application will not be published on the Play Store, and needs to be working only on Android.
Any idea of what's happening?

Creating a CSV file in Android 11 Return Error "java.io.FileNotFoundException: EPERM (Operation not permitted)"

Hello I am trying to create a csv file in my android application. My code works when I try to run it on android 10 below. But I cant seem to find a problem why I cant do it on devices that are Android 11 already.
Here is my Manifest Permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<application
...
android:requestLegacyExternalStorage="true">
Here is my code where I create a folder inside the download folder
#NonNull
public static File getStorageDirectory() {
if (Environment.getExternalStorageState() == null) {
File f = new File(Environment.getDataDirectory().getAbsolutePath() + "/Download/(Project Name)/");
if(!f.exists())
f.mkdirs();
return f;
} else {
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/(Project Name)/");
if(!f.exists())
f.mkdirs();
return f;
}
}
Here is my code on how I create my csv file
File baseDir = Utility.getStorageDirectory();
String fileName = pollutant.getStationName();
String date = Utility.convertDate(new Date().getTime(), "dd-MM-yyyy HH:mm:ss");
File csvFile = new File(baseDir, fileName + "(1hr - "+pollutant.getPollutantName()+")(" + date + ").csv");
FileWriter writer;
if(csvFile.exists() && !csvFile.isDirectory()) {
writer = new FileWriter(csvFile , true);
} else {
writer = new FileWriter(csvFile);
}
I am already creating a folder in the download folder in android 11 problem is when I am trying to do the create csv part program return a
java.io.FileNotFoundException: ... open failed: EPERM (Operation not permitted)
I am really having a hard time to fix my problem for devices with android 11
"dd-MM-yyyy HH:mm:ss"
You have a forbidden character in your file name.
A : is not allowed.
Change to "dd-MM-yyyy HH.mm.ss" or so.
I believe that this a permission issue. In Order to Write into files you need to allow it.
Here is example of the code:
public void onPermission()
{
// Permision can add more at your convinient
if ((ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) !=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(
this,
new String[]
{
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH,
Manifest.permission.CAMERA,
Manifest.permission.CALL_PHONE
},
0
);
}
}
Usage :
onPermission(); at onStart() or in the onAcitivty().
Alternatively you can use a library as well ,
Reference : https://github.com/Karumi/Dexter
For External Storage:
Add attribute in your app's AndroidManifest.xml file inside the application tag:
android:requestLegacyExternalStorage="true"
eg.
<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/AppTheme"
android:requestLegacyExternalStorage="true">
...
</application>
For More Reference : https://stackoverflow.com/a/61406983/10758321
I have a similar behavior in my “SFTP Server s0 v1” app and the problem respective the allowed characters in file- and directory-names is related to the underlying file system – see Comparison of file systems . You can check which file system is mounted to which directory by calling adb shell mount. For example creating a file in your application home directory (e.g. /data/data/ch.becke.sftp_server__s0_v1/files) is no issue because the /data directory is mounted as ext4 (/dev/block/dm-5 on /data type ext4 ...) which allows almost all characters in file names. Whereas the external storage directory (e.g. /storage/emulated/0 or /storage/140E-3C1A) is mounted as vfat or fuse which only allows a limited set of characters in file names. (in my app I alternatively also support managing files using scoped storage but I personally think this is even worse because it auto replaces all special characters with an underscore character _).

Android studio getting error IOException: Operation not permitted while creating file

I am trying to create a file. (testipfs folder already exists)
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "testipfs");
File photo= new File(imagesFolder, "desktopWallpaper.jpg");
System.out.println("Saving file in "+photo.getAbsolutePath());
if (!photo.exists()) {
try {
photo.createNewFile();
} catch (IOException e) {
System.out.println("Failed to create photo");
e.printStackTrace();
}
}
But getting error Operation not permitted.
I/System.out: Saving file in /storage/emulated/0/testipfs/desktopWallpaper.jpg
I/System.out: Failed to create photo
W/System.err: java.io.IOException: Operation not permitted
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
at java.io.File.createNewFile(File.java:1008)
at com.example.ipfs.MainActivity.SavePhotoTask(MainActivity.java:49)
at com.example.ipfs.MainActivity.onCreate(MainActivity.java:112)
I have added permission in my manifest file as bellow
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
How do i solve this problem?
I am expecting you are testing your application in android 11, In Android 11 things changed ... You have to ask for this permission
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
and in you MainActivity
if (Build.VERSION.SDK_INT >= 30){
if (!Environment.isExternalStorageManager()){
Intent getpermission = new Intent();
getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(getpermission);
}
}
Basically this is just an intent which will take user to setting to give us Permission, and this is necessary in android 11 , If you just asking for READ nd WRITE permission then you application is having just a read-only access to files in the device
Try to add requestLegacyExternalStorage in Manifest.xml file, if you are using Android 10 or later versions.
<application
...
android:requestLegacyExternalStorage="true">
Use this
File imagesFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "testipfs");
File photo = new File(imagesFolder, "desktopWallpaper.jpg");
Declaring permissions in the Manifest file is not enough if you are using Android Marshmallow and above, before you write or read any external files you need to request the appropriate permissions explicitly.
storage-permission-error-in-marshmallow
Documentation
If this doesn't work try setting your targetSdkVersion to 28 or less.
I had special characters in my directory name (specifically ":"). Removing this allowed me to save the file

Writing logs with Tinylog on Android

I want to save logs on Android using tinylog and I have added dependencies and configuration file. Sometimes the file is created with content and other times the file is empty. It seems like random behavior. Also the app has writing and reading permissions.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have added this on graddle.
implementation 'org.tinylog:tinylog-api:2.1.0'
implementation 'org.tinylog:tinylog-impl:2.1.0'
I have put my tinylog.properties file inside src/main/resources
writer1 = logcat
writer1.level = debug
writer2 = rolling file
writer2.level = trace
writer2.format = {date} [{thread}] {level}:\n{message}
writer2.file = /storage/emulated/0/app/logs/log_{date:yyyyMMdd}.txt
writer2.charset = UTF-8
writer2.append = true
writer2.policies = daily: 03:00
writingthread = true

Not able to create a new folder in device's Documents folder even after giving runtime permissions

Asking this questions after trying a lot. I have checked a lot ob blogs and questions.
When I'm trying to create a new folder in the device's doucments folder, its not creating the folder even after giving all permissions including runtime permissions.
This is my code to create the new folder -
var path = (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS))
var directory = path.absolutePath + "/justCheck"
var file = File(directory)
if(!file.exists()){
file.createNewFile()
}
I'm checking on Android device with marshmallow OS. This is my permissions in Manifest -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Also, I have authorized the runtime permissions.
Am I doing anything wrong ? Why is the older not getting created ?
You've to create a folder not a file:
file.mkdirs();

Categories

Resources