Android says it cannot solve getExternalFilesDir (null) 'method

I am using Android Studio to try to write a file to external storage.

Other posts recommended that I do this with getExternalFilesDir(null) , but I get the Cannot resolve method 'getExternalFilesDir(null)' message Cannot resolve method 'getExternalFilesDir(null)' .

  public void makeFile() { try { String storageState = Environment.getExternalStorageState(); if (storageState.equals(Environment.MEDIA_MOUNTED)) { File file = new File(getExternalFilesDir(null), "outputFile.txt"); FileOutputStream fos = new FileOutputStream(file); String text = "Hello, world!"; fos.write(text.getBytes()); fos.close(); } } catch (Exception e) { e.printStackTrace(); } } 

I could not find a way to get rid of this error. Thanks in advance for any solutions to the problem.

+5
source share
1 answer

getExternalFilesDir() is a method that requires Context . In the Activity class, you just need to call getExternalFilesDir() , but in other classes you need to call it using Context .

how

  • getActivity().getExternalFilesDir(null) in fragment

  • context.getExternalFilesDir(null) in classes where you pass Context as a parameter

  • YourActivity.this.getExternalFilesDir(null); when called in the inner class Activity

+14
source

Source: https://habr.com/ru/post/1240015/


All Articles