Read file in android - file permission denied - android

I want to read file from external storage. I uploaded the file in Eclipse DDMS to storage/sdcard (image below). But whenever I tried to read, I got an error of permission denied. Is there any problem in my file permission? Or I need to add anything in manifest file (I am not writing anything at the moment)?
Any help will be appreciated.
Code:
public void extimport(View v){
EditText xedittxt = (EditText) findViewById(R.id.frmexttxt);
String xedit = xedittxt.getText().toString();
xedit = xedit.trim();
File file;
file = new File(xedit);
StringBuilder text = new StringBuilder();
Log.d("fcheck",""+xedit);
try {
BufferedReader br = new BufferedReader(new FileReader(file)); //THIS LINE THROWS ERROR
Log.d("fcheck","f3"); //This line never got printed
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
resultView = (TextView) findViewById(R.id.header);
resultView.setText(text);
}
catch (IOException e) {
Log.d("File open error",""+e);
Toast.makeText(getApplicationContext(), "Error opening the file.", Toast.LENGTH_SHORT).show();
}
}
LogCat:
11-19 00:21:54.252: D/fcheck(5885): /storage/sdcard/mylibman.csv
11-19 00:21:54.272: D/File open error(5885): java.io.FileNotFoundException: /storage/sdcard/mylibman.csv: open failed: EACCES (Permission denied)

Make sure you have added the permission to read external storage in your manifest file.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I was experiencing the same problem and it can be easily removed by following either of these steps:
1. Install your app by using -g if installing on Android N and O versions.
2. Grant permission manually
Settings->apps->"app_name"->Permissions->Enable Switch
For Both steps 1 and 2, define uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" and uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" in AndroidManifest.xml
Like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="...">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- all permissions here -->
<application
...

Storage permission needs to be given by the user before accessing the functionality
Add Dependency:
dependencies:
permission_handler: ^5.0.1
Code Snippet:
var status = await Permission.storage.status;
if (status.isUndetermined) {
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.storage,
].request();
print(statuses[Permission.storage]); // it should print PermissionStatus.granted
}

Related

FileNotFoundException open failed: EACCES (Permission denied) on Android Emulator

Following is the code where activity is erroring out :
the error happens at line outputStream = new FileOutputStream(file);
public class MainActivity extends AppCompatActivity {
public void layoutToJPG(View v) {
View screen = v.getRootView();
// or I've also tried: View screen = new View(this);
screen.setDrawingCacheEnabled(true);
Bitmap b = screen.getDrawingCache();
Log.d("bitmap", b.toString());
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES);
File file = new File(path, "/sample.jpg");
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
b.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Toast.makeText(getApplicationContext(), "Saved to Gallery.", Toast.LENGTH_SHORT).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Error :
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Movies/sample.jpg: open failed: EACCES (Permission denied)
at libcore.io.IoBridge.open(IoBridge.java:496)
at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
The above is the error I am getting. I am running it on android emulator Pixel XL API 29
Does it require some special permissions to save file on the emulator.
As.
Android's permission system is one of the biggest security concern all
along since those permissions are asked for at install time. Once
installed, the application will be able to access all of things
granted without any user's acknowledgement what exactly application
does with the permission.
Android 6.0 Marshmallow introduces one of the largest changes to the
permissions model with the addition of runtime permissions, a new
permission model that replaces the existing install time permissions
model when you target API 23 and the app is running on an Android 6.0+
device
Try this code.
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
}
}
Add this in Menifest:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
You have to add permission. And, ask user to accept permission.
Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Request permission :
There's a library which you can use to ask for permission
Dexter.withContext(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
#Override public void onPermissionGranted(PermissionGrantedResponse response) {/* ... */}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}
#Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
Over than API level 23(maybe, I actually forgot) you have to request user to grant permission. That's why you have to add above source code.

Android manifest permissions not matching up with runtime permissions

bit of a strange question.
I'm trying to write some code that, for testing purposes, allows my test instance of Instrumentation to programmatically add Call Logs. It is simple but to do this, but it requires the android.permission.WRITE_CALL_LOG permission.
I've added this in my manifest
<uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
But when I use this code during runtime...
PackageManager instrumentationPM = instrumentationContext.getPackageManager();
PackageInfo info = instrumentationPM.getPackageInfo(PACKAGE_NAME,
PackageManager.GET_PERMISSIONS);
PermissionInfo[] permission_info = info.permissions;
The permission_info (aka info.permissions) array is null. Thus, during runtime no permissions are detected. Any clue what could be the issue here, and if this is at all relevant to my task of allowing my Instrumentation to add call logs?
Thanks a bunch.
This code will not return the <uses-permission> specified manifest file. Instead it will return the <permission>, which is system level permission.
I tried this code:
PackageManager instrumentationPM = getApplicationContext().getPackageManager();
PackageInfo info;
try {
info = instrumentationPM.getPackageInfo("com.example.testingproj",
PackageManager.GET_PERMISSIONS);
PermissionInfo[] permission_info = info.permissions;
if(permission_info!=null)
System.out.println(permission_info.length);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
And I have kept this permission in my manifest file:
<permission android:name="anypermission"></permission>
It gives me length = 1 in logcat.
I am not aware of getting all the <uses-permission> from manifest. But if you just want to check if there is a specific permission in manifest, you can try this:
if (instrumentationPM.checkPermission(permission.ACCESS_WIFI_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED) {
System.out.println("wifi state permission");
} else {
// do something
}

Source not found error

i am new android developer
when ever i run this code i get this error "Source not found." just when it reaches the
url.openStream()
any idea how to fix this?
try {
URL url = new URL("http://pollsdb.com/test.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
<uses-permission
android:name="android.permission.INTERNET" />
add that under your first manifest tag in your AndroidManifest.xml
I have the same problem too. But now, i have been solved this problem by reference http://developer.android.com/guide/components/processes-and-threads.html
about the thread use.
You need to create a worker thread to work for open the URL stream rather than using the main thread(UI thread).
Of course, you also need to add
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml

Android network errors connecting to an address

Snippet provided:
public void update(){
try {
Socket appSoc = new Socket( "XXX.XXX.XXX.X" ,XXXXX);
BufferedReader in = new BufferedReader(new
InputStreamReader(appSoc.getInputStream()));
for (int i = 0; i < 100; i++) {
String message = in.readLine();
add(message);}
}
catch (Exception e) {
add("ERROR" + e);
}
}
add(String text) adds text to a textview.
Using the domain name instead of the IP address says that the phone cannot find the domain, is this an android problem, because it runs fine on java on the desktop.
You are probably missing the Internet persmission in your manifest. Make sure it is located outside of the application tag, like this:
<manifest>
<application>
.
.
.
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
In your androidmanifest.xml, check to see if you have given proper internet permissions.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Unknown host Exception while calling method " twitter.getOAuthRequestToken()"

I am trying to integrate twitter api using library twitter4j-core-2.1.1-SNAPSHOT.jar. But i am getting error Unknown host Exception from 2 days. here is the part of code(index by .....(1)) that is generating Exception.
public String beginAuthorization() {
//showDialog("Authorization...........");
//new AuthorizationTask(this).execute("Authorize");
try {
if (null == currentRequestToken) {
Log.e("begin","i am here the line below is throwing excetion");
currentRequestToken = twitter.getOAuthRequestToken();............(1)
}
Log.e("beginAuthorization", currentRequestToken.getAuthorizationURL());
return currentRequestToken.getAuthorizationURL();
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
anyone have idea about this problem???
thank u in advance
Did you put permission in xml manifest?
Have you tried opening a browser in android and going to twitter.com?
Try to connect to any url from the code and see what happens.
This is what I'd forgotten to include in my AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />

Categories

Resources