Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, Saving and loading a bitmap in cache from different activities

I have i bitmap that needs to show in a new activity, so i cahe it and in the opened activity i try to load it but i get a nullPointerException. Here i save the image :

File cacheDir = getBaseContext().getCacheDir();
File f = new File(cacheDir, "pic");

try {
    FileOutputStream out = new FileOutputStream(
            f);
    pic.compress(
            Bitmap.CompressFormat.JPEG,
            100, out);
    out.flush();
    out.close();

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Intent intent = new Intent(
        AndroidActivity.this,
        OpenPictureActivity.class);
startActivity(intent);

and then in the new activity i try to open it :

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    File cacheDir = getBaseContext().getCacheDir();
    File f = new File(cacheDir, "pic");     
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(fis);

    ImageView viewBitmap = (ImageView) findViewById(R.id.icon2);
    viewBitmap.setImageBitmap(bitmap);
    setContentView(R.layout.open_pic_layout);
like image 310
user924941 Avatar asked Sep 24 '11 16:09

user924941


People also ask

What is bitmap caching?

Caching bitmap means that images and other bitmap resources are locally stored on the client computer for reusing them later. This way, the remote server or PC doesn't send images twice reducing the amout of data sent and saving your bandwidth usage.

How do you save cache on Android?

Android also provides a means to cache some data rather than store it permanently. You can cache data in either internal storage or external storage. Cache files may be deleted by the Android system when the device is low on space. To get the internal storage cache directory, use the getCacheDir() method.

How do you handle bitmaps in Android?

For most cases, we recommend that you use the Glide library to fetch, decode, and display bitmaps in your app. Glide abstracts out most of the complexity in handling these and other tasks related to working with bitmaps and other images on Android.


1 Answers

Just check your code:

ImageView viewBitmap = (ImageView) findViewById(R.id.icon2);
viewBitmap.setImageBitmap(bitmap);
setContentView(R.layout.open_pic_layout);

You have written findViewById() before setting Content View. Its wrong.

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.open_pic_layout);

  // do your operations here
  }
like image 144
Paresh Mayani Avatar answered Oct 30 '22 07:10

Paresh Mayani