Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image is not getting download and saved in local storage using Picasso Library

I am trying to download images by using Picasso library and then save the image into local storage. Error: After the log "inside getImage" from method getImage() the logcat is displaying the log from onBitmapFailed(Drawable errorDrawable). I have only been able to find examples converting the target reference into a strong reference. However, this does not solve the problem.

Below is a snippet of the code I've written to download and save the image:

import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

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


public class DownloadImage {

    Context mContext;
    Target target;

    public void getImage(Context context) {
        mContext = context;
        String path = "/data/data/ops.com.imagefetcher/images";
        Picasso.with(context)
                .load("http://blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png")
                .into(getTarget(path));
        Log.e("Download Image: ", "inside  getImage()");
    }

    private Target getTarget(final String path) {
//        ContextWrapper cw = new ContextWrapper(mContext);
//        final File directory = cw.getDir(path, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir

        target = new Target() {
            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("Download Image: ", "inside  run");
                        final File myImageFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + path, "example");
                        FileOutputStream ostream = null;
                        try {
                            Log.e("Download Image: ", "inside  try");
                            myImageFile.createNewFile();
                            ostream = new FileOutputStream(myImageFile);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                            ostream.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                ostream.close();
                                Log.e("Download Image: ", "inside  finally");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Log.e("Download Image: ", "image saved to >>>" + myImageFile.getAbsolutePath());
                    }
                }).start();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                Log.e("Download Image: ", "error!");

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        return target;
    }
}

The manifest file is:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ops.com.imagefetcher">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"
            android:enabled="true"
            android:exported="true"/>
    </application>

</manifest>

LogCat output: This is what i am getting in logs, Nothing else.

 01-09 19:56:26.964 30021-30021/ops.com.imagefetcher E/Download Image:: before target
01-09 19:56:26.964 30021-30021/ops.com.imagefetcher E/Download Image:: inside  getImage()
01-09 19:56:26.964 30021-30021/ops.com.imagefetcher E/MyService:: below getImage()
01-09 19:56:27.884 30021-30111/ops.com.imagefetcher D/dalvikvm: GC_FOR_ALLOC freed 314K, 12% free 3109K/3500K, paused 2ms, total 2ms
like image 253
sak Avatar asked Nov 08 '22 12:11

sak


1 Answers

Use the default DownloadManager to download the image

  private long downloadFile( String uRl, String desc, String name) {

    File direct = new File(Environment.getExternalStorageDirectory()
            + "/MyFolderName");

    if (!direct.exists()) {
        direct.mkdirs();
    }

    DownloadManager mgr = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);

    Uri downloadUri = Uri.parse(uRl);
    DownloadManager.Request request = new DownloadManager.Request(
            downloadUri);

    request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false).setTitle(name)
            .setDescription(desc)
            .setVisibleInDownloadsUi(true)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalFilesDir(context,"/MyFolderName", name + ".jpg")
            .setDestinationInExternalPublicDir("/MyFolderName", name + ".jpg");

     return mgr.enqueue(request);
}

Simply pass the url to this method. It'll do all required process

like image 176
AMAN SINGH Avatar answered Nov 14 '22 22:11

AMAN SINGH