Download image and display from local hidden folder in Android

1k views Asked by At

I am trying to download image from internet and store it locally in some hidden folder where the images are not visible to the user in his/her gallery.

Here is my code to do so. The image is getting displayed only when the device is connected to internet. In other words the image is not getting saved in the device and it is throwing an exception.

Here is my ImageStorage class:

package com.example.adhish.downloadretriveimage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by appy-20 on 6/1/17.
 */

public class ImageStorage {


    public static String saveToSdCard(Bitmap bitmap, String filename) {

        String stored = null;

        File sdcard = Environment.getExternalStorageDirectory() ;

        File folder = new File(sdcard.getAbsoluteFile(), ".test_directory");//the dot makes this directory hidden to the user
        folder.mkdir();
        File file = new File(folder.getAbsoluteFile(), filename + ".jpg") ;
        if (file.exists())
            return stored ;

        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            stored = "success";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stored;
    }

    public static File getImage(String imagename) {

        File mediaImage = null;
        try {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root);
            if (!myDir.exists())
                return null;

            mediaImage = new File(myDir.getPath() + "/.test_directory/"+imagename);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mediaImage;
    }
    public static boolean checkifImageExists(String imagename)
    {
        Bitmap b = null ;
        File file = ImageStorage.getImage("/"+imagename+".jpg");
        String path = file.getAbsolutePath();

        if (path != null)
            b = BitmapFactory.decodeFile(path);

        if(b == null ||  b.equals(""))
        {
            return false ;
        }
        return true ;
    }
}

and here is my MainActivity.java:

package com.example.adhish.downloadretriveimage;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {


    ImageView imageView;
    Bitmap b;
    String imagename;
    String imgurl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView=(ImageView)findViewById(R.id.imageView);

        imagename="394968_538b_7";
        imgurl="https://udemy-images.udemy.com/course/750x422/394968_538b_7.jpg";

        if(ImageStorage.checkifImageExists(imagename))
        {
            File file = ImageStorage.getImage("/"+imagename+".jpg");

//            File file = ImageStorage.getImage("https://udemy-images.udemy.com/course/750x422/394968_538b_7.jpg");

            String path = file.getAbsolutePath();
            if (path != null){
                b = BitmapFactory.decodeFile(path);
                imageView.setImageBitmap(b);
            }
        } else {
            new GetImages(imgurl, imageView, imagename).execute() ;
        }
    }

    private class GetImages extends AsyncTask<Object, Object, Object> {
        private String requestUrl, imagename_;
        private ImageView view;
        private Bitmap bitmap;
        private FileOutputStream fos;

        private GetImages(String requestUrl, ImageView view, String _imagename_) {
            this.requestUrl = requestUrl;
            this.view = view;
            this.imagename_ = _imagename_;
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                URL url = new URL(requestUrl);
                URLConnection conn = url.openConnection();
                bitmap = BitmapFactory.decodeStream(conn.getInputStream());
            } catch (Exception ex) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            if (!ImageStorage.checkifImageExists(imagename_)) {
                view.setImageBitmap(bitmap);
                ImageStorage.saveToSdCard(bitmap, imagename_);
            }
        }
    }
}

I have already given the external storage read write permission in my Manifest.

1

There are 1 answers

0
Adhish On BEST ANSWER

I found the solution to this problem. I am storing the images in SQLite database and here is the code for it:

https://github.com/adhishlal/URL_to_DB_Image