Android: Java.lang.String cannot be converted to JsonArray - java
This is my android code. When I am trying to parse my jsonArray it gives me an error that string cannot be converted to Jsonarray through my response is json array:
public class Main2Activity extends AppCompatActivity {
EditText tv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
tv1= (EditText) findViewById(R.id.textView);
DefaultOAuthConsumer defaultOAuthConsumer = new DefaultOAuthConsumer("my consumer key","my secret key");
//REQUEST URL
String url = "http://back.unaux.com/wp-json/wc/v2/products";
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
try {
url = defaultOAuthConsumer.sign(url);
Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
JsonArrayRequest req=new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Toast.makeText(Main2Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this,"Error"+error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(req);
}
}
This is my response for json
[
{
"id":685,
"name":"Caramel-min",
"slug":"caramel-min",
"permalink":"http:\/\/back.unaux.com\/product\/caramel-min\/",
"date_created":"2017-09-26T18:56:01",
"date_created_gmt":"2017-09-26T18:56:01",
"date_modified":"2017-09-27T12:27:56",
"date_modified_gmt":"2017-09-27T12:27:56",
"type":"variable",
"status":"publish",
"featured":false,
"catalog_visibility":"visible",
"description":"",
"short_description":"",
"sku":"",
"price":"350",
"regular_price":"350",
"sale_price":"",
"date_on_sale_from":null,
"date_on_sale_from_gmt":null,
"date_on_sale_to":null,
"date_on_sale_to_gmt":null,
"price_html":"<span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">₹<\/span>350.00<\/span> – <span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">₹<\/span>500.00<\/span>",
"on_sale":false,
"purchasable":true,
"total_sales":2,
"virtual":false,
"downloadable":false,
"downloads":[
],
"download_limit":-1,
"download_expiry":-1,
"external_url":"",
"button_text":"",
"tax_status":"taxable",
"tax_class":"",
"manage_stock":false,
"stock_quantity":null,
"in_stock":true,
"backorders":"no",
"backorders_allowed":false,
"backordered":false,
"sold_individually":false,
"weight":"1.0",
"dimensions":{
"length":"",
"width":"",
"height":""
},
"shipping_required":true,
"shipping_taxable":true,
"shipping_class":"",
"shipping_class_id":0,
"reviews_allowed":true,
"average_rating":"0.00",
"rating_count":0,
"related_ids":[
],
"upsell_ids":[
],
"cross_sell_ids":[
],
"parent_id":0,
"purchase_note":"",
"categories":[
{
"id":43,
"name":"Chocolate",
"slug":"chocolate"
}
],
"tags":[
],
"images":[
{
"id":710,
"date_created":"2017-09-27T12:25:19",
"date_created_gmt":"2017-09-27T12:25:19",
"date_modified":"2017-09-27T12:25:19",
"date_modified_gmt":"2017-09-27T12:25:19",
"src":"http:\/\/back.unaux.com\/wp-content\/uploads\/2015\/08\/Caramel-min-1.jpg",
"name":"Caramel-min-1",
"alt":"",
"position":0
},
{
"id":710,
"date_created":"2017-09-27T12:25:19",
"date_created_gmt":"2017-09-27T12:25:19",
"date_modified":"2017-09-27T12:25:19",
"date_modified_gmt":"2017-09-27T12:25:19",
"src":"http:\/\/back.unaux.com\/wp-content\/uploads\/2015\/08\/Caramel-min-1.jpg",
"name":"Caramel-min-1",
"alt":"",
"position":1
}
],
"attributes":[
{
"id":0,
"name":"Kg",
"position":0,
"visible":true,
"variation":true,
"options":[
"1\/2",
"1.0",
"2.0",
"3.0",
"4.0",
"5.0"
]
}
],
"default_attributes":[
],
"variations":[
705,
704
],
"grouped_products":[
],
"menu_order":0,
"meta_data":[
{
"id":1369,
"key":"_vc_post_settings",
"value":{
"vc_grid_id":[
]
}
},
{
"id":1404,
"key":"slide_template",
"value":"default"
}
],
"_links":{
"self":[
{
"href":"http:\/\/back.unaux.com\/wp-json\/wc\/v2\/products\/685"
}
],
"collection":[
{
"href":"http:\/\/back.unaux.com\/wp-json\/wc\/v2\/products"
}
]
}
}
]
you have array inside array.Test like that : add volley library
oncreate(){
sendRequest(); }
private void sendRequest() {
try {
StringRequest stringRequest = new StringRequest(test_urls,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("respnose", "" + response);
parseJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(Page_details_bkp.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Page_details_bkp.this);
requestQueue.add(stringRequest);
} catch (Exception e) {
progressDialog.dismiss();
Log.e("sendreq:", e.toString());
}
}
public void parseJSON(String json) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
try {
userID = jsonObject.getString("api_status");
//ids = new String[jsonArray.length()];
if (userID.equals("success")) {
ids = new String[users.length()];
names = new String[users.length()];
emails = new String[users.length()];
sub_images1 = new String[users.length()][3];
sub_ids = new String[users.length()][3];
// images = new String[users.length()];
//log.e("length :", users.length() + "");
for (int i = 0; i < users.length(); i++) {
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
names[i] = jo.getString(KEY_NAME);
emails[i] = jo.getString(KEY_EMAIL);
try {
JSONObject locArrObj = users.getJSONObject(i); // cotains one "out" array
JSONArray conferenceLocArr = locArrObj.getJSONArray("posts");
if (conferenceLocArr.length() > 0) {
// this array has two objects and each object has array
JSONObject o = null;
for (int ii = 0; ii < conferenceLocArr.length(); ii++) {
o = conferenceLocArr.getJSONObject(ii); // it has one array
try {
// if (!o.getString("image").equals("")) {
sub_images1[i][ii] = o.getString("image");
sub_ids[i][ii] = o.getString("id");
//log.e("Main response:", ids[i] + "," + ids[i] + "," + names[i] + "," + emails[i]);
//}
} catch (JSONException e) {
e.printStackTrace();
//log.e("sub response:", e.toString());
}
// sub_images1[i] = o.getString("image");
// do your work with Stage 1 and guests
// and for second object for Stage 2 and guests.
}
Categories movie = new Categories(ids[i], names[i], emails[i], "2015", sub_images1[i][0],
sub_ids[i][0], sub_images1[i][1], sub_ids[i][1], sub_images1[i][2],
sub_ids[i][2]);
movieList.add(movie);
}
} catch (JSONException e) {
//log.e("response:", e.toString());
e.printStackTrace();
}
}
} else {
}
} catch (JSONException e) {
//log.e("response:", e.toString());
e.printStackTrace();
} finally {
prepareMovieData();
}
} catch (JSONException e) {
//log.e("parse:", e.toString());
}
}
Related
Get JSONObject out of URL and get Integer out of the JSON
I have this URL with a JSON in it I would like to make a JSONObject of it and store the value in a variable named previousID. [ { "id": "179" } ] How can I create that JSONObject and get that int value out of it? I can't make it work with the JSONObject so I tried it with a JSONArray but for some reason I always get the value 0 as return value. private int getPreviousID(Context context){ RequestQueue queue = Volley.newRequestQueue(context); final int[] info = new int[1]; JsonArrayRequest totalListRequest = new JsonArrayRequest(Request.Method.GET, GET_LAST_URL,null, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { for (int i=0; i<response.length(); ++i) { JSONObject o = null; info[0] = 0; try { info[0] += response.getJSONObject(i).getInt("id"); } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, "Unable to communicate with the server", Toast.LENGTH_LONG).show(); } }); queue.add(totalListRequest); return info[0]; }
How to return the value of an asynchronous callback?
This is my code, it's a query to mysql for return 1 or 0, if exist a element in database. I want to know how I get the value? private void comprobarUsuario(String url){ JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(url, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { JSONObject jsonObject = null; for (int i = 0; i < response.length(); i++) { try { String ob = "IF(EXISTS (SELECT * FROM `loginusuario` WHERE `idusuario`='" + id.getText() + "' and `contrasena`='" + contra.getText() + "'), '1', '0')"; jsonObject = response.getJSONObject(i); jsonObject.getString(ob) //I want return this value *-*-*-* } catch (JSONException e) { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(),"Error de conexion",Toast.LENGTH_SHORT).show(); } }); requestQueue=Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); }
Handle null exception in RecyclerView from PHP URL
I'm trying to handle this null exception in RecyclerView from PHP URL. I want it to show a Toast message if a null exception occurs: No Result Found. null exception: Code StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { #Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray array = jsonObject.getJSONArray(uarray); for (int i = 0; i < array.length(); i++) { JSONObject p = array.getJSONObject(i); Category_Movie item = new Category_Movie( p.getInt("id"), p.getString("mTitle"), p.getString("mDesc"), p.getInt("mYear"), ); listItems.add(item); } mAdapter = new CategoryListAll_Adapter(listItems, getActivity()); recyclerView.setAdapter(mAdapter); } catch(JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show(); } }); RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); requestQueue.add(stringRequest);
EDIT Create one method to validate your JSONObject public boolean isJSONValid(String jsonStr) { try { new JSONObject(jsonStr); } catch (JSONException ex) { return false; } return true; } Try to edit following code: StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { #Override public void onResponse(String response) { if (isJSONValid(response)) { try { JSONObject jsonObject = new JSONObject(response); JSONArray array = jsonObject.getJSONArray(uarray); for (int i = 0; i < array.length(); i++) { JSONObject p = array.getJSONObject(i); Category_Movie item = new Category_Movie( p.getInt("id"), p.getString("mTitle"), p.getString("mDesc"), p.getInt("mYear"), ); listItems.add(item); } mAdapter = new CategoryListAll_Adapter(listItems, getActivity()); recyclerView.setAdapter(mAdapter); } catch (JSONException e) { e.printStackTrace(); } } else { // your Toast Message } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show(); } }); RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); requestQueue.add(stringRequest);
Returning early ordinary is way to go ... therefore I'd compare to the known String value of null, in case of no results, before checking if it possibly could be valid JSON (which can already be out-ruled): if(! response.equals("null")) { try ... } or improve statement e.printStackTrace() and handle that JSONException accordingly: try { ... } catch(JSONException e) { if(response.equals("null")) { /* assume no results */ } else { e.printStackTrace(); } } While having access to the PHP code ...better always return a parse-able JSON response: header("Content-Type: application/json"); die(json_encode((object) array( "success" => false, "error" => "no results" ))); ... when the client expects application/json instead of text/plain.
How to get data out of try catch block?
final ArrayList<String> pic = new ArrayList<String>(); final ArrayList<String> name = new ArrayList<String>(); RequestQueue mQueue = Volley.newRequestQueue(this); JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { try { for (int i = 0; i < response.length(); i++) { JSONObject jobj = response.getJSONObject(i); name.add(jobj.getString("name")); pic.add(jobj.getString("pic")); } txt1.setText(name.toString()); } catch (JSONException e) { } } }, new Response.ErrorListener() { #Override public void onErrorResponse(VolleyError error) { Log.d("TAG", "Error: " + error.getMessage()); } }); txt.setText(pic.toString()); mQueue.add(req); name.toString in try is not empty(ex: [a,b,c,d]),but if i move this out of try like pic.toString array is empty (ex:[]).
Android JSON parser Array
The Class: public class MainActivity extends Activity { #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Read().execute("masjids"); } public JSONObject retrieveInfo(String radius) throws ClientProtocolException, IOException, JSONException { StringBuilder url = new StringBuilder( "http://iqamah.org/api/index.php?lat=43&long=-79&radius="); url.append(radius); HttpClient httpclient = new DefaultHttpClient(); HttpGet get = new HttpGet(url.toString()); HttpResponse r = httpclient.execute(get); HttpEntity e = r.getEntity(); String data = EntityUtils.toString(e); JSONObject timeline = new JSONObject(data); return timeline.getJSONObject("1"); } private class Read extends AsyncTask<String, Integer, String> { ProgressDialog pd = null; #Override protected void onPreExecute() { super.onPreExecute(); pd = new ProgressDialog(MainActivity.this); pd.setTitle("Loading..."); pd.setMessage("Please wait..."); pd.setCancelable(false); pd.show(); } protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { JSONObject json = retrieveInfo("200"); return json.getString(arg0[0]); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } #Override protected void onPostExecute(String status) { super.onPostExecute(status); pd.dismiss(); TextView day = (TextView) findViewById(R.id.displayDay); day.setText("Masjid: " + status); } } } The JSON: { "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] } I am trying to access the masjids->id[0] array, how can I do this with the above code?
String data = "{ "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] }"; JSONObject jObj = new JSONObject(data); JSONArray jArray_masjids = jObj.getJSONArray("masjids"); String address = jArray_masjids.getJSONObject(0).getString("id");
JSONObject timeline = new JSONObject(data); JasonArry jarry=timeline.getJsonArray("masjids"); for (int i = 0; i < jarry.length(); i++) { JSONObject explrObject = jsonArray.getJSONObject(i); String newStr = explrObject.getString("id"); }
Try this, String data = "{ "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] }"; JSONObject jObj = new JSONObject(data); JSONArray jArray_masjids = jObj.getJSONArray("masjids"); for(int i = 0 ;i<jArray_masjids;i++){ String address = jsonArray.getJSONObject(i).getString("id"); }