drivetrdr
drivetrdr

Reputation: 19

How to use getExternalFilesDir() not in Activity

How to use getExternalFilesDir() not in Activity? Here is my class:

public class Storage2 {

  public String deviceRootDir;
  public String sdRootDir;

  public Storage2() {
    String replacePattern = "(.+?)/Android.*";
    if (Integer.valueOf(android.os.Build.VERSION.SDK) > 18) {
      File[] f = getExternalFilesDirs(null);
      this.deviceRootDir = f[0].getPath().replaceAll(replacePattern, "$1");
      if (f[1] != null) this.sdRootDir = f[1].getPath().replaceAll(replacePattern, "$1");
    } else {
      this.deviceRootDir = getExternalFilesDir(null).getPath().replaceAll(replacePattern, "$1");
    }
  }
}

I try to New Context().getExternalFilesDirs(null) and other things but nothing works.

Upvotes: 0

Views: 1148

Answers (2)

PPartisan
PPartisan

Reputation: 8231

Quite simply, either pass a Context as an argument, or use dependency injection to supply a Context to your Storage2 class:

public (static?) Storage2(Context ctx) {
    //...
    File[] f = ctx.getExternalFilesDirs(null);
    //...
    this.deviceRootDir = ctx.getExternalFilesDir(null).getPath().replaceAll(replacePattern, "$1");
    }
  }

Or

public class Storage2 {

  public String deviceRootDir;
  public String sdRootDir;

  private final Context context;

  public Storage2(Context context) {
      this.context = context;
  }

  public Storage2() {
    //...
    File[] f = context.getExternalFilesDirs(null);
    //...
    this.deviceRootDir = context.getExternalFilesDir(null).getPath().replaceAll(replacePattern, "$1");
    }
  }
}

You could also use a global Application Context, but that's a little bit of a hack:

public class App extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = this;
    }

    public static Context get() {
        return context;
    }
}

Add App to your AndroidManifest.xml and you could then use App.get().getExternalFiles(null)...

Upvotes: 1

drivetrdr
drivetrdr

Reputation: 19

Thanks PPartisan, I make changes due your advice

public class Storage2 {

  public String deviceRootDir;
  public String sdRootDir;

  public Storage2(Context passedContext) {
    String replacePattern = "(.+?)/Android.*";
    if (Integer.valueOf(android.os.Build.VERSION.SDK) > 18) {
      File[] f = passedContext.getExternalFilesDirs(null);
      this.deviceRootDir = f[0].getPath().replaceAll(replacePattern, "$1");
      if (f[1] != null) this.sdRootDir = f[1].getPath().replaceAll(replacePattern, "$1");
    } else {
      this.deviceRootDir = passedContext.getExternalFilesDir(null).getPath().replaceAll(replacePattern, "$1");
    }
  }
}

Upvotes: 0

Related Questions