Volley简单封装之Gson解析

这里设计了一个InternetHelper接口,然后实现了接口 VolleyHelper类,Activity调用 VolleyHelper类中的方法发起网络请求,然后通过继承抽象类VolleyCallBack来获得网络请求的结果,通知View视图层更新UI。至此,就将View视图和网络请求(数据处理)隔离开。

思路:

{“weathering”{“city”:”beijing”,”cityid”:”101190404”,”temp1”:”12C”,”temp2”:”16C”,
“weather”:”sunny”,”img1”:”n0.gif”,”img2”:”d1.gif”,”ptime”:”18:00”}}

例如需要解析上的Json数据。通过Volley请求网络数据,这里为了简单,只封装了GET请求(即从服务器获取一段Json字符串)。这里为了网络请求和Gson解析的代码能够复用,使用了泛型来定义VolleyCallBack抽象类,在继承该抽象类的时候传入了实际类型(JavaBean类型),对于不同形式的Json数据,我们只需要编写不同的JavaBean类,在继承时传入对应的类型即可,不需要去修改网络请求的代码。

InternetHelper接口:

public interface InternetHelper
{
    void getData(String url , VolleyCallBack callBack);
}

VolleyHelper实现类:

public class VolleyHelper implements InternetHelper
{
    private Gson gson;
    private RequestQueue requestQueue;

    public VolleyHelper(Context context)
    {
        gson = new Gson();
        requestQueue = Volley.newRequestQueue(context);
    }

    @Override
    public void getData(String url, final VolleyCallBack callBack)
    {
        StringRequest stringRequest = new StringRequest("http://192.168.1.100/" + url + ".json",
                new Response.Listener()
        {
            @Override
            public void onResponse(String response)
            {
                if (response != null && !response.equals(""))
                {
                    if (callBack.mType == String.class)
                    {
                        callBack.onSuccess(response , response);
                    }
                    else
                    {
                        try
                        {
                            Object object = gson.fromJson(response, callBack.mType);
                            callBack.onSuccess(response , object);
                        }
                        catch (JsonParseException e)
                        {
                            callBack.onError(response , e);
                        }
                    }
                }
                else
                {
                    callBack.onError(response , null);
                }
            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError volleyError)
            {
                callBack.onFailure(volleyError);
            }
        });
        requestQueue.add(stringRequest);
    }
}

VolleyCallBack回调抽象类:

public abstract class VolleyCallBack
{
    protected Type mType;

    static Type getSuperclassTypeParameter(Class subClass)
    {
        Type superclass = subClass.getGenericSuperclass();
        if (superclass instanceof Class)
        {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    }

    public VolleyCallBack()
    {
        mType = getSuperclassTypeParameter(getClass());
    }

    public abstract void onFailure(VolleyError error);
    public abstract void onSuccess(String response ,T t);
    public abstract void onError(String response , Exception e);
}

实体类Weather:

public class Weather
{
    public Weatherinfo weatherinfo;

    public Weatherinfo getWeatherinfo()
    {
        return weatherinfo;
    }

    public void setWeatherinfo(Weatherinfo weatherinfo)
    {
        this.weatherinfo = weatherinfo;
    }

    public static class Weatherinfo
    {
        public String city;
        public String cityid;
        public String temp1;
        public String temp2;
        public String weather;
        public String img1;
        public String img2;
        public String ptime;

        public String getCityid() {
            return cityid;
        }

        public void setCityid(String cityid) {
            this.cityid = cityid;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getTemp1() {
            return temp1;
        }

        public void setTemp1(String temp1) {
            this.temp1 = temp1;
        }

        public String getTemp2() {
            return temp2;
        }

        public void setTemp2(String temp2) {
            this.temp2 = temp2;
        }

        public String getWeather() {
            return weather;
        }

        public void setWeather(String weather) {
            this.weather = weather;
        }

        public String getImg1() {
            return img1;
        }

        public void setImg1(String img1) {
            this.img1 = img1;
        }

        public String getImg2() {
            return img2;
        }

        public void setImg2(String img2) {
            this.img2 = img2;
        }

        public String getPtime() {
            return ptime;
        }

        public void setPtime(String ptime) {
            this.ptime = ptime;
        }
    }
}

MainActivity类:

public class MainActivity extends Activity
{
    private InternetHelper weatherModel;
    private EditText input;
    private Button button;
    private TextView show;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        weatherModel = new VolleyHelper(this);
        init();
    }

    private void init()
    {
        input = (EditText) findViewById(R.id.input);
        button = (Button) findViewById(R.id.button);
        show = (TextView) findViewById(R.id.show);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                weatherModel.getData(input.getText().toString().trim() , new VolleyCallBack()
                {
                    @Override
                    public void onFailure(VolleyError error)
                    {
                        error.printStackTrace();
                    }

                    @Override
                    public void onSuccess(String response, Weather weatherInfo)
                    {
                        showData(weatherInfo);
                    }

                    @Override
                    public void onError(String response, Exception e)
                    {
                        Log.d("Error" , response);
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    private void showData(Weather weatherInfo)
    {
        Weather.Weatherinfo weatherMsg = weatherInfo.getWeatherinfo();
        StringBuilder result = new StringBuilder();
        result.append("city: " + weatherMsg.getCity() + "\n"
                + "city no: " + weatherMsg.getCityid() + "\n"
                + "temp1: " + weatherMsg.getTemp1() + "\n"
                + "temp2: " + weatherMsg.getTemp2() + "\n"
                + "weather: " + weatherMsg.getWeather() + "\n"
                + "img1: " + weatherMsg.getImg1() + "\n"
                + "img2: " + weatherMsg.getImg2() + "\n"
                + "ptime:" + weatherMsg.getPtime());

        show.setText(result.toString() , TextView.BufferType.NORMAL);
    }
}

主布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Input CityId"/>

        <Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="20sp"
            android:text="下载"/>

    LinearLayout>

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text=""/>

LinearLayout>

至此对Volley的简单封装完毕,如有不妥之处,欢迎大家批评指责谢谢!

你可能感兴趣的:(Java基础)