Try to POST JSONArray with volley - java

I got an jsonarray like:
[{
"color": -1,
"fill": false,
"id": 1,
"radius": 154.613,
"shapeText": "",
"shapeType": "circle",
"x1": 141.172,
"x2": 0,
"y1": 231.188,
"y2": 0
}, {
"color": -4569601,
"fill": false,
"id": 2,
"radius": 0,
"shapeText": "",
"shapeType": "rectangle",
"x1": 512.656,
"x2": 606.781,
"y1": 305.25,
"y2": 413.502
}]
and I try to do POST to the server but I fail :[
I already get an jsonarray frm the server and I also did POST but for jsonobject to the server but I couldn't make it POST Jsonarray :[, anyone got any idea how to do it?
public class JSONPostArrayRequest extends JsonRequest<JSONObject> {
JSONArray params;
public JSONPostArrayRequest(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, JSONArray params) {
super(Method.POST, url, null, listener, errorListener);
this.params=params;
}
#Override
public byte[] getBody() {
if ( this.params != null && this.params.length() > 0) {
return encodeParameters( this.params, getParamsEncoding());
}
return null;
}
private byte[] encodeParameters(JSONArray params, String paramsEncoding) {
try {
return params.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
and my request done with this code:
public void updateDraw(ArrayList<Shape> shapes) {
JSONArray jsonArrayShapes = new JSONArray();
Log.d("START OF JSON ARRAY ", shapes.toString());
for (Shape shape : shapes) {
try {
JSONObject jsonObjectShape = new JSONObject();
jsonObjectShape.put("color", String.valueOf(shape.getColor()));
jsonObjectShape.put("fill", String.valueOf(shape.isFill()));
jsonObjectShape.put("radius", String.valueOf(shape.getRadius()));
jsonObjectShape.put("shapeText", String.valueOf(shape.getShapeText()));
jsonObjectShape.put("shapeType", String.valueOf(shape.getShapeType()));
jsonObjectShape.put("x1", String.valueOf(shape.getX1()));
jsonObjectShape.put("x2", String.valueOf(shape.getX2()));
jsonObjectShape.put("y1", String.valueOf(shape.getY1()));
jsonObjectShape.put("y2", String.valueOf(shape.getY2()));
jsonObjectShape.put("id", String.valueOf(shape.getId()));
jsonArrayShapes.put(jsonObjectShape);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSONARRAY = ", jsonArrayShapes.toString());
}
String shapeUrl = Main.GROUPS_URL + "/" + id + "/shape";
Log.d("URL = ", shapeUrl);
JSONPostArrayRequest jsonPostArrayRequest = new JSONPostArrayRequest(shapeUrl,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onErrorResponse ", error.toString());
}
}, jsonArrayShapes);
requestQueue.add(jsonPostArrayRequest);
}

You aren't passing your JSONArray into the request.
super(Method.POST, url, null, listener, errorListener);
That null parameter, as per the documentation
A JSONArray to post with the request. Null is allowed and indicates no parameters will be posted along with request.
Therefore, I don't see why you need to extend JsonRequest, or especially why you typed it with <JSONObject>.
The JsonArrayRequest class already exists, you just need to give the JSONArray object as the third parameter there.

Related

JSONObject cannot be converted to String

I saw this questions a bunch of times here in Stack, but had no luck. The thing is, I'm using this API for validate my CNPJ field, if I have a connection, the response would be the field "nome" and populate my textview field.
So far so good, the JSON is valid (already passed in jsonformatter) but I can't the object through JSONArray and when I manage to find it by JSONObject it tells me that can't be converted to String.
valide.setOnClickListener(view1 -> {
//String PJ = cnpj.getText().toString();
String PJ = "06990590000123";
String url = "https://www.receitaws.com.br/v1/cnpj/" + PJ;
jsonParse(url);
});
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getJSONObject("nome").toString();
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
JSON
{ "atividade_principal": [ { "text": "Portais, provedores de conteúdo e outros serviços de informação na internet", "code": "63.19-4-00" } ],
"data_situacao": "01/09/2004",
"complemento": "ANDAR 17A20 TSUL 2 17A20", "tipo": "MATRIZ",
**"nome": "GOOGLE BRASIL INTERNET LTDA.", //Need this field**
"uf": "SP",
"telefone": "(11) 2395-8400",
"email": "googlebrasil#google.com",
LOG
org.json.JSONException: Value GOOGLE BRASIL INTERNET LTDA. at nome of
type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:101)
URL USED
https://www.receitaws.com.br/v1/cnpj/06990590000123
Can someone help me with this problem, please ? Thank you !
In your JSON the nome is of type String. So rather than getJSONObject use getString method from JSONObject class. So your code should be like below:
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
String json;
#Override
public void onResponse(JSONObject response) {
try {
json = response.getString("nome"); // Here is the change
razao.append(json);
razao.setText(json);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Invalid ! ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError erro) {
erro.printStackTrace();
}
});
mQueue.add(request); //Volley.newRequestQueue
}
Try this:
First construct JsonObject and then get the string value of the key.
JSONObject jsonObject = new JSONObject(json);
String valueIWanted = jsonObject.getString("nome"))

