Issue
New to Android development here, and I need help.
This code/function is working in the built-in emulator of Android Studio with Android 11.
private String[] getData(String filename) throws IOException {
FileInputStream fin = null;
int ch;
StringBuffer sb = new StringBuffer();
String text = "";
String[] fragments = new String[0];
try{
fin = new FileInputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/"+filename);
while((ch = fin.read()) != -1) {
sb.append((char)ch);
}
text = sb.toString();
fragments = text.split(";");
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
}
finally {
// close the stream using close method
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
return fragments;
}
The code just read the file in the public folder "Documents" and return the contents as array of Strings. But for some reason, this code doesn't work in Android 10.
The manifest file includes these two requests:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Solution
You can use the same code.
But for an Android 10 device you should add
requestLegacyStorageLocation="true"
(or something like that ) in application tag of manifest file.
Answered By - blackapps
Answer Checked By - Willingham (JavaFixing Volunteer)