Shant11
Shant11

Reputation: 29

Caching on Android

I have an app which gets data from Parse.com and uses in 2 sections, one in a listView and second in a grid view.

So I want to cache this data(Strings,bitmaps),to work offline, whenever the device won't have internet so it loads from cache. And whenever my app closed and opened again, it should update the cached data if there is internet. During the update if I have the same data in my cache it shouldn't create it again, it has to only create the new ones and update the views.

What is the best way to do this in android ?. Thanks.

Upvotes: 0

Views: 244

Answers (3)

sud
sud

Reputation: 505

try this code it will help-

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-

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.open_pic_layout);
    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);

Upvotes: 0

Zahidul Islam
Zahidul Islam

Reputation: 3190

For String / Text :

  1. If your data amount is not so much , you can use SharedPreference

  2. If you have huge Data you should use SQlite

For Image :

  1. Picasso -> http://square.github.io/picasso/

  2. Universal Image Loader -> https://github.com/nostra13/Android-Universal-Image-Loader

Upvotes: 0

santoXme
santoXme

Reputation: 802

For caching a data coming form Webservice

for Get a data u can use Volley or retrofit after getting an data you can set it to user desired attributes for caching the data both library giving the caching option for saving an data try to use that library.

Upvotes: 1

Related Questions