This question already has answers here:
JSON Array of strings (no objects), extracting data
(4 answers)
Closed 6 years ago.
its actually a simple code, cuz of lack of basic I still cant manage to handle this.
After I made a Post JSON Method on my own Api, I get the following response
[{"id":"2"}]
What I'm trying to achieve is that I would like to get the value of this "id" which is "2".
I've tried the following code in my private void method
private void getUserID() {
StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();
}
output.setText(idUser);
} catch (JSONException e) {e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I get it from here.
It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.
replace your try block with following
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String idUser = jsonObject.getString("id");
Log.e("id is: ", idUser);
}
Try this way you will get
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( delprourl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
// Parsing json
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person" + person);
//get your id here
String id = person.getString("id");
Log.e("id: ", id);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
Related
Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.
I have using volley library for fetching data. I used a HashMap to store response data. When I fetch the data out of the volley request it is showing empty. I knew I should use this Hashmap inside the response method. But I need to get that in a global variable. Any suggestions?
String liveURL = BASE_URL + "livescores?api_token=" + API_KEY;
HashMap<String, String> hashMap = new HashMap<>();
JsonObjectRequest livescoresRequest = new JsonObjectRequest(Request.Method.GET,
liveURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
final JSONArray liveArray = response.getJSONArray("data");
for (int i = 0; i < liveArray.length(); i++) {
JSONObject data = liveArray.getJSONObject(i);
String liveID = data.getString("id");
final String league_id = data.getString("league_id");
hashMap.put(league_id, liveID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
});
Volley.newRequestQueue(getContext()).add(livescoresRequest);
Log.i("HASHMAP", hashMap.toString());
I am parsing json using volley but its not working and getting error. Follwing is my code and json reponse. please help me to solve this
private void getStaffList() {
showpDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
final String url = "url";
try {
final JSONObject jsonObj = new JSONObject();
jsonObj.put("username", "test");
jsonObj.put("password", "123456");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", "Main response=" + response);
staffarraylist=new ArrayList<DataModel>();;
try {
JSONObject jobSuccess=response.getJSONObject("TABLE_DATA");
Log.d("TAG", "JSONObj response=" + jobSuccess);
JSONArray jarMyData=jobSuccess.getJSONArray("data");
Log.d("TAG", "JSONArray response=" + jarMyData);
for (int i = 0; i < jarMyData.length(); i++) {
JSONArray jar = jarMyData.getJSONArray(i);
DataModel movie = new DataModel();
movie.setName(jar.getString(0));
movie.setOccupation(jar.getString(1));
movie.setPlace(jar.getString(2));
movie.setId(jar.getString(3));
movie.setDate(jar.getString(4));
movie.setPrice(jar.getString(5));
staffarraylist.add(movie);
}
}catch (JSONException e)
{
Log.d("JSONException",e.toString());
}
rcAdapter = new RecyclerViewAdapterHome(MainActivity.this, staffarraylist);
recyclerView.setAdapter(rcAdapter);
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("TAG", "JSONObj Error: " + error.getMessage());
hidepDialog();
//Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
});
requestQueue.add(jsonObjReq);
} catch (JSONException e) {
e.printStackTrace();
}
}
Logcat
Main response={"TABLE_DATA":"{\"data\":[[\"Tiger Nixon\",\"System Architect\",\"Edinburgh\",\"5421\",\"2011/04/25\",\"$320,800\"],[\"Garrett Winters\",\"Accountant\",....so on
D/JSONException: org.json.JSONException: Value {"data":[["Tiger Nixon","System Architect","Edinburgh","5421","2011/04/25","$320,800"],["Garrett Winters","Accountant","Tokyo","8422","2011/07/25","$
First check that your json format is correct or not by clicking here and paste your json for checking. If the response is correct then use Gson. It will parse the response without any error.
I need help in modifying my android studio code for converting Json object to an array. Bellow is the error in my log cat and the actual code.
This is the error message I am getting in the logcat:
04-03 12:01:16.727 19993-19993/com.errandit E/Volley: com.android.volley.ParseError: org.json.JSONException: Value {"data":[{"errand":"Shopping","charges":"500"},{"errand":"House Assistance","charges":"7000"},{"errand":"Pick - Up","charges":"2500"}],"success":1,"message":" 0 records found"} of type org.json.JSONObject cannot be converted to JSONArray
**I am trying to fetch the json array from my wamp server using the method below. **
private void getData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.show();
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley",error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
Change like below as You are getting JSONObject and inside it there is JSONArray named "data".
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
(Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject mResponse)
{
JSONArray response=mResponse.optJSONArray("data")
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Service service = new Service();
service.setName(jsonObject.getString("errand"));
service.setCharges(jsonObject.getInt("charges"));
serviceList.add(service);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
// Add the request to the RequestQueue.
queue.add(jsonObjRequest);
I get the error no value for city.
I'm new to Android. I was unable to pass the spinner data using PHP URL, volley method. And in my XML I'm using the spinner and text views city, id and pass the city list through spinner URL.
Here is my activity:
private void spinnerapi(){
sprCoun = (Spinner) findViewById(R.id.spinner);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String serverURL = "server url";
final StringRequest getRequest = new StringRequest(Request.Method.POST, serverURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("officerResponse", response);
try {
JSONObject jsonObject = new JSONObject(response);
String str_status = jsonObject.getString("status");
String str_message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectGuest = jsonArray.getJSONObject(i);
city_name = jsonObjectGuest.getString("cityname");
city_id = jsonObjectGuest.getString("cityid");
listarraylist.add(new CityModel(city_name));
}
sprCoun.setAdapter(new ArrayAdapter<String>
(RegistrationActivity.this, android.R.layout.simple_spinner_dropdown_item, list));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG).show();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
// Toast.makeText(context, "" + error, Toast.LENGTH_LONG).show();
Log.d("tyghj", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
queue.add(getRequest);
}