Unable To Display Json Data
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 passi
Solution 1:
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 !
Post a Comment for "Unable To Display Json Data"