I have an app who has to download some generated images (PNG).
I tried the standard approach ImageDownloader extends AsyncTask, doInBackground() retrieves the image and the onPostExecute() will try to save it to internal image. 
(Part of the) code is below:
public class HandleImages extends AppCompatActivity {
String filename = "";
public boolean saveImageToInternalStorage(Bitmap image) {
    try {
        FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
        image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
public Bitmap retrieveImage(String url){
    ImageDownloader task = new ImageDownloader();
    Bitmap image =  Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
    try {
        image = task.execute(url).get();
    } catch (InterruptedException e) {
        MainActivity.debb("InterruptedException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
        e.printStackTrace();
    } catch (ExecutionException e) {
        MainActivity.debb("ExecutionException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
        e.printStackTrace();
    }
    return image;
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        try {
            String[] filenames = urls[0].split("/");
            filename = filenames[filenames.length-1] + ".jpg";
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            return BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if (bitmap != null)
            saveImageToInternalStorage(bitmap);
    }
}
}
and the error that I get is: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference. 
It seems that the FileOutputStream fos = openFileOutput(..) fails, but have no idea why. 
Also tried to prepend a path (sdCard.getPath() + "/" +) to the filename. As expected it did not make any difference. 
Images are ok, I can see them in the browser. Also tried with uploaded images - instead of the generated ones, same result.
This is pretty odd, does anyone have any idea?
Thanks!
 
    