0

In a class which is not Activity and thus doesn't have a Context I need to store a file like:

public static void saveAvatar(String fileName, Bitmap avatar) {
    if (avatar == null)
        return;

    FileOutputStream fos;
    try {
        fos = context.openFileOutput(fileName + ".jpg", Context.MODE_PRIVATE);
        avatar.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

To make it work I need to keep a context in a class because I'm calling this method from another class which doesn't have a context either. Is there a way to do it without context like using ContentResolver or something like?

nbanic
  • 1,270
  • 1
  • 8
  • 11
Stan
  • 6,511
  • 8
  • 55
  • 87
  • Just pass in your context as a parameter. – dymmeh Mar 20 '14 at 20:32
  • @dymmeh Never pass a context to anything which is static - memory leak heaven! @Stan - read the documentation for `getApplicationContext`. http://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-and – Simon Mar 20 '14 at 20:35

2 Answers2

1

You can use the Context of your application class. Use the following template to be able to use your application class as a singleton:

private static MyApplication instance;

public static MyApplication getInstance() {
  return instance;
}

@Override
public void onCreate() {
  super.onCreate();
  instance = this;
}

Now, you can change your code to the following:

public static void saveAvatar(String fileName, Bitmap avatar) {
    if (avatar == null)
        return;

    FileOutputStream fos;
    try {
        fos = MyApplication.getInstance().openFileOutput(fileName + ".jpg", Context.MODE_PRIVATE);
        avatar.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
deRonbrown
  • 635
  • 7
  • 14
0

A couple of ways.

1)Pass in a context in the constructor

2)Pass in the file or the directory in the constructor and just create the file using the standard java apis.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • If this is the only reason the Context is needed, then obtaining the directory path using it once and passing *that* around as in your (2) sounds like a better idea. – Chris Stratton Mar 20 '14 at 20:55