0

I'm hitting an URL and saving the returned image response in cache dir. If I try to save Bitmap from Returned response inputstream then I get correct Bitmap. Now after saving that response inputstream in cache and after fetching it I'm getting null Bitmap

Write inputStream to cache dir -

String root = mContext.getCacheDir().toString();
String path = root + "/tomorrow.jpg";

try {
  final File file = new File(path);

  final OutputStream output = new FileOutputStream(file);
  try {
    try {
      final byte[] buffer = new byte[1024];
      int ch;

      while ((ch = in.read(buffer)) != -1)
        output.write(buffer, 0, ch);

    } finally {
      output.close();
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}catch(Exception e){
  e.printStackTrace();
}

now I'm reading the file from cache dir -

FileInputStream fin = null;
try {
  fin = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
  e.printStackTrace();
}   
Bitmap bmp1 = BitmapFactory.decodeStream(fin);
kevz
  • 2,727
  • 14
  • 39
  • Your code looks good at first sight. If you have your phone rooted, try navigating to the cache folder, or, in the second piece of code, debug when you create "new File(path)", to see if file exists – webo80 Jul 01 '15 at 08:29
  • @ webo80: Yeah I have debug it and file exists. – kevz Jul 01 '15 at 08:31
  • check this line. String path = root + "/tomorrow.jpg";. Sometimes "/" becomes culprit. – Vilas Jul 01 '15 at 08:34
  • @EagleEye: Okay But I didn't got File not found exception. Is the file written correctly? – kevz Jul 01 '15 at 08:36
  • possible duplicate of [BitmapFactory.decodeStream returning null when options are set](http://stackoverflow.com/questions/2503628/bitmapfactory-decodestream-returning-null-when-options-are-set) – Maveňツ Jul 01 '15 at 08:38
  • Look at [this][1] to resolve issue. [1]: http://stackoverflow.com/questions/8296248/how-to-convert-outputstream-to-file – Dmitri Budiansky Jul 01 '15 at 09:07

1 Answers1

0

I'd like to thanks Dimitri Budiansky for guiding me. Fix as below-

//final byte[] buffer = new byte[1024];
//int ch;
//while ((ch = in.read(buffer)) != -1)
//output.write(buffer, 0, ch);

I commented above lines. Simply add below line.

bmp.compress(Bitmap.CompressFormat.PNG, 100, output);

for clarification u may check this Link

Community
  • 1
  • 1
kevz
  • 2,727
  • 14
  • 39