Search code examples
androidpicasso

Android | Where to store images fetched at run-time from server


I am developing an Android app (Similar to shopping cart) which tends to fetch images (of cart catalog items) and store it in local directory for later use. (Due to limited network connectivity, I can't load images from server every-time shopping cart opens)

I found a way to download images from server using Google's picasso library (this link).

Where I am stuck is that I don't know what path to specify to store the images. I intend to dedicate a directory for that, but not sure where to create that path (android app directory structure post installation?).

I wish to store it in the res directory in my app, but would that be the same once the application gets installed? If yes then how can I find that path at run-time?

If you have a better approach to do this, I am open to suggestions.

Thank You.


Solution

  • In android you need to store them either as

    Internal Storage if you want to Store private data on the device memory.

    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();
    

    External Storage if you want to Store public data on the shared external storage.

    /* Checks if external storage is available for read and write */
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }
    
    /* Checks if external storage is available to at least read */
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state) ||
            Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            return true;
        }
        return false;
    }
    

    Use this function to store data on external:

        private void SaveImage(Bitmap finalBitmap) {
    
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/saved_images");    
        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image-"+ n +".jpg";
        File file = new File (myDir, fname);
        if (file.exists ())
          file.delete (); 
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
    
        } catch (Exception e) {
             e.printStackTrace();
        }
    }
    

    Dont forget to add the permissions. Sources : Android saving file to external storage https://developer.android.com/guide/topics/data/data-storage.html#filesInternal