未将位图添加到onPostExecute的List对象

时间:2019-03-16 00:55:11

标签: java android

我正在尝试从网站上下载所有img标签,将它们作为位图存储在列表中,然后在GridView中显示这些位图,但是,在我的图片的异步调用中,这些图片未添加到清单。它们将被添加到DownloadImageTask的列表中。

Here is my code

package com.example.homework18;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class MainActivity extends AppCompatActivity {
    ImageView img;
    final private int REQUEST_INTERNET = 123;
    final List<Bitmap> images = new ArrayList<Bitmap>();

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, REQUEST_INTERNET);
        } else{
            downloadSomething();
        }

        final ImageSwitcher imgSwitcher = findViewById(R.id.imgSwitcher);

        imgSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imgView = new ImageView(MainActivity.this);
                imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                imgView.setBackgroundColor(Color.GREEN);
                ImageSwitcher.LayoutParams imgLayoutParams = new ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
                imgView.setLayoutParams(imgLayoutParams);
                return imgView;

            }
        });

        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
                imgSwitcher.setImageResource(images.indexOf(position));

                Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();

            }
        });


    }
    private void downloadSomething() {

        //String imgurl = "http://2.bp.blogspot.com/-us_u2PBLSOI/UqgPMh7ovjI/AAAAAAAACdI/ujdyGregs6Y/s1600/amazing-butterfly-hd-image.jpg";
        String texturl = "https://www.csuohio.edu/";

        //new DownloadImageTask().execute(imgurl);
        //new DownloadTextTask().execute(texturl);
       new DownloadTextTask().execute(texturl);

    }
    private void getWebsite(String html) {
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("img");
        int num_of_imgs = imgs.size();
        String img[] = new String[num_of_imgs];
        int i = 0;
        for(Element x : imgs){
            String url = x.absUrl("src");
            img[i] = url;
            i++;
        }

        for(String url : img){
            //Bitmap image = DownloadImage(url);
            //images.add(image);
            new DownloadImageTask().execute(url);
        }

    }
    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap = null;
        InputStream in = download(URL);
        if(in != null) {
            bitmap = BitmapFactory.decodeStream(in);
            try {
                in.close();
            } catch (IOException e1) {
                Log.d("NetworkingActivity", e1.getLocalizedMessage());
            }
        }
        return bitmap;
    }

    private class DownloadTextTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return DownloadText(urls[0]);
        }
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
            getWebsite(result);
        }
    }
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        protected Bitmap doInBackground(String... urls) {
            return DownloadImage(urls[0]);
        }
        protected void onPostExecute(Bitmap result) {
            //ImageView img = (ImageView) findViewById(R.id.imageView);
            images.add(result);
            //img.setImageBitmap(result);
        }
    }

    private String DownloadText(String URL)
    {
        int BUFFER_SIZE = 2000;
        InputStream in = download(URL);
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];
        try {
            while ((charRead = isr.read(inputBuffer))>0) {
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            Log.d("Networking", e.getLocalizedMessage());
            return "";
        }
        return str;
    }
    private InputStream download(String URL) {
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            return in;
        } catch (IOException e1) {
            Log.d("NetworkingActivity", e1.getLocalizedMessage());
        }
        return null;
    }
    private InputStream OpenHttpConnection(String urlString) throws IOException
    {
        InputStream in = null;   int response = -1;  URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }  catch (Exception ex)
        {
            Log.d("Networking", " " +ex.getLocalizedMessage());  throw new IOException("Error connecting");
        }
        return in;
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        public ImageAdapter(Context c) { context = c; }
        //---returns the number of images---
        public int getCount() { return images.size();  }
        //---returns the item---
        public Object getItem(int position) { return position; }
        //---returns the ID of an item---
        public long getItemId(int position) { return position; }
        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(images.indexOf(position));
            return imageView;
        }
    }
}

如果您有任何建议,请告诉我!我知道可以找到这些图像,但是List数据结构有问题。

0 个答案:

没有答案