Volley之自定义GsonRequest

原创
2015/11/21 17:36
阅读数 342

第一步:导入volley 和gson的jar

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

第三步: static 的单例类,用于管理volley中的方法

public class MySingleton {
          private static MySingleton mInstance;
          private static Context context;
          private RequestQueue mRequestQueue;
          public static synchronized MySingleton getInstance(Context context) {
                     if (mInstance == null) {
                               mInstance = new MySingleton(context);
                     }
                      return mInstance;
            }

           private MySingleton(Context mcontext) {
                   context = mcontext;
                    mRequestQueue = getRequestQueue();
           }

            public RequestQueue getRequestQueue() {
                      if (mRequestQueue == null) {// ApplicationContext确保volley的队列在app运行中都存在
                      mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
                     }
                    return mRequestQueue;
              }


               public <T> void addToRequestQueue(Request<T> req) {
                     getRequestQueue().add(req);
                  }
}

第四步: 自定义Gson请求
public class GsonRequest<T> extends Request<T> {

             private final Listener<T> mListener;
             private Gson mGson;
             private Class<T> mClass;

            public GsonRequest(String url, Class<T> mClass, Listener<T> mListener,ErrorListener listener) {
                 this(Method.GET, url, mClass, mListener, listener);
             }

            public GsonRequest(int method, String url, Class<T> mClass,
                                       Listener<T> mListener, ErrorListener listener) {
                            super(method, url, listener);
                            mGson = new Gson();
                            this.mClass = mClass;
                            this.mListener = mListener;
           }

          @Override//将服务器响应的数据解析出来,然后Gson的fromJson方法将数据组装成对象,在工作线程中运行
          protected Response<T> parseNetworkResponse(NetworkResponse response) {
                     try {
                                  String jsonString = new String(response.data,
                                  HttpHeaderParser.parseCharset(response.headers));
                                   return Response.success(mGson.fromJson(jsonString, mClass),
                                                            HttpHeaderParser.parseCacheHeaders(response));
                      } catch (UnsupportedEncodingException e) {
                                 return Response.error(new ParseError(e)); 
                      }
 
            }
            //最终的数据进行回调给ui线程
           protected void deliverResponse(T response) {
                     mListener.onResponse(response);
           }

}

案例:

url :"http://www.weather.com.cn/data/sk/101010100.html"
return result:
                    {"weatherinfo": {"city":"北京","cityid":"101010100","temp":"19",
                             "WD":"南风","WS":"2级","SD":"43%", "WSE":"2","time":"19:45","isRadar":"1",
                              "Radar":"JC_RADAR_AZ9010_JB"}
                     }
第五步:定义实体类和引用类(根据实际返回结果写)
/**
 * 实体类的引用类
 *
 * @author  Administrator
 *
 */
public class Entity_Quote {
            private Entity  weatherinfo;

            public Entity getEntity() {
               return entity;
              }

            public void setEntity(Entity entity) {
                   this.entity = entity;
            }
}

/**
 * 实体类
 * @author  Administrator
 *
 */
public class Entity {
             private String city;
             private String temp;
             private String time;
             public String getCity() {
                 return city;
             }
             public void setCity(String city) {
                 this.city = city;
             }
             public String getTemp() {
                  return temp;
             }
             public void setTemp(String temp) {
                   this.temp = temp;
             }
            public String getTime() {
                  return time;
             }
            public void setTime(String time) {
                 this.time = time;
             }
   
}

第六步:activity中使用
public class MainActivity extends Activity {
               TextView tv;
               public String url=  "http://www.weather.com.cn/data/sk/101010100.html";
               public  final static String  TAG=MainActivity.class.getSimpleName();
                @Override
               protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                         tv = (TextView) findViewById(R.id.mian_tv);
 
                       sendRequest();
              }


            //volley适合数据量小且通信频繁,但是不可用数据大的操作,如流媒体,下载文件(downloadManager)等。
           private void sendRequest() {
                 GsonRequest<Entity_Quote>  gsonRequest= 

                                   new GsonRequest<Entity_Quote>(url,Entity_Quote.class,new   Listener<Entity_Quote>() {
                                                                @Override
                                        public void onResponse(Entity_Quote quote) {//返回一个引用类,通过引用类拿到实体类
                                                        Entity entity=quote.getEntity();
                                                        tv.setText(entity.getCity()+""+entity.getTemp()+""+entity.getTime());
    
                                        }
                                    }, new ErrorListener() {
                                      @Override
                                        public void onErrorResponse(VolleyError error) {
                                            Log.e("TAG", error.getMessage(), error);
                                    }
                                });
                      gsonRequest.setTag(TAG);//添加标记,便于取消
                      MySingleton.getInstance(this).addToRequestQueue(gsonRequest);
                      //可以在任何线程中添加一个请求,    但是响应结果都是返回在主线程中
            }
 
           @Override
            protected void onStop() {
                   RequestQueue mQueue=MySingleton.getInstance(this.getApplicationContext()).getRequestQueue();
 
                   if(mQueue!=null){
                    mQueue.cancelAll(TAG);//取消用TAG标记的request
                   }
                     super.onStop();
            }
}

展开阅读全文
打赏
0
3 收藏
分享
加载中
更多评论
打赏
0 评论
3 收藏
0
分享
返回顶部
顶部