OkHttpClient()打开方法显示错误

时间:2016-09-28 19:20:00

标签: android okhttp

我的代码显示错误,我不知道究竟是什么导致它,这一行:HttpURLConnection con = client.open(new URL(imageUrl));

package www.com.easyrecepee;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.util.LruCache;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

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

/**
 * Created by Joshua on 9/28/2016.
 */
public class PlacesListAdapter extends ArrayAdapter<Places> {
    private Context context;
    private List<Places> placesList;

    private LruCache<String, Bitmap> imageCache;

    // create a field of the RequestQueue to be used by volley
    // so it persist through out the life time of the class
    //private RequestQueue queue;

    public OkHttpClient client = new OkHttpClient();

    public PlacesListAdapter(Context context, int resources, List<Places> objects) {
        super(context, resources, objects);
        this.context = context;
        this.placesList = objects;

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        imageCache = new LruCache<>(cacheSize);

        // instantiate the queue field and passing current context
        // so its associated with proper activity
        //queue = Volley.newRequestQueue(context);
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater =
                (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.item_vicinity, parent, false);

        // Display places name in the TextView widget
        final Places places = placesList.get(position);
        TextView placeTitle = (TextView) view.findViewById(R.id.place_title);
        TextView vicinity = (TextView) view.findViewById(R.id.vicinity);
        //TextView openNow = (TextView)view.findViewById(R.id.openNow);

        placeTitle.setText(places.getName());
        vicinity.setText(places.getVicinity());
//        if(places.isOpenNow()){
//            openNow.setText("Open");
//        } else {
//            openNow.setText("Closed");
//        }

        //Display place photo in ImageView widget
        Bitmap bitmap = imageCache.get(places.getId());
        // for volley
        final ImageView image = (ImageView) view.findViewById(R.id.place_image);
        if (bitmap != null) {
            //For the volley, this commented line of code is refactored so it can
            // be called outside this block
            //ImageView image = (ImageView) view.findViewById(R.id.place_image);
            image.setImageBitmap(places.getBitmap());
        } else {
            // Retrieves image url
            //String imageUrl = places.getIconUrl();
            // declare instance of image request
            /*ImageRequest request = new ImageRequest(imageUrl,
                    new Response.Listener<Bitmap>(){
                        @Override
                        public void onResponse(Bitmap arg0) {
                            image.setImageBitmap(arg0);
                            imageCache.put(places.getId(), arg0);
                        }
                    },
                    80, 80,
                    Bitmap.Config.ARGB_8888,

                    new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError arg0) {
                            Log.d("PlacesAdapter", arg0.getMessage());
                        }
                    }
                    );

            //adding request to queue
            queue.add(request);*/

            /*
                The line of code below is used by the ImageLoader AsyncTask
                Uncomment if using AsyncTask
             */
            PlaceAndView container = new PlaceAndView();
            container.places = places;
            container.view = view;

            ImageLoader loader = new ImageLoader();
            loader.execute(container);

        }


        return view;
    }

    // Used with AsyncTask, since am using Volley, no need

    class PlaceAndView {
        public Places places;
        public View view;
        public Bitmap bitmap;
    }

    // Using the Volley Method does what the AsyncTask do
    // Uncomment to use

    private class ImageLoader extends AsyncTask<PlaceAndView, Void, PlaceAndView> {
        @Override
        protected PlaceAndView doInBackground(PlaceAndView... params) {

            PlaceAndView container = params[0];
            Places places = container.places;

            try {
                String imageUrl = places.getIconUrl();

                // Using OkHttpClient to fetch images
                HttpURLConnection con = client.open(new URL(imageUrl));
                //HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                InputStream in = con.getInputStream();

                }

                //InputStream in = (InputStream) new URL(imageUrl).getContent();
                Bitmap bitmap = BitmapFactory.decodeStream(in);
                places.setBitmap(bitmap);
                in.close();
                container.bitmap = bitmap;
                return container;
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(PlaceAndView result) {
            ImageView image = (ImageView) result.view.findViewById(R.id.place_image);
            image.setImageBitmap(result.bitmap);
            // saves image for future use
            //result.places.setBitmap(result.bitmap);

            imageCache.put(result.places.getId(), result.bitmap);

        }
    }
}

如何让open()方法停止显示错误,这是在代码中创建错误的唯一方法,所以我觉得应该有一些其他方法或更新的方法来处理open方法。

1 个答案:

答案 0 :(得分:0)

我想你在这里复制相同的代码Fatal Exception: Exception in do in background method (AsyncTask)

所以我想你可以根据需要修改这段代码,看看你的代码是否运行。

@Override
protected FlowerAndView doInBackground(FlowerAndView... params) {

    FlowerAndView container = params[0];
    Flower flower = container.flower;

    try {
        String imageUrl = MainActivity.PHOTOS_BASE_URL + flower.getPhoto();
        InputStream in = (InputStream) new URL(imageUrl).getContent();
        Bitmap bitmap = BitmapFactory.decodeStream(in);
        flower.setBitmap(bitmap);
        in.close();
        container.bitmap = bitmap;
        return container;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

<强> [EDITED]

但是使用OkHttpClient,您的代码应该是这样的。

    @Override
    protected PlaceAndView doInBackground(PlaceAndView... params) {

        PlaceAndView container = params[0];
        Places places = container.places;

        try {
            String imageUrl = places.getIconUrl();

            // Using OkHttpClient to fetch images
            // HttpURLConnection con = client.open(new URL(imageUrl));
            //HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //InputStream in = con.getInputStream();
            Request req = new Request.Build()
                   .url(imageUrl)
                   .build();
            Response response = client.newCall(req).execute();
            InputStream in = response.body().byteStream();

            //InputStream in = (InputStream) new URL(imageUrl).getContent();
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            places.setBitmap(bitmap);
            in.close();
            container.bitmap = bitmap;
            return container;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

PS:请记住,有很多库可以下载图片glidepicasso等,以节省时间和代码。

如何使用Glide的示例,请注意您需要的代码少。

public class PlacesListAdapter extends ArrayAdapter<Places> {

    private LayoutInflater mInflater;


    public PlacesListAdapter(Context context, int resources, List<Places> objects) {
        super(context, resources, objects);
        mInflater = LayoutInflater.from(context);
    }

    class Holder {
        TextView placeTitle;
        TextView vicinity;
        ImageView placeImage;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;
        Holder holder;
        if (view == null) {

            view = mInflater.inflate(R.layout.item_vicinity, parent, false);

            holder = new Holder();
            holder.placeTitle = (TextView) view.findViewById(R.id.place_title);
            holder.vicinity (TextView) view.findViewById(R.id.vicinity);
            holder.placeImage = (ImageView) view.findViewById(R.id.place_image);

            view.setTag(holder);
        } else {
            holder = view.getTag();
        }


        // Display places name in the TextView widget
        final Places places = getItem(position);
        holder.placeTitle.setText(places.getName());
        holder.vicinity.setText(places.getVicinity());

        Glide
           .with(parent.getContext())
           .load(places.getIconUrl())
           .into(holder.placeImage);

        return view;
    }


}