在放置在ViewCreated()之外的Runnable中使用Glide

时间:2018-01-09 13:06:06

标签: java android

我正在使用Glide函数从服务器响应中加载图像。下面的代码在onViewCreated函数中正常工作,但我想建立一个Handler来验证互联网连接,并且我将Runnable声明为全局变量。在Runnable内部我不能使用getActivity作为上下文/容器。我该怎么用?

以下是onViewCreated()内的代码:

        try {
            Glide.with(this.getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
        } catch (JSONException e) {
            e.printStackTrace();
        }

这是Runnable

    Runnable runnable = new Runnable() {

    @Override
    public void run() {
        if(!isNetworkConnected())
        {
            handler.postDelayed(runnable , time);
        }
        else
        {
            try {
                jsonObject = new JSONObject(MainActivity.dispensaries);
                jsonArray = jsonObject.optJSONArray("dispensaries");
                Log.e(TAG, "jsonArray = " + jsonArray);
                jsonObject = null;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                try {
                    JSONObject object = jsonArray.getJSONObject(i);
                    if(MainActivity.ID.equals(object.get("dispensary_id")))
                    {
                        jsonObject = object;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            try {
                Glide.with(this.).load(jsonObject.getString("dispensary_thumbmail")).into(image);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
};

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

1 个答案:

答案 0 :(得分:1)

试试这个,基本上,你需要 runOnUiThread 的活动类

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                Glide.with(getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });