Stan
Stan

Reputation: 6571

What could be alternative without need to keep context?

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?

Upvotes: 0

Views: 295

Answers (2)

deRonbrown
deRonbrown

Reputation: 645

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();
    }
}

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93726

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.

Upvotes: 0

Related Questions