I'm new to the Android World. I will starting saying I know i'm writing bad code, my purpose is "make it work first and then make it nicer", well at least for really tiny project. I'm using the library Picasso to download a picture. Well, it works! But now i want to take that ImageView and put it in a Bitmap object so i can save it.
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
ImageView iview = new ImageView(cc);
Picasso.with(cc).load(myUrl).into(iview);
I didn't understand the concept of the context yet so i just made Picasso works. As a global variable i declared:
Context cc;
I inizialied in the function onCreate:
cc = this;
That's because i was calling Picasso inside a class that extends AsyncTask and just writing with(this) wasn't working. I can feel it is such a bad practice! Anyway it is working but when i try:
Bitmap bmx = iview.getDrawingCache();
bmx gets null.
i tried bulding the cache:
iview.buildDrawingCache();
bmx = iview.getDrawingCache();
iview.destroyDrawingCache();
Using a function i found:
public static Bitmap loadBitmapFromView(View v)
{
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return b;
}
Going through BitmapDrawable:
BitmapDrawable drawable = (BitmapDrawable) iview.getDrawable();
Bitmap bitmap = drawable.getBitmap();
and this:
Bitmap bitmap = ((BitmapDrawable)iview.getDrawable()).getBitmap();
Openly enabling the cache:
iview.setDrawingCacheEnabled(true);
Bitmap bmx = iview.getDrawingCache();
No luck. In the end i throw Picasso away for this guy: DownloadManager.
I would like to know what i was getting wrong, also, if you guys have spare time, i'd be happy to listen to some good practice! Like stop using AsyncTask for downloading an image like i did and start using an intentservice.
This is my full bad code:
> package com.cmandracchia.template;
>
> import android.app.Activity; import android.app.DownloadManager;
> import android.content.Context; import android.content.Intent; import
> android.content.pm.PackageManager; import android.graphics.Bitmap;
> import android.graphics.Canvas; import
> android.graphics.drawable.BitmapDrawable; import android.net.Uri;
> import android.os.AsyncTask; import android.os.Build; import
> android.os.Environment; import android.support.v4.app.ActivityCompat;
> import android.support.v4.content.ContextCompat; import
> android.support.v7.app.AppCompatActivity; import android.os.Bundle;
> import android.view.View; import android.view.ViewGroup; import
> android.widget.ImageView; import android.widget.Toast;
>
> import com.squareup.picasso.Picasso;
>
> import java.io.BufferedReader; import java.io.File; import
> java.io.FileOutputStream; import java.io.IOException; import
> java.io.InputStreamReader; import java.net.URL; import
> java.util.regex.Matcher; import java.util.regex.Pattern;
>
> public class DisplayMessageActivity extends AppCompatActivity {
> String myUrl;
> Context cc;
> Bitmap bmx;
>
> @Override
> protected void onCreate(Bundle savedInstanceState)
> {
> super.onCreate(savedInstanceState);
> setContentView(R.layout.activity_display_message);
>
> Intent intent = getIntent();
> String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
>
> cc = this;
> if(Build.VERSION.SDK_INT >= 23)
> {
> if(checkPermission())
> {
> // Code for above or equal 23 API Oriented Device
> // Create a common Method for both
> }
> else
> {
> requestPermission();
> }
> }
> else
> {
> // Code for Below 23 API Oriented Device
> // Create a common Method for both
> }
>
> RetrievePage rp = new RetrievePage();
> rp.execute(message);
> }
>
> public class RetrievePage extends AsyncTask<String, Void, String>
> {
> protected String doInBackground(String... urls)
> {
> StringBuilder sb = new StringBuilder();
> try
> {
> URL url = new URL(urls[0]);
> BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
> String str;
> while ((str = in.readLine()) != null)
> {
> sb.append(str);
> }
> in.close();
> }
> catch(IOException e)
> {
> e.printStackTrace();
> }
> return sb.toString();
> }
>
> @Override
> protected void onPostExecute(String ss)
> {
> // here there is some manipulation that you don't see because i deleted for keeping the code short
> myUrl = ss;
>
> ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
> ImageView iview = new ImageView(cc);
> Picasso.with(cc).load(myUrl).into(iview);
>
> layout.addView(iview);
> iview.buildDrawingCache();
> bmx = iview.getDrawingCache();
> iview.destroyDrawingCache();
>
>
> if(bmx == null)
> {System.out.println("bmx is null");}
> else
> {System.out.println("bmx is not null");}
>
> try
> {
> File image = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
> "Example.jpg");
> FileOutputStream out = new FileOutputStream(image);
>
> bmx.compress(Bitmap.CompressFormat.JPEG, 100, out);
> out.flush();
> out.close();
> System.out.println("it's over");
> }
> catch(Exception e)
> {
> e.printStackTrace();
> }
> }
> }
>
> private boolean checkPermission()
> {
> int result = ContextCompat.checkSelfPermission(cc, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
> if (result == PackageManager.PERMISSION_GRANTED)
> {
> return true;
> }
> else
> {
> return false;
> }
> }
>
> private void requestPermission()
> {
> if (ActivityCompat.shouldShowRequestPermissionRationale(cce, android.Manifest.permission.WRITE_EXTERNAL_STORAGE))
> {
> Toast.makeText(cc, "Write External Storage permission allows us to do store images. Please allow this permission in App
> Settings.", Toast.LENGTH_LONG).show();
> } else {
> ActivityCompat.requestPermissions(cce, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
> }
> }
>
> @Override
> public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
> {
> switch (requestCode)
> {
> case 1:
> if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
> {
> System.out.println("Permission Granted, Now you can use local drive .");
> }
> else
> {
> System.out.println("Permission Denied, You cannot use local drive .");
> }
> break;
> }
> }
>
> }
Thanks!!!