Home » Java » java – Android onPause method not working as desired-Exceptionshub

java – Android onPause method not working as desired-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

So I have an application that collects some data in a String called dataFull. This string needs to be saved in a file whenever the onPause() method is called. Normally, the same code in onCreate() method works fine.

public void onPause(){
super.onPause();
File dir = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
File file = new File(dir, "example.txt");

try {
        FileWriter fileWriter = new FileWriter(file);
        fileWriter.append(datafull);
    } catch (IOException e) {
        Toast.makeText(MainActivity.this,
                "Sorry! File not written", Toast.LENGTH_LONG).show();
        //Handle exception
    }
}

Every time exception is being called. The same code in onCreate() writes a file to Downloads. What am I doing wrong? All permissions in XML have been given.

How to&Answers: