0

I searched a lot online for solutions. But it seems the code used everywhere is still not excuting properly here. It might be a silly mistake but it has put me on edge for hours.

public class FileActivity extends Activity {

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

        Intent intent = getIntent();
        String filepath = intent.getStringExtra("KEY");

        TextView pane = findViewById(R.id.TextPanel);
        StringBuilder text = new StringBuilder();
        try {
           BufferedReader br = new BufferedReader(new FileReader(filepath));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            br.close();

        }
        catch (IOException e) {
            Toast.makeText(getApplicationContext(),filepath,Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        pane.setText(text);

    }
}

Question: I'm getting IOException. Though the file path is absolute.

Editted: Works.It needed specifying the permissions in the code.

used the following code FROM: Exception 'open failed: EACCES (Permission denied)' on Android

    // Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

1 Answers1

0

If you are sure that the filepath is correct, you will need to verify that there are file read and write permissions.write it on AndroidManifest.xml.

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

If the version number of the Android device is greater than or equal to 6, you need to get runtime permissions.