0

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.

Adhish
  • 134
  • 8
  • Show the logcat output. – K Neeraj Lal Jan 07 '17 at 07:24
  • @KNeerajLal 01-07 12:19:06.535 26907-26907/com.example.adhish.downloadretriveimage W/System.err: java.io.FileNotFoundException: 394968_538b_7: open failed: EROFS (Read-only file system) – Adhish Jan 07 '17 at 07:28
  • do you ask permissions in runtime for android 6? could you add logs and check path to file? i've noticed eхtra "/" in path. – Siarhei Jan 07 '17 at 07:33
  • at com.example.adhish.downloadretriveimage.ImageStorage.saveToSdCard(ImageStorage.java:46) – Adhish Jan 07 '17 at 07:33
  • @user5599807 No, not asking permission at run time. Also, where is extra "/" ? Thanks in advance. – Adhish Jan 07 '17 at 07:35
  • Check this line: 01-07 12:19:06.531 26907-26907/com.example.adhish.downloadretriveimage E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/.test_directory/394968_538b_7.jpg: open failed: ENOENT (No such file or directory) I dont think there is an extra "/" – Adhish Jan 07 '17 at 07:36
  • first of all for android 6(if your test with this version) you should ask permissions in runtime: for ex http://stackoverflow.com/questions/34150083/request-permission-at-runtime-for-android-marshmallow-6-0 – Siarhei Jan 07 '17 at 07:42
  • and for example here getImage("/"+imagename+".jpg") you call get image with "/" at the begining, but in your `getImage` you also adds "/" - "/.test_directory/" <- here. so, add logs in places where you merge path to check if its ok – Siarhei Jan 07 '17 at 07:44

1 Answers1

2

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

Adhish
  • 134
  • 8