Kahn Kah Kahn Kah - 5 months ago 24
Android Question

Android: Saving image on Android Phone from ImageView in a Fragment

So I have this fragment here that looks like:

enter image description here

What I'm trying to do is save the image on my phone (in the file downloads or gallery or ... ).

I have scanned Stackoverflow and the internet but my code is not working. I do not get an error, but I also don't get a picture stored on my phone. What could be my problem? The code I used comes from Stackoverflow.

public class MainFragment extends Fragment {
Button download;
ImageView DownloadImage;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


View v = inflater.inflate(R.layout.fragment_main, container, false);

DownloadImage = (ImageView) v.findViewById(R.id.imageToDownload);
download = (Button) v.findViewById(R.id.buttonDownloadImage);


Picasso.with(getActivity()).load("http://192.168.200.2/android_login_api/images/actie.png").into(DownloadImage);

download.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveImageLocally(DownloadImage);

}
});
return v;
}


private String saveImageLocally(ImageView iv) {
iv.buildDrawingCache();

Bitmap bmp = iv.getDrawingCache();

File storageLoc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); //context.getExternalFilesDir(null);

File file = new File(storageLoc, "test" + ".jpg");

try{
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();

scanFile(getActivity(), Uri.fromFile(file));

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return "true";
}

private static void scanFile(Context context, Uri imageUri){
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(imageUri);
context.sendBroadcast(scanIntent);

}

}

Answer

Do you have this permissions in Manifest.xml, because i tried your code and logged its working perfect :

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

Actually i tried your code and logged , the result : open failed: EACCES (Permission denied)

Try to look logcats like :

catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.v("bitmap","not found , "+e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        Log.v("bitmap","io ex , "+e.getMessage());
    }
Comments