你的位置:首页 > 操作系统

[操作系统]ImageLoader简单使用


如图是效果图

                   

我从接口拉出来的数据然后将它们展示在界面上

1   先定义布局 我定义了MyGridView来展示商品

2   导入jar包universal-image-loader-1.8.6-with-sources 用来展示商品使用    在使用 ImageLoader应加入

     ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));不然会报

     java.lang.IllegalStateException: ImageLoader must be init with configuration before using字面意思是在使用前要初始化

3  定义适配器在getView中展示产品,不过我在展示的时候发现第一条数据总是在请求数据如下图,重复网址加载太慢也消耗服务器(也不知道是我哪里写错了第0条在重复请求 在网上我也没找到方法)

   所以我定义了一个 View arrView[]有数据的时候就不许再请求了

                        

4 开启子线程 在子线程中加载数据,在handler中解析数据并将其展示在界面上

主要的代码如下

布局代码

package com.demo.content;import android.content.Context;import android.util.AttributeSet;import android.widget.GridView;public class MyGridView extends GridView {  public MyGridView(Context context, AttributeSet attrs) {    super(context, attrs);  }  public MyGridView(Context context) {    super(context);  }  public MyGridView(Context context, AttributeSet attrs, int defStyle) {    super(context, attrs, defStyle);  }  @Override  public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,        MeasureSpec.AT_MOST);    super.onMeasure(widthMeasureSpec, expandSpec);  }}

View Code
<?  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical" >  <ScrollView    android:layout_width="match_parent"    android:layout_height="match_parent" >    <LinearLayout      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:background="#eee"      android:orientation="vertical" >      <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/app_name"        android:textColor="#000" />      <View        android:layout_width="match_parent"        android:layout_height="5dp"        android:background="@drawable/btn_normal" />      <com.demo.content.MyGridView        android:id="@+id/gg_mygridview"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:horizontalSpacing="7dp"        android:numColumns="2"        android:verticalSpacing="7dp" />    </LinearLayout>  </ScrollView></LinearLayout>

