Android的Fragment从okhttp获取数据

最近开发某个Android项目:DateListThingsAnalyse-Android,其中用到了Fragment来展示数据,获取数据一直被卡住了。最后在StackOverflow找到了相关解决办法。建议还是去clone一下我的项目查看实际代码去体会用法。

okhttp工具类

public class Singleton {
    private static Singleton INSTANCE = null;
    private Singleton() {};

    OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    public static Singleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
        return(INSTANCE);
    }

    public void doGetRequest(String url, final HttpResponseCallBack responseCallBack) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String strResponse = response.body().string();
                Log.v("getStream-strResponse",strResponse);
                try {
                    responseCallBack.getResponse(strResponse);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void doPostRequest(String url,String json, final HttpResponseCallBack responseCallBack) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String strResponse = response.body().string();
                Log.v("getStream-strResponse",strResponse);
                try {
                    responseCallBack.getResponse(strResponse);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

接口

package info.emperinter.DateListThingsAnalyseAndroid.API;

import org.json.JSONException;

public interface HttpResponseCallBack {
    void getResponse(String response) throws JSONException;
}

fragment

  • 如下是主要调用的地方,完整代码建议去查看整个项目代码。
try {
            Singleton.getInstance().doGetRequest(url, new HttpResponseCallBack() {
                @Override
                public void getResponse(String response) throws JSONException {
                    reqGet = response;
                    if(reqGet.contains("things_id")){
                        JSONArray userJson = new JSONArray(reqGet);
                        for (int i = 0;i < userJson.length();i++){
                            key = userJson.getJSONObject(i).getString("key");
                            if(KeyMap.containsKey(key)){
                                KeyMap.put(key,KeyMap.get(key) + 1);
                            }else if(!key.contains("nan") && key != ""){
                                KeyMap.put(key,1);
                            }
                        }

                        TagChart(view,KeyMap);

                    }else if(reqGet.contains("[]")){
                        Toast.makeText(getActivity().getBaseContext(),"username or password is wrong !",Toast.LENGTH_SHORT).show();
                    }else if(reqGet.contains("HTTP")){
                        Toast.makeText(getActivity().getBaseContext()," Cleartext HTTP traffic to not permitted",Toast.LENGTH_SHORT).show();
                    }else {
                        Toast.makeText(getActivity().getBaseContext(),"Please Input Your Information !"+reqGet,Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *