0

I'm making a small image downloading android app as a project. It takes URLs of two images, downloads them and displays them in ImageViews. Currently I'm using two separate ImageDownloaders i.e ImageDownloader1 and ImageDownloader2 both extending AsyncTask and instantiating their objects which then download the images. Both these classes are doing the same work but on different ImageViews. I want this to be done by making only one class like ImageDownloader and then making two instances to download images for each ImageView? Is there any way to do so then please suggest me?

Java Code:

public class MainActivity extends AppCompatActivity {

    Button image1Button,image2Button,resetButton;

    ImageView upperImageIV,lowerImageIV;

    ProgressBar upperImagePB,lowerImagePB;

    ImageDownloader1 image1;
    ImageDownloader2 image2;

    TextView textView1,textView2;

    boolean status1,status2;


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

        image1Button = (Button) findViewById(R.id.button1);
        image2Button = (Button) findViewById(R.id.button2);
        resetButton = (Button) findViewById(R.id.button3);

        upperImageIV = (ImageView) findViewById(R.id.imageView1);
        lowerImageIV = (ImageView) findViewById(R.id.imageView2);

        upperImagePB = (ProgressBar) findViewById(R.id.pbarUpperIMG);
        lowerImagePB = (ProgressBar) findViewById(R.id.pbarLLowerIMG);

        status1 = false;
        status2 = false;

        textView1 = (TextView) findViewById(R.id.editText1);
        textView2 = (TextView) findViewById(R.id.editText2);
    }

    public void downloadImage1(View view){
        upperImageIV.setVisibility(View.GONE);
        String url;
        url = textView1.getText().toString();
        if(!url.isEmpty()) {
            status1 = true;
            image1 = new ImageDownloader1();
            upperImagePB.setVisibility(View.VISIBLE);
            image1.execute(url);
        }
        else if(url.isEmpty()){
            upperImageIV.setVisibility(View.GONE);
        }
    }


    public class ImageDownloader1 extends AsyncTask<String,Void,Bitmap>{


        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                System.out.println("Content Type = "+connection.getContentType());
                if(connection.getContentType().contains("image")){
                    InputStream inputStream = connection.getInputStream();
                    return BitmapFactory.decodeStream(inputStream);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            while(image1.cancel(true) == false ){
                if (isCancelled())
                    break;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap){
            super.onPostExecute(bitmap);
            try {
                upperImageIV.setImageBitmap(image1.get());
                upperImagePB.setVisibility(View.GONE);
                upperImageIV.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    public void downloadImage2(View view){
        lowerImageIV.setVisibility(View.GONE);
        String url;
        url = textView2.getText().toString();
        if(!url.isEmpty()) {
            status2 = true;
            image2 = new ImageDownloader2();
            lowerImagePB.setVisibility(View.VISIBLE);
            image2.execute(url);
        }
        else if(url.isEmpty()){
            lowerImageIV.setVisibility(View.GONE);
        }
    }


    public class ImageDownloader2 extends AsyncTask<String,Void,Bitmap>{

        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                if(connection.getContentType().contains("image")){
                    InputStream inputStream = connection.getInputStream();
                    return BitmapFactory.decodeStream(inputStream);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            while(image2.cancel(true) == false ){
                if (isCancelled())
                    break;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap){
            super.onPostExecute(bitmap);
            try {
                lowerImageIV.setImageBitmap(image2.get());
                lowerImagePB.setVisibility(View.GONE);
                lowerImageIV.setVisibility(View.VISIBLE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    public void reset(View view){
        System.out.println("Reset Button pressed");
        upperImageIV.setVisibility(View.GONE);
        upperImagePB.setVisibility(View.GONE);

        lowerImageIV.setVisibility(View.GONE);
        lowerImagePB.setVisibility(View.GONE);

        if(status1 == true && status2 == false){
            image1.cancel(true);
        }
        else if(status1 == false && status2 == true){
            image2.cancel(true);
        }
        else if(status1 == true && status2 == true){
            image1.cancel(true);
            image2.cancel(true);
        }
        else {
        }
    }
}

XML code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    tools:context="com.example.syeddanish.downloadingimages.MainActivity">

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="URL here"
        android:textSize="24sp"/>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="URL here"
        android:textSize="24sp"
        android:layout_below="@id/editText1"/>

    <LinearLayout
        android:id="@+id/buttonsLinearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/editText2">

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="downloadImage1"
            android:text="Image 1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="downloadImage2"
            android:text="Image 2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="reset"
            android:text="Reset" />
    </LinearLayout>


    <LinearLayout
        android:id="@+id/imagesLinearLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/buttonsLinearLayout"
        android:orientation="vertical"
        android:weightSum="1">

        <RelativeLayout
            android:id="@+id/upperIMGRL"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_weight="0.5">

            <ProgressBar
                android:id="@+id/pbarUpperIMG"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:indeterminate="true"
                android:layout_centerInParent="true"
                android:visibility="gone" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone"/>

        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/lowerIMGRL"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_weight="0.5">

            <ProgressBar
                android:id="@+id/pbarLLowerIMG"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:indeterminate="true"
                android:layout_centerInParent="true"
                android:visibility="gone" />


            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="gone"/>


        </RelativeLayout>
    </LinearLayout>

</RelativeLayout>
gcourtet
  • 74
  • 2
  • 10
  • 1
    You can use glide library for the same https://github.com/bumptech/glide – buzzingsilently Jul 10 '18 at 12:48
  • AsyncTask instances can only be used one time. So, even if you manage to merge the other methods, there won't be any real benefit other than readability/maintenance. Check this one: https://stackoverflow.com/questions/6373826/execute-asynctask-several-times – Janaaaa Jul 10 '18 at 13:06

2 Answers2

0

With the Picasso library, you can do the following

Picasso.with(context).load(url).centerCrop().into(imageView)
prashant17
  • 1,520
  • 3
  • 14
  • 23
  • anyway of doing this job without using any library? – Syed Danish Jul 10 '18 at 12:57
  • Why would you want to do that? and for the record, use Glide – Shmuel Jul 10 '18 at 13:04
  • @Shmuel i am a student and making this app as a college project just for learning purposes to have a better understanding... hope you understood ? – Syed Danish Jul 10 '18 at 13:11
  • Yes, but this is a highly error prone task. For example, your current code will crash if you rotate the phone while the download is happening. Using Asynctask is error prone, and a very dangerous way to do background work on Android – Shmuel Jul 10 '18 at 13:16
  • If you want to learn hot to make http calls I'd suggest focusing on that and leaving bitmaps aside for the moment. – Shmuel Jul 10 '18 at 13:17
0
public void downloadImage1(View view){
    String url = textView1.getText().toString();
    if(!url.isEmpty()) {
        ImageDownloader imageDownloader1 = new ImageDownloader(upperImageIV, upperImagePB);
        imageDownloader1.execute(url);
    } else if(url.isEmpty()) {
        upperImageIV.setVisibility(View.GONE);
    }
}


public void downloadImage2(View view){
    String url = textView2.getText().toString();
    if(!url.isEmpty()) { 
        ImageDownloader imageDownloader2 = new ImageDownloader(lowerImageIV, lowerImagePB);
        imageDownloader2.execute(url);
    } else if(url.isEmpty()) {
        lowerImageIV.setVisibility(View.GONE);
    }
}

you can use AsyncTask like this

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
    ImageView upperImageIV;
    ProgressBar upperImagePB;

    ImageDownloader(ImageView upperImageIV, ProgressBar upperImagePB) {
        this.upperImageIV = upperImageIV;
        this.upperImagePB = upperImagePB;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        upperImageIV.setVisibility(View.GONE);
        upperImagePB.setVisibility(View.VISIBLE);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            System.out.println("Content Type = " + connection.getContentType());
            if (connection.getContentType().contains("image")) {
                InputStream inputStream = connection.getInputStream();
                return BitmapFactory.decodeStream(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        try {
            upperImageIV.setImageBitmap(bitmap);
            upperImagePB.setVisibility(View.GONE);
            upperImageIV.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Vinay Rathod
  • 1,262
  • 1
  • 10
  • 19
  • AsyncTask will be same for both but you have to define 2 times. like-> ImageDownloader imageDownloader1, imageDownloader2; – Vinay Rathod Jul 10 '18 at 13:12