Android framework: using Imageloader and NetWorkImageView to load pictures

Keywords: Android network JSON Java

First, we import this framework into the project:

implementation 'com.mcxiaoke.volley:library:1.0.19'

Add network permissions to the Android manifest file:

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

Here is our homepage layout:
In this layout, we have made a button for all the functions of the Volley framework. After pressing the button, the result will be displayed under "display result". A ScrollView is used under the display result, and a Textview and Imageview are nested under the ScrollView to display the pictures and texts after we have successfully loaded them.

Here is the code of the homepage layout:

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
<Button
    android:id="@+id/get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Get request" / >
    <Button
        android:id="@+id/post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post request" / >
    <Button
        android:id="@+id/json"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text = "request JSON" / >
    <Button
        android:id="@+id/ImageRquest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ImageRquest load image" / >
    <Button
        android:id="@+id/ImageLoader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ImageLoader load image" / >
    <Button
        android:id="@+id/NetWorkImageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="NetWorkImageView load picture" / >
    <TextView
        android:text = "show results"
        android:textSize="20sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:visibility="gone"
        android:id="@+id/iv_volley"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/NetWork"
        android:visibility="gone"
        android:layout_width="200dp"
        android:layout_height="200dp" />
   <ScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <TextView
           android:id="@+id/tv_volley_result"
           android:layout_width="match_parent"
           android:layout_height="match_parent" />



   </ScrollView>
</LinearLayout>
 

BitmapCache.java code of picture cache class:

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader;

public class BitmapCache implements ImageLoader.ImageCache {

    private LruCache<String, Bitmap> mCache;

    public BitmapCache() {
        int maxSize = 10 * 1024 * 1024;// 10m
        mCache = new LruCache<String, Bitmap>(maxSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return mCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        mCache.put(url, bitmap);
    }


}

 

Main activity business logic implementation code:

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private Button get;
    private Button post;
    private Button json;
    private Button imagerequest;
    private  Button imageload;
    private  Button netWorkImageView;

    private ImageView iv;
    private NetworkImageView network;
    private TextView tv_volley_result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        initListener();

    }
    public void initview()//It's a good programming paradigm to write the logic of the control to be initialized here
    {

        get=findViewById(R.id.get);
        post=findViewById(R.id.post);
        json=findViewById(R.id.json);
        imagerequest=findViewById(R.id.ImageRquest);
        imageload=findViewById(R.id.ImageLoader);
        netWorkImageView=findViewById(R.id.NetWorkImageView);
        iv=findViewById(R.id.iv_volley);
        network=findViewById(R.id.NetWork);
        tv_volley_result=findViewById(R.id.tv_volley_result);



    }
    public void initListener()
    {
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Create a request queue
                RequestQueue requestQueue=Volley.newRequestQueue(MainActivity.this);
                //Create a request
                String url="http://gank.io/api/xiandu/category/wow";
                StringRequest stringRequest=new StringRequest(url, new Response.Listener<String>() {
                   //Callback after correctly accepting data
                    @Override
                    public void onResponse(String response) {
                    tv_volley_result.setText(response);
                    }
                }, new Response.ErrorListener() {//Listening callback after exception
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        tv_volley_result.setText("Loading error"+error);
                    }
                });
                //Add the created request to the request queue
                requestQueue.add(stringRequest);
            }
        });


        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1 Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 Create a post request
                String url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        tv_volley_result.setText(s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tv_volley_result.setText("request was aborted" + volleyError);
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {

                        Map<String, String> map = new HashMap<String, String>();
//                        map.put("value1","param1");

                        return map;
                    }
                };

                // 3 take post Request added to queue
                requestQueue.add(stringRequest);




            }
        });

        json.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
// 1 Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 Create a request
                String url = "http://gank.io/api/xiandu/category/wow";
                //JsonArrayRequest jsonObjectRequest2=......
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        tv_volley_result.setText(jsonObject.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        tv_volley_result.setText("request was aborted" + volleyError);
                    }
                });

                // 3 Add the created request to the request queue
                requestQueue.add(jsonObjectRequest);

//After this step, you can use our json Parsed

            }
        });

        imagerequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1 Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // 2 Request to create a picture
                String url = "http://img5.mtime.cn/mg/2016/10/11/160347.30270341.jpg";
                ImageRequest imageRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                        // Picture received correctly
                        iv.setVisibility(View.VISIBLE);//Make picture visible
                        iv.setImageBitmap(bitmap);//Pictures to be accepted Bitmap Object passed into our imageview Among
                    }
                }, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                    //The first two parameters of 0 and 0 represent the maximum width and height of the loaded image, and the following parameters Bitmap.Config.RGB_565 Indicates the quality of the picture
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        iv.setImageResource(R.drawable.test);
                    }
                });

                // 3 Add request to request queue
                requestQueue.add(imageRequest);

            }
        });


        imageload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);


                ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
                   @Override
                   public Bitmap getBitmap(String s) {
                      return null;
                   }

                   @Override
                  public void putBitmap(String s, Bitmap bitmap) {

                  }
               });


                // Loading pictures
                String url = "http://img5.mtime.cn/mg/2016/10/11/160347.30270341.jpg";
                iv.setVisibility(View.VISIBLE);
                ImageLoader.ImageListener imageListener = imageLoader.getImageListener(iv, R.drawable.test, R.drawable.test);
                //The last two parameters of the above code respectively represent the default image and the image after loading failure
                imageLoader.get(url, imageListener);
            }
        });

        netWorkImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Let the control display
                network.setVisibility(View.VISIBLE);

                // Create a request queue
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                // Create a Imageloader
                ImageLoader imageLoader = new ImageLoader(requestQueue, new BitmapCache());

                // Default and exception picture settings
                network.setDefaultImageResId(R.drawable.test);
                network.setErrorImageResId(R.drawable.test);

                // Loading pictures
                String url = "http://img5.mtime.cn/mg/2016/10/11/160347.30270341.jpg";
                network.setImageUrl(url, imageLoader);


            }
        });

    }
}

Understand.

Posted by ams53 on Sat, 09 Nov 2019 09:47:42 -0800