Unable to display Json data

2019-08-18 22:58发布

I am trying to display json array which is inside a json object but nothing is displaying on the text view. I debugged and found that info.java class is working fine. If i am passing the simple string value(after removing the json parsing java code) in the info.java class it's working but i am unable to pass json data.
Singleton.java

package com.example.osama.recyclerthug;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class Singleton {
    private static Singleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private Singleton(Context context){
        mCtx = context;
        mRequestQueue =getRequestQueue();

                mImageLoader = new ImageLoader(mRequestQueue,
                        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 synchronized Singleton getInstance(Context context){
        if (mInstance == null){
            mInstance = new Singleton(context);
        }
        return mInstance;
    }
    public RequestQueue getRequestQueue(){
        if (mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }
    public <T> void addToRequestQueue(Request<T> request){
        getRequestQueue().add(request);
    }
    public ImageLoader getmImageLoader(){
        return mImageLoader;
    }

}

................................................................... ThugAdapter.java

 package com.example.osama.recyclerthug;

import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;


public class ThugAdapter extends RecyclerView.Adapter<ThugAdapter.ThugHolder> {

    ArrayList<Info> arrayList1;

    public ThugAdapter(ArrayList<Info> arrayList){
        this.arrayList1 = arrayList;
    }

    @NonNull
    @Override
    public ThugHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View view = inflater.inflate(R.layout.appearance, viewGroup, false);
        ThugHolder thugHolder = new ThugHolder(view);
        return thugHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ThugHolder thugHolder, int i) {

        thugHolder.text.setText(arrayList1.get(i).getTxt1());
        thugHolder.text2.setText(arrayList1.get(i).getTxt2());
      /*  thugHolder.image.setImageURI(arrayList.get(i).getImageUri());*/

    }

    @Override
    public int getItemCount() {
        return arrayList1.size();
    }

    public class ThugHolder extends RecyclerView.ViewHolder{

        TextView text,text2;
        ImageView image;
        public ThugHolder(@NonNull View itemView) {
            super(itemView);
            text = itemView.findViewById(R.id.textView);
            text2 = itemView.findViewById(R.id.textView2);
            image = itemView.findViewById(R.id.imageView);
        }



    }
}

............................................................................ Info.java

package com.example.osama.recyclerthug;

import android.net.Uri;

public class Info {
    private String txt1,txt2;
   // private Uri imageuri;
    public Info(String txt1, String txt2/*, Uri imageuri*/){
        this.setTxt1(txt1);
        this.setTxt2(txt2);
       /* this.setImageUri(imageuri);*/
    }

    public String getTxt1() {
        return txt1;
    }

    public void setTxt1(String txt1) {
        this.txt1 = txt1;
    }

    public String getTxt2() {
        return txt2;
    }

    public void setTxt2(String txt2) {
        this.txt2 = txt2;
    }

    /*public Uri getImageUri() {
        return imageuri;
    }

    public void setImageUri(Uri imageuri) {
        this.imageuri = imageuri;
    }*/
}

........................................................ BackgroundTask.java

package com.example.osama.recyclerthug;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class BackgroundTask {
    Context context;
    ArrayList<Info> arrayList;
    String json_url = "http://cc97cf60.ngrok.io/api/note/";

    public BackgroundTask(Context context){
        this.context = context;
    }
    public ArrayList<Info> getArrayList(){

        arrayList = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray jsonArray ;
                        try {
                            jsonArray = response.getJSONArray("objects");
                            int i;
                            for (i = 0; i < jsonArray.length(); i++){
                                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                           /*     Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
                                String a = jsonObject.getString("title");
                                String b = jsonObject.getString("body");
                                Info info = new Info(a,b);
                                arrayList.add(info);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {



            }
        });
        Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
        return arrayList;
    }
}

.............................................. MainActivity.java

package com.example.osama.recyclerthug;

import android.app.DownloadManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONObject;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ThugAdapter thugAdapter;
    BackgroundTask backgroundTask;
    ArrayList<Info> arrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recycler);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        backgroundTask = new BackgroundTask(this);
        arrayList = new ArrayList<>();
        arrayList= backgroundTask.getArrayList();
        thugAdapter = new ThugAdapter(arrayList);
        recyclerView.setAdapter(thugAdapter);


    }
}

Edit: Below is the json data:

{
  "meta": {
    "limit": 20,
    "next": null,
    "offset": 0,
    "previous": null,
    "total_count": 2
  },
  "objects": [
    {
      "body": "Breaking News:\r\nOsama Abrar is Iron Man.",
      "created_at": "2018-12-08T08:40:59.949776",
      "id": 1,
      "image": "https://wonderfulengineering.com/wp-content/uploads/2016/01/iron-man-wallpaper-6.jpg",
      "resource_uri": "/api/note/1/",
      "title": "Iron Man"
    },
    {
      "body": "Will Iron Man aka Osama Abrar survive?",
      "created_at": "2018-12-08T08:41:40.279677",
      "id": 2,
      "image": "https://marciokenobi.files.wordpress.com/2013/03/iron_man.jpg",
      "resource_uri": "/api/note/2/",
      "title": "End Game"
    }
  ]
}

1条回答
闹够了就滚
2楼-- · 2019-08-18 23:53

JSON parsing is OK but you can't retrieve your data like this because you used Volley in asynchronous mode. It means that you can't assume that data will be retrieved as soon as you put the request in the queue. Maybe the queue is very long and your request can be sent later. So, when you tried to retrieve your data, you've seen that your arrayList is null, and it's normal. To deal with the asynchronous way, you have to tell Volley : "tell me when you've retrieved data". And you can do this with a listener.

Here is an example.

public interface Listener {

    void onDataReceived(ArrayList<Info> list);
    void onError(int error);
}

BackgroundTask

public class BackgroundTask {
    Context context;
    ArrayList<Info> arrayList;
    Listener mListener; // listener to retrieve data
    String json_url = "http://cc97cf60.ngrok.io/api/note/";

    public BackgroundTask(Context context, Listener listener) {
        this.context = context;
        mListener = listener;
    }

    public void getArrayList() { // no return needed

        arrayList = new ArrayList<>();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, json_url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        JSONArray jsonArray;
                        try {
                            jsonArray = response.getJSONArray("objects");
                            int i;
                            for (i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                                /*     Uri b = Uri.parse(jsonObject.getString("image")); //Type casting string to uri*/
                                String a = jsonObject.getString("title");
                                String b = jsonObject.getString("body");
                                Info info = new Info(a, b);
                                arrayList.add(info);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // if listener has been set, send data
                        if (mListener != null) {
                            mListener.onDataReceived(arrayList);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // if listener has been set, send error
                if (mListener != null) {
                    mListener.onError(error.networkResponse.statusCode);
                }
            }
        });
        Singleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
    }
}

In your MainActivity :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = findViewById(R.id.recycler);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    backgroundTask = new BackgroundTask(this, new Listener() {
        @Override
        public void onDataReceived(ArrayList<Info> list) {
            thugAdapter = new ThugAdapter(list);
            recyclerView.setAdapter(thugAdapter);
        }

        @Override
        public void onError(int error) {

        }
    });
    backgroundTask.getArrayList();
}

And that is !

查看更多
登录 后发表回答