JSON object not displaying values after fetching from database

I am fetching data from database in android and i can see data fetching from databse in JSON format using POSTMAN but when i am trying to display it in my android application, its not displaying any value.
Values from POSTMAN:
{
"result": [
{
"Date": "18-3-2016",
"Events": "Local Holiday"
},
{
"Date": "23-3-2016",
"Events": "Monthly Fees"
},
{
"Date": "15-4-2016",
"Events": "Monthly Fees"
},
{
"Date": "23-4-2016",
"Events": "Annual Day"
},
{
"Date": "30-4-2016",
"Events": "session end"
},
{
"Date": "9-4-2016",
"Events": "Parent Teacher Meeting"
}
]
}
I am following some tutorials and Code using:
private void getData() {
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = config_events.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(events.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response) {
String date = "";
String comment="";
//String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_events.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
date = collegeData.getString(config_events.KEY_NAME);
comment = collegeData.getString(config_events.KEY_ADDRESS);
//vc = collegeData.getString(config_events.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Date:"+date + "Comment:"+ comment);
Assuming that you have tried to debug it, this could be the problem of user-permissions in Android manifest. Make sure that you have following permissions in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
if you really getting the response through the API you might want to check the JSON parsing code this is something I wrote while assuming the response in the question
private void showJSON(String response){
try{
Log.d(TAG, "showJSON: \n"+response);// print here to check you are getting the right response
JSONObject response_JsonObject = new JSONObject(response);
JSONArray result_JsonArray = response_JsonObject.getJSONArray("result");
ArrayList<Event> events = new ArrayList<>();
for (int i = 0; i < result_JsonArray.length(); i++) {
Event single_Event = new Event();
single_Event.setDate(result_JsonArray.getJSONObject(i).getString("Date"));
single_Event.setEvent(result_JsonArray.getJSONObject(i).getString("Events"));
events.add(single_Event);
}
Log.d(TAG, "showJSON: Event list size: "+events.size()); // check number of elements
}catch (Exception e){
e.printStackTrace();
}
}
private class Event{
private String date;
private String event;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
}

Unable to mimmick POSTMAN request in Volley

I am new to using Volley on Android. Using the old http client stuff I could make my web requests perfectly with the various headers and parameters, now I am unable. My request looks like this in Postman:
POST /token HTTP/1.1
Host: my.api.co.za
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
username=test&password=1234&grant_type=password
Yet I am unable to recreate and execute this request in Volley. I have tried making a custom Json request class that extends Request<JSONObject> but to no avail. Please see my code below:
public class CustomJsonRequest extends Request<JSONObject> {
private Response.Listener<JSONObject> listener;
private Map<String, String> params;
public CustomJsonRequest(int method, String url, Listener<JSONObject> responseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = responseListener;
}
#Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", "test");
params.put("password", "1234");
params.put("grant_type", "password");
if (params != null && params.size() > 0) {
return encodeParameters(params, getParamsEncoding());
}
return null;
}
/**
* Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
*/
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
encodedParams.deleteCharAt(encodedParams.lastIndexOf("&"));
Log.e("params", encodedParams.toString());
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.e("response", response.toString());
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
Log.e("response", response.toString());
listener.onResponse(response);
}
private Priority mPriority;
public void setPriority(Priority priority) {
mPriority = priority;
}
#Override
public Priority getPriority() {
return mPriority == null ? Priority.NORMAL : mPriority;
}
}
And I call this as follows in my MainActivity class:
CustomJsonRequest request = new CustomJsonRequest(Request.Method.POST, AUTH_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//showJSON(response);
VolleyLog.v("Response:%n %s", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
txtError(error);
}
});
Can somebody tell me where I am going wrong in creating this request?
You can try with my following sample code:
String url = "http://server/token";
Map<String, String> stringMap = new HashMap<>();
stringMap.put("grant_type", "password");
stringMap.put("username", "bnk");
stringMap.put("password", "bnk123");
Uri.Builder builder = new Uri.Builder();
Iterator entries = stringMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
entries.remove();
}
String requestBody = builder.build().getEncodedQuery();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}){
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
};
UPDATE:
If your project uses Google's official volley as a module, you should add the following into JsonObjectRequest.java file:
public JsonObjectRequest(int method, String url, String requestBody,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
UPDATE 2:
If you don't want to edit JsonObjectRequest.java file as I mentioned above, you can use the following code:
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() {
// init parameters
Map<String, String> params = new HashMap<>();
params.put("grant_type", "password");
params.put("username", "bnk");
params.put("password", "bnk123");
// encode parameters (can use Uri.Builder as above)
String paramsEncoding = "UTF-8";
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
};
Hope it helps!

Volley JSONException: End of input at character 0 of

I've seen others come across this problem, but none of the posts have been able to assist me. I'm attempting to use Volley for my REST call library, and when I'm attempting to use a Put call with a JSON Object as a parameter, I'm getting error with: org.json.JSONException: End of input at character 0 of.
Here is the code:
protected void updateClientDeviceStatus(Activity activity, final int status) {
JSONObject jsonParams = new JSONObject();
try {
jsonParams.put("statusId", String.valueOf(status));
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.i(LOG_TAG, "json: " + jsonParams.toString());
String url = Constants.API_URL + "client/device/" + getDeviceId();
// Request a response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest
(Request.Method.PUT, url, jsonParams, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(LOG_TAG, "updated client status");
Log.i(LOG_TAG, "response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(LOG_TAG, "error with: " + error.getMessage());
if (error.networkResponse != null)
Log.i(LOG_TAG, "status code: " + error.networkResponse.statusCode);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", getUserAgent());
params.put("X-BC-API", getKey());
return params;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
request.setRetryPolicy(new DefaultRetryPolicy(20000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(activity).addToRequestQueue(request);
}
}
The jsonParams log displays:
json: {"statusId":"1"}
Is there another setting that I'm missing? It appears that the request can't parse the JSON Object. I even tried creating a HashMap and then using that to create a JSON Object, but I still get the same result.
I also have encountered this issue.
It's not necessarily true that this is because a problem on your server side - it simply means that the response of the JsonObjectRequest is empty.
It could very well be that the server should be sending you content, and the fact that its response is empty is a bug. If, however, this is how the server is supposed to behave, then to solve this issue, you will need to change how JsonObjectRequest parses its response, meaning creating a subclass of JsonObjectRequest, and overriding the parseNetworkResponse to the example below.
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject result = null;
if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
Keep in mind that with this fix, and in the event of an empty response from the server, the request callback will return a null reference in place of the JSONObject.
Might not make sense but nothing else worked for me but adding a content-type header
mHeaders.put("Content-Type", "application/json");
In my case it was simply the request I was sending(POST) was not correct. I cross-checked my fields and noted that there was a mismatch, which the server was expecting to get thus the error->end of input at character 0 of...
I had the same problem, I fixed it by creating a custom JsonObjectRequest that can catch a null or empty response :
public class CustomJsonObjectRequest extends JsonObjectRequest {
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomJsonObjectRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONObject result = null;
if (jsonString != null && jsonString.length() > 0)
result = new JSONObject(jsonString);
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
Then just replace the default JsonObjectRequest by this one !
You need to check if the server response is not empty. Maybe it could be a emtply String "".
if (response.success()) {
if (response.getData() == null) {
return null;
} else if (response.getData().length() <= 0){
return null;
}
// Do Processing
try {
I have faced the same problem, there was just a small silly mistake that happened.
instead of
val jsonObject = JSONObject(response.body()?.string())
should be
val jsonObject = JSONObject(response.body()!!.string())

How to loop through json data in android

As mentioned in the title. How can I loop through my json data that I am getting from server. My getting this kind of json data
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Saleem",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
here is where I am getting my json data
public class Home extends Activity {
Button btnLogout;
ScrollView svHome;
UserFunctions userFunctions;
LoginActivity userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
userid = new LoginActivity();
svHome = (ScrollView)findViewById(R.id.svHome);
setContentView(R.layout.home);
userFunctions = new UserFunctions();
/***********************************************************/
//here is where my above mentioned json data is
JSONObject json = userFunctions.homeData();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
//currently this only shows the first json object
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*******************************************************/
}
}
Update
After make changes accroding to the link given in the answer. Here are my changes
/***********************************************************/
JSONObject json = userFunctions.homeData();
String jsonData = json.toString();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("Object", jsonObject.getString("places"));
//Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
}
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Please look over the link
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
an if possible made the changes in json, as there is no array braces "[" "]" in json and you need that to itrate in loop
json should be like that
{
"arrayKey": [
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
},
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
}
]
}
You could use the json libraries like the following:
import org.json.JSONArray;
import org.json.JSONObject;
which allows you to read json data into array like this:
JSONArray jsonArray = new JSONArray([your json data]);
Try this tutorial: http://www.vogella.com/articles/AndroidJSON/article.html
one other way I'll recommend is Use GSON library, It is easy end pain less. for well formatted Json
As your logcat states, you're trying to convert a JSONObject to a JSONArray:
org.json.JSONException: Value {"uid":"4fc8f94f1a51c5.32653037","places":{"place_photo":"http://example.info/android/places_photos/place1.jpg","created_at":"2012-06-02 00:00:00","seeked":"0","longitude":"24.943514","latitude":"60.167112"},"error":0,"success":1,"tag":"home","profile_photo":"http://example.info/android/profile_photos/profile1.jpg","name":"Zafar Saleem"} of type org.json.JSONObject cannot be converted to JSONArray
Try to debug the code - find out where the exception is thrown, and make a JSONObject there instead of a JSONArray.

Categories