I have an adapter class which is extending GroupingCursorAdapter
and constructor of type
Adapter_Contacts(Context context, Cursor cursor, AsyncContactImageLoader asyncContactImageLoader)
.
I want to use this same class for populating my ListView
. I am getting data from one web service which is JSON
.
So my question is that, how can I convert a JSONArray
to Cursor
to use same adapter class?
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
So my question is that, how can I convert a JSONArray to Cursor to use same adapter class?
You can convert that JSONArray
to a MatrixCursor
:
// I'm assuming that the JSONArray will contain only JSONObjects with the same propertties
MatrixCursor mc = new MatrixCursor(new String[] {"columnName1", "columnName2", /* etc*/}); // properties from the JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
// extract the properties from the JSONObject and use it with the addRow() method below
mc.addRow(new Object[] {property1, property2, /* etc*/});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With