Volley、handler、Json、RefreshLayout

网络包——Volley
volley是安卓网络通信库,可以处理网络请求异步加载小图片,少量缓存。不适合数据量比较多的网络通信。
具体步骤
1.创建RequestQueue对象:把队列实例化。
        RequestQueuere questqueue=Volley.newRequest(context);
2.创建JsonObjectRequest对象(StringRequest,ImageRequest)
JsonObjectRequest jsonobjectrequest=new JsonObjectRequest("网址",null,Response.Listener ,ErrorResponse);
3.将JsonRequest对象放入RequestQueue中,表示提交了信息。
requestqueue.add(JsonObjectRequest);
(记得添加网络权限!)


handler---负责线程中的消息循环
在写正确信息和错误信息时,要在函数中给出相关信息。正确时:获取信息返回json数据
错误时:显示网络异常信息
由于不能在子线程中向外部传递数据  
//CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
因此要使用handler,它是子线程向主线程传递消息的"车",Message是"货物",主线程是”收货点“,子线程是”出货点“

private Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {//}
用volley实现获取网络天气数据
主线程
private Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
        switch(msg.what){
            case 1:
                try {
                    JSONObject jsonObject=new JSONObject(msg.obj.toString());//定义json对象

                    JSONObject weatherinfo=jsonObject.getJSONObject("weatherinfo");//获取天气数据
                    String name=weatherinfo.getString("city");
                    city_name.setText(name);
                    String temp=weatherinfo.getString("temp1")+"~"+weatherinfo.getString("temp2");
                    city_temp.setText(temp);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                swipeRefreshLayout.setRefreshing(false);
                break;
            case 0:
                Toast.makeText(MainActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                break;
        }
        }
    };
 子线程
 public void onResponse(JSONObject jsonObject) {
            Message message=mhandler.obtainMessage();//获取

                String json = null;
                try {
                    json =new String(jsonObject.toString().getBytes("ISO-8859-1"),"utf-8");//数据解析乱码解决
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                };
                message.what=1;
                message.obj=json;
                mhandler.sendMessage(message);}
    
    
 public void onErrorResponse(VolleyError volleyError) {
        mhandler.sendEmptyMessage(0);
            }



你可能感兴趣的:(Android)