接外包,有相关需求的可以联系我:Telegram | Email

Android的Fragment从okhttp获取数据

该文章创建(更新)于02/14/2022,请注意文章的时效性!

最近开发某个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();
        }


👇 Share | 分享 👇


要不赞赏一下?

微信
支付宝
PayPal
Bitcoin

版权声明 | Copyright

除非特别说明,本博客所有作品均采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明转自-
https://www.emperinter.info/2022/02/14/how-to-get-data-from-okhttp-in-fragment/


要不聊聊?

我相信你准备留下的内容是经过思考的!【勾选防爬虫,未勾选无法留言】

*

*



微信公众号

👉 NewsLetter ❤️ 邮箱订阅 👈

优惠码


阿里云国际版20美元
Vultr10美元
搬瓦工 | Bandwagon应该有折扣吧?
域名 | namesiloemperinter(1美元)