2016-09-28 177 views
0

我的代碼顯示錯誤,我不知道是什麼實際上導致它,這一行:HttpURLConnection con = client.open(new URL(imageUrl));OkHttpClient()打開方法顯示錯誤

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()方法停止顯示錯誤,這就是在代碼中創建錯誤的唯一方法,所以我覺得應該有一些其他方法或辦理開放式方法的新途徑。

+2

究竟是什麼錯誤? – Michael

+0

你說這是「顯示錯誤」。你的意思是代碼運行時出現錯誤(運行時錯誤),IDE中出現錯誤(編譯時錯誤)或其他內容? –

+1

OkHttpClient類沒有方法'open(...)'。 https://github.com/square/okhttp/blob/6e236ce3b80f21369dc544f0e1053ff71be8689b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java – betorcs

回答

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; 
} 

將帖子

但使用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; 
    } 


} 
+0

謝謝大家,如果你向下滾動到代碼中的AsyncTask方法,那麼你應該看到這一行://使用OkHttpClient獲取圖像 HttpURLConnection con = client.open(new URL(imageUrl));這就是我的錯誤來自哪裏。 –

+0

Okhttp不需要AsyncTask,儘管 –

+1

很酷!感謝betorcs,謝謝大家,最後讓它工作。所以快樂的窺視。對於請求req = new Request.Build();它實際上是:Request req = new Request.Builder();它可以幫助任何其他人。豎起大拇指Betorcs。 –