View Code
 1 package com.demo.activity; 2  3 import java.util.ArrayList; 4 import java.util.List; 5 import org.json.JSONArray; 6 import org.json.JSONObject; 7 import com.demo.content.MyGridView; 8 import com.demo.entity.Product; 9 import com.demo.pullrefresh.R; 10 import com.demo.util.GetThread; 11 import com.nostra13.universalimageloader.core.DisplayImageOptions; 12 import com.nostra13.universalimageloader.core.ImageLoader; 13 import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; 14 import com.nostra13.universalimageloader.core.assist.ImageScaleType; 15 import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; 16 import android.annotation.SuppressLint; 17 import android.app.Activity; 18 import android.graphics.Bitmap; 19 import android.os.Bundle; 20 import android.os.Handler; 21 import android.util.Log; 22 import android.view.View; 23 import android.view.ViewGroup; 24 import android.widget.BaseAdapter; 25 import android.widget.ImageView; 26 import android.widget.TextView; 27  28 public class MyMainActivity extends Activity { 29   // 定义的布局 30   private MyGridView myGridView; 31   private DisplayImageOptions options; 32   // 产品 33   private List<Product> products; 34   // 地址 35   private String url = "" 36       + "Product/GetProductsByProType/12000000/20"; 37  38   @Override 39   protected void onCreate(Bundle arg0) { 40     // TODO Auto-generated method stub 41     super.onCreate(arg0); 42     setContentView(R.layout.mymainactivity); 43     options = new DisplayImageOptions.Builder() 44         .showImageForEmptyUri(R.drawable.ic_empty) 45         // image连接地址为空时 46         .showImageOnFail(R.drawable.ic_error) 47         // image加载失败 48         .resetViewBeforeLoading(true).cacheOnDisc(true) 49         .imageScaleType(ImageScaleType.EXACTLY) 50         .bitmapConfig(Bitmap.Config.RGB_565) 51         .displayer(new FadeInBitmapDisplayer(300))// 设置用户加载图片task(这里是渐现图片显示) 52         .build(); 53     // 创建默认的ImageLoader的参数 不加回报java.lang.IllegalStateException 54     // 但不是每次用到ImageLoader都要加 55     ImageLoader.getInstance().init( 56         ImageLoaderConfiguration.createDefault(this)); 57     myGridView = (MyGridView) findViewById(R.id.gg_mygridview); 58     // 开启线程 59     new GetThread(url, handler).start(); 60   } 61  62   @SuppressLint("HandlerLeak") 63   private Handler handler = new Handler() { 64     public void handleMessage(android.os.Message msg) { 65       switch (msg.what) { 66       case GetThread.SUCCESS: 67         String jsonString = (String) msg.obj; 68         // 用JSON来解析数据 69         products = getJsonProducts(jsonString); 70         Log.d("jiejie", "DDDDDDD" + products); 71         // 创建个适配器 72         Adapter adapter = new Adapter(); 73         myGridView.setAdapter(adapter); 74         break; 75  76       default: 77         break; 78       } 79     }; 80   }; 81  82   protected List<Product> getJsonProducts(String jsonString) { 83     List<Product> resultTempList = new ArrayList<Product>(); 84     try { 85       JSONArray array = new JSONArray(jsonString); 86       for (int i = 0; i < array.length(); i++) { 87         Product temProductSimple = new Product(); 88         JSONObject object = array.getJSONObject(i); 89         temProductSimple.setId(object.getInt("id")); 90         temProductSimple.setProType(object.getInt("ProType")); 91         temProductSimple.setProOrder(object.getInt("ProOrder")); 92         temProductSimple.setAddTime(object.getString("AddTime")); 93         temProductSimple.setTitle(object.getString("Title")); 94         temProductSimple.setSmallPic(object.getString("SmallPic")); 95         temProductSimple.setPrice(object.getDouble("Price")); 96         temProductSimple.setSalePrice(object.getDouble("SalePrice")); 97         temProductSimple.setZhishubi(object.getString("Zhishubi")); 98         temProductSimple.setProNo(object.getString("ProNo")); 99         temProductSimple.setContens(object.getString("Contens"));100         temProductSimple.setBuyCount(object.getInt("BuyCount"));101         temProductSimple.setReadCount(object.getInt("ReadCount"));102         temProductSimple.setProImg(object.getString("ProImg"));103         temProductSimple.setShopFlag(object.getString("ShopFlag"));104         temProductSimple.setBrandId(object.getInt("BrandId"));105         temProductSimple.setStartTime(object.getString("StartTime"));106         if (object.get("Score") == null107             || object.get("Score").toString() == "null") {108           temProductSimple.setScore(0);109         } else {110 111           temProductSimple.setScore(object.getInt("Score"));112         }113 114         temProductSimple.setProductOrigin(object115             .getString("ProductOrigin"));116         if (object.get("kucun").toString() == "null") {117           temProductSimple.setKucun(0);118 119         } else {120           temProductSimple.setKucun(object.getInt("kucun"));121         }122 123         resultTempList.add(temProductSimple);124       }125     } catch (Exception e) {126       // TODO: handle exception127       e.printStackTrace();128       System.out.println(e.toString());129 130     }131     return resultTempList;132   }133 134   private View arrView[];135 136   private class Adapter extends BaseAdapter {137 138     @Override139     public int getCount() {140       // TODO Auto-generated method stub141       // return products.size();142       if (arrView == null) {143         arrView = new View[products.size()];144       }145       return products.size();146     }147 148     @Override149     public Object getItem(int arg0) {150       // TODO Auto-generated method stub151       return products.get(arg0);152     }153 154     @Override155     public long getItemId(int arg0) {156       // TODO Auto-generated method stub157       return arg0;158     }159 160     @Override161     public View getView(int arg0, View arg1, ViewGroup arg2) {162       if (arrView[arg0] == null) {163         Product info = products.get(arg0);164         Holder holder = null;165         if (null == arg1) {166           holder = new Holder();167 168           arg1 = View.inflate(MyMainActivity.this,169               R.layout.product_item, null);170           holder.product_cost = (TextView) arg1171               .findViewById(R.id.product_cost);172           holder.product_title = (TextView) arg1173               .findViewById(R.id.product_title);174           holder.product_img = (ImageView) arg1175               .findViewById(R.id.product_img);176           holder.buy_count = (TextView) arg1177               .findViewById(R.id.buy_count);178           arg1.setTag(holder);179         } else {180           holder = (Holder) arg1.getTag();181         }182         holder.product_cost.setText(products.get(arg0).getSalePrice()183             + "");184         holder.product_title.setText(products.get(arg0).getTitle());185         holder.buy_count.setText(products.get(arg0).getBuyCount() + "");186         String urlString = "http://**/UploadImages/ProductImages/"187             + products.get(arg0).getSmallPic();188 189         Log.d("jiejie", "dddddd___  " + arg0);190         Log.d("jiejie", "_________" + info.getTitle());191         Log.d("jiejie", "ProducteGridAdapter--" + urlString);192         ImageLoader.getInstance().displayImage(urlString,193             holder.product_img, options);194 195         arrView[arg0] = arg1;196       }197       return arrView[arg0];198       // return arg1;199 200     }201 202   }203 204   static class Holder {205     ImageView product_img;206     TextView product_title;207     TextView product_cost;208     TextView buy_count;209   }210 }

package com.demo.util;import java.io.IOException;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.os.Handler;import android.os.Message;import android.util.Log;public class GetThread extends Thread {  public static final int SUCCESS = 10, FAIL = -11;  private String url;  private Handler handler;  public GetThread(String url, Handler handler) {    this.url = url;    this.handler = handler;  }  @Override  public void run() {    // TODO Auto-generated method stub    super.run();    HttpClient httpClient = new DefaultHttpClient();    HttpGet httpGet = new HttpGet(url);    try {      HttpResponse httpResponse = httpClient.execute(httpGet);      Message msg = Message.obtain();      Log.v("asdf", httpResponse.getStatusLine().getStatusCode()          + "返回码   " + url);      if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {        String jsonString = EntityUtils.toString(httpResponse            .getEntity());        msg.what = SUCCESS;        msg.obj = jsonString;        handler.sendMessage(msg);      } else {        msg.what = FAIL;        handler.sendMessage(msg);      }    } catch (ClientProtocolException e) {      e.printStackTrace();    } catch (IOException e) {      e.printStackTrace();    }  }}