将Json数据解析为具有RecyclerView的网格视图

时间:2015-11-07 09:11:42

标签: android json gridview android-recyclerview recycler-adapter

我指的是这个tuto link。我想在这个网格视图中从服务器获取json数据。请告诉我如何解析数据。加上我需要缓存那些图像..使用凌空库等。  你可以提供解析的任何链接我们的tuto ???请快速建议我

1 个答案:

答案 0 :(得分:0)

使用Volley解析您的数据可以这样实现:

  1. 创建类VolleyService 公共课VolleyService {

    private static VolleyService instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;
    
    private VolleyService(Context context) {
        requestQueue = Volley.newRequestQueue(context);
    
        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);
    
            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }
    
            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url,bitmap);
            }
        });
    }
    
    public static VolleyService getInstance(Context context) {
        if (instance == null) {
            instance = new VolleyService(context);
        }
        return instance;
    }
    
    public RequestQueue getRequestQueue() {
        return requestQueue;
    }
    
    public ImageLoader getImageLoader() {
        return imageLoader;
    }
    

    }

  2. 像这样使用它来创建请求并获取URL的JSON响应:

    RequestQueue queue =

        VolleyService.getInstance(this.getContext()).getRequestQueue();    
        StringRequest request = new StringRequest(url, new 
        Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // we got the response, now our job is to handle it
                try {
                    updateArticleData(response, syncResult,categoryID);
                } catch (RemoteException | OperationApplicationException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
    
            @Override
            public void onErrorResponse(VolleyError error) {
                //something happened, treat the error.
                Log.e("Error", error.toString());
            }
        });
    
        queue.add(request);
    
  3. Mehod getJsonFromResponse(回复):

     private SomeClass getDataFromJson(String json) {     
        //Do sth with json    
        return someData;
    }