-1

I've been trying to read and write to a text file from Android studio, and keep getting the "Permission denied" exception. I've read through the different posts,and still can't seem to solve it.

My code:

public void buttonSave(View view) {
    //File directory = new File(path);
    File directoryFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "");
    directoryFile.mkdirs();
    File file = new File(directoryFile, "savefile.txt");
    try {
        file.createNewFile();
    } catch (IOException e) {;}

    eV = (EditText)findViewById(R.id.editText_box);
    String[] editTextValue = eV.getText().toString().split(" ");

    Save(file, editTextValue);
}

public void Save(File file, String[] data){
    FileOutputStream foe = null;
    Toast.makeText(getApplicationContext(), Integer.toString(data.length), Toast.LENGTH_SHORT).show();

    try {
        foe = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
    }
    try {
        for (int i=0; i<data.length; i++){
            foe.write(data[i].getBytes());
            if (i<data.length){
                foe.write("\n".getBytes());
            }
        }
    } catch (IOException e) {};
    try {
        foe.close();
    } catch (IOException e) {};
}

And my manifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="home.learningapp2">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Any suggestions? It doesn't work on the emulator or when I run it on my phone.

Andy
  • 6,869
  • 2
  • 31
  • 24
  • you need run time permission ! read this https://developer.android.com/training/permissions/requesting.html – iamkdblue Apr 12 '18 at 14:18

2 Answers2

1

First you should get permissions in manifest file :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then you should get run time permission, add this methods to your activity :

private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE);
    int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
    return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}

private void requestPermission() {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 100:
            if (grantResults.length > 0) {
                boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                if (locationAccepted && cameraAccepted)
                    Toast.makeText(this, "Permission Granted, Now you can access", Toast.LENGTH_LONG).show();
                else {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            showMessageOKCancel("You need to allow access to both the permissions",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                        100);
                                            }
                                        }
                                    });
                            return;
                        }
                    }

                }
            }


            break;
    }
}


private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(MainActivity.this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

and then change your onCreate() method :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (checkPermission()) {
        Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "Please request permission.", Toast.LENGTH_LONG).show();
    }

    if (!checkPermission()) {
        requestPermission();
    } else {
        Toast.makeText(this, "Permission already granted.", Toast.LENGTH_LONG).show();
    }

}

also you can see this example in kotlin : Runtime permission example

Ali reza
  • 23
  • 8
0

I'm using for this code in different permisson but I think they are same try this:

 public void Save(File file, String[] data){

          public void Save(File file, String[] data){

        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
        }else {

        FileOutputStream foe = null;
        Toast.makeText(getApplicationContext(), Integer.toString(data.length), Toast.LENGTH_SHORT).show();

        try {
            foe = new FileOutputStream(file);
        }catch (FileNotFoundException e) {Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();}

        try {

            for (int i=0; i<data.length; i++){
                foe.write(data[i].getBytes());
                if (i<data.length){
                    foe.write("\n".getBytes());
                }

            }
        }catch (IOException e) {};

        try {
            foe.close();
        } catch (IOException e) {};
    } }
Baran KARABOGA
  • 80
  • 1
  • 11