Traveller
Traveller

Reputation: 157

getApplicationContext() cannot be resolved

I am trying to use a method to generate a bitmap from Layouts and save the bitmap to a file in the internal memory. However, the getApplicationContext() is not resolved.

Here is the code for the method

    private void generateAndSaveBitmap(View layout) {
//Generate bitmap
        layout.setDrawingCacheEnabled(true);
        layout.buildDrawingCache();
        Bitmap imageToSave = layout.getDrawingCache();

//Create a file and path
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        File fileName = new File(directory, "sharableImage.jpg");
        if (fileName.exists())
            fileName.delete();

//Compress and save bitmap under the mentioned fileName
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//    return directory.getAbsolutePath();
    }

Used some help from StackOverFlow codes to generate this method. Even after reading related queries on getApplicationContext(), I am unable to find the issue. Any help would be really appreciated

EDIT : Forgot to mention, that the method generateAndSaveBitmap(View layout) is defined inside a separate class

Regards

Upvotes: 2

Views: 792

Answers (3)

Joel
Joel

Reputation: 838

Have you tried:

File dir = getApplicationContext().getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE);

Now, from the image processing to the write of the file into the directory everything should be done off thread. Encapsulate it in an AsyncTask when possible and within it move generateAndSaveBitmap() method to it.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007624

Step #1: Delete ContextWrapper cw = new ContextWrapper(getApplicationContext());, as you do not need it.

Step #2: Replace cw.getDir("imageDir", Context.MODE_PRIVATE); with layout.getContext().getDir("imageDir", Context.MODE_PRIVATE);

Also, please move this disk I/O to a background thread.

Upvotes: 2

MrRobot9
MrRobot9

Reputation: 2684

Try ,

ContextWrapper cw = new ContextWrapper(getActivity());

incase it's a fragment.

Upvotes: 1

Related Questions