排球JSON CACE图像无法脱机[英] volley json cache image doesn't work offline

问题描述

您好,我在Anroid中的初学者.我创建了导航抽屉和碎片.我可以通过URL从JSON获取数据.它在网上工作.但是,当我离线时电话时,我会遇到"无法解决主机"错误.我想离线时从JSON中获取URL的数据.不是缓存 在此处输入图像说明

片段

private static final String jsonUrl = "http://sunumsitesi.com/json.php";
private ProgressDialog pDialog;
private List<Urun> urunList = new ArrayList<Urun>();
private ListView listView;
private CustomListAdapter adapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View root = inflater.inflate(R.layout.fragment_yemek, container, false);
    return root;
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    View v = getView();
    if(v!=null)
    {
        listView = (ListView) v.findViewById(R.id.yemekList);
        adapter = new CustomListAdapter(getActivity(), urunList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.show();
        JsonArrayRequest urunReq = new JsonArrayRequest(jsonUrl, new Response.Listener<JSONArray>()
        {
            @Override
            public void onResponse(JSONArray response)
            {
                hidePDialog();
                for (int i = 0; i < response.length(); i++)
                {
                    try
                    {

                        JSONObject obj = response.getJSONObject(i);
                        Urun urun = new Urun();
                        urun.setUrun_adi(obj.getString("urun_adi"));
                        urun.setUrl("http://www.iremdeveci.com/ornekler/resimler/resim.png");//example
                        urunList.add(urun);
                    } catch (JSONException ex)
                    {
                        ex.printStackTrace();
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError volleyError)
            {
                Toast.makeText(getActivity(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        AppController.getmInstance().addToRequestQueue(urunReq);
    }
}

@Override
public void onDestroy()
{
    super.onDestroy();
    hidePDialog();
}
private void hidePDialog()
{
    if(pDialog!=null)
    {
        pDialog.dismiss();
        pDialog=null;
    }
}

和CustomListAdapter(扩展BaseAdapter)

private Activity activity;
private LayoutInflater inflater;
private List<Urun> urunItems;
ImageLoader imageLoader = AppController.getmInstance().getmImageLoader();
public CustomListAdapter(Activity activity,List<Urun> urunItems)
{
    this.activity=activity;
    this.urunItems=urunItems;
}

@Override
public int getCount()
{
    return urunItems.size();
}

@Override
public Object getItem(int location)
{
    return urunItems.get(location);
}

@Override
public long getItemId(int position)
{
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    if (inflater==null)
    {
        inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    if (convertView==null)
    {
        convertView=inflater.inflate(R.layout.list_row,null);
    }
    if (imageLoader==null)
    {
        imageLoader=AppController.getmInstance().getmImageLoader();
    }
    NetworkImageView urunResim=(NetworkImageView)convertView.findViewById(R.id.urunResim);
    TextView urun_adi= (TextView)convertView.findViewById(R.id.urun_adi);
    Urun u = urunItems.get(position);

    urunResim.setImageUrl(u.getUrl(),imageLoader);
    urun_adi.setText(u.getUrun_adi());
    return convertView;
}

lrubitmapcache.java

public static int getDefaultLruCacheSize()
{
    final int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
    final int cacheSize= maxMemory/8;
    return cacheSize;
}
public LruBitmapCache()
{
    this(getDefaultLruCacheSize());
}
public LruBitmapCache(int sizeInKiloBytes)
{
    super(sizeInKiloBytes);
}

@Override
protected int sizeOf(String key, Bitmap value)
{
    return value.getRowBytes() * value.getHeight()/1024;
}

@Override
public Bitmap getBitmap(String url)
{
    return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap)
{
    put(url,bitmap);
}

推荐答案

您的图片(/resimler/resim.png )似乎已正确缓存,因为有ETAG和缓存标头.

但是,您提出的第一个请求( http://sunumsitesi.com/json.com/json.php )似乎没有返回缓存标头也没有返回.因此,您有错误,甚至没有到达图片部分.

您可以从服务器修复该问题,也可以使其全部制作凌空缓存,您需要为其创建自定义请求并覆盖

protected Response<String> parseNetworkResponse(NetworkResponse response)

您可以检查我的答案 >.

在您的代码中,这会像

一样smth
        JsonArrayRequest urunReq = new JsonArrayRequest(jsonUrl, new Response.Listener<JSONArray>()
    {
        @Override
        public void onResponse(JSONArray response)
        {
            String dosyakonum = "http://www.pukkaliving.concept.com/upload/galeri/buyuk/";
            hidePDialog();
            for (int i = 0; i < response.length(); i++)
            {
                try
                {

                    JSONObject obj = response.getJSONObject(i);
                    Urun urun = new Urun();
                    urun.setUrun_adi(obj.getString("urun_adi"));
                    urun.setUrl("http://www.iremdeveci.com/ornekler/resimler/resim.png");//example
                    urunList.add(urun);
                } catch (JSONException ex)
                {
                    ex.printStackTrace();
                }
            }
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError volleyError)
        {
            Toast.makeText(getActivity(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
        }
    }) {
        @Override
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString =
                        new String(response.data, HttpHeaderParser.parseCharset(response.headers));

                long now = System.currentTimeMillis();
                Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);
                entry.ttl = now + 30l * 24 * 60 * 60 * 1000;  //keeps cache for 30 days
entry.softTtl = now + 1 * 24 * 60 * 60 * 1000;  //will not try to refresh for 1 day     
                    return Response.success(new JSONArray(jsonString), entry);
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JSONException je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        AppController.getmInstance().addToRequestQueue(urunReq);

但是,对于网络图视图,您必须自定义 Imageloader 因为这是创建图像请求的人,然后逻辑相同.您必须覆盖" makeimagerequest".

ex:

  ...
mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache()) {
    @Override
        protected Request<Bitmap> makeImageRequest(String requestUrl, int maxWidth, int maxHeight,
                    ScaleType scaleType, final String cacheKey) {
                return new ImageRequest(requestUrl, new Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        onGetImageSuccess(cacheKey, response);
                    }
                }, maxWidth, maxHeight, scaleType, Config.RGB_565, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        onGetImageError(cacheKey, error);
                    }
                }){
          @Override
                    public Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
                        Response<Bitmap> resp = super.parseNetworkResponse(response);
                        if(!resp.isSuccess()) {
                            return resp;
                        }
                        long now = System.currentTimeMillis();
                        Cache.Entry entry = resp.cacheEntry;
                        entry.ttl = now + 30l * 24 * 60 * 60 * 1000;  //keeps cache for 30 days
                        return Response.success(resp.result, entry);
                    }

        };
            }
};
    ...

本文地址:https://www.itbaoku.cn/post/978447.html