Download and display pictures from the network

Keywords: Android Java network xml

Get the network pictures through get request -- mainly for future reference and making a note

Task requirements:

1. Create a new layout file, and add two controls: Button and ImageView to the layout file

2. Create a new GetPictThread to implement the Runnable interface

(1) define a handler to transfer data to the main thread

(2) define a method with parameters, including path and handler

(3) complete the network picture acquisition (sub thread) in the run() method

3. Complete picture display in MainActivity (i.e. main thread)

 

xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get network pictures"/>

    <ImageView
        android:id="@+id/image_download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp"
        />

</LinearLayout>

 

 

java code:

package com.example.jiaho.handleproject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class ImageDownLoadActivity extends AppCompatActivity implements View.OnClickListener{

    public static final int DOWNLOAD_CODE = 10001;
    public static final int DOWNLOAD_FAIL = 300;
    public static final int CONNECT_TIMEOUT = 2000;
    private ImageView image_download;
    private Button btn_download;

    private Handler handler;

    private String path="https://img2.mukewang.com/5adfee7f0001cbb906000338-240-135.jpg";

    private int fileLength;

    private Bitmap mBitmap;

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

        //Initialize control
        initialView();

        btn_download.setOnClickListener(this);

        //Receive messages from child threads
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case DOWNLOAD_CODE:
                        /*
                        * Update UI
                        * Extract the bitmap in the message and set the ImageView
                        * */
                        Bitmap bitmap=(Bitmap) msg.obj;
                        if (bitmap!=null){
                            image_download.setImageBitmap(bitmap);//disPlay image
                        }
                        break;
                    case DOWNLOAD_FAIL:
                        Toast.makeText(ImageDownLoadActivity.this,"Download failed",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };

    }

    //Initialize control
    public void initialView(){
        btn_download=findViewById(R.id.btn_download);
        image_download=findViewById(R.id.image_download);
    }

    //Button click
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_download:
                //Open thread
                new Thread(new GetPictThread(handler,path)).start();
                break;
        }
    }


    //Custom GetPictThread class implements Runnable class
    public class GetPictThread implements Runnable{
        //Define handler and path
        public Handler handler;
        public String path;

        //Parametric structure
        public GetPictThread(Handler handler, String path) {
            this.handler = handler;
            this.path = path;
        }

        //Image download in run method
        @Override
        public void run() {
            //Request to Get network picture through Get method
            try {
                URL url=new URL(path);
                HttpURLConnection connection=(HttpURLConnection) url.openConnection();

                //Set request method
                connection.setRequestMethod("GET");
                //Set timeout
                connection.setConnectTimeout(30*1000);
                //Initiate connection
                connection.connect();

                //Get status code
                int requestCode=connection.getResponseCode();
                System.out.println(requestCode);

                if (requestCode==HttpURLConnection.HTTP_OK){
                    /*
                    * 1.Get file length
                    * 2.By buffering the input stream
                    * 3.Convert input stream to byte array
                    * 4.Convert byte array to bitmap
                    * */
                    fileLength=connection.getContentLength();

                    InputStream is=new BufferedInputStream(connection.getInputStream());

                    //Get byte array
                    byte[] arr=streamToArr(is);

                    //Convert byte array to bitmap
                    mBitmap= BitmapFactory.decodeByteArray(arr,0,arr.length);

                    /*
                    * Send message after download
                    * Notify main thread, update UI
                    * */
                    Message message=Message.obtain();
                    message.what=DOWNLOAD_CODE;
                    message.obj=mBitmap;
                    handler.sendMessage(message);

                }else {
                    Log.e("TAG", "run:error "+requestCode);
                }
            }catch (MalformedURLException e){
                e.printStackTrace();
                handler.sendEmptyMessage(DOWNLOAD_FAIL);
            }catch (IOException e){
                e.printStackTrace();
                handler.sendEmptyMessage(DOWNLOAD_FAIL);
            }
        }
    }

    //Convert input stream to byte array
    public byte[] streamToArr(InputStream inputStream){

        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024];
            int len;

            while ((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }

            //Close output stream
            baos.close();
            //Close input stream
            inputStream.close();
            //Return byte array
            return baos.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
            //If failed, return null
            return null;
        }
    }

}

 

 

An essential step to add permissions to the network:

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

 

 

Then you can start to download the pictures!

Posted by zenag on Fri, 27 Dec 2019 11:06:50 -0800