I have a problem in using volley Rest API Post Request
I am not sure is it required to use Map but here I didn't use it.
I'm trying to update my jSONArray from this :
[
{
"id": 1,
"num1": "1",
"num2": "0",
"num3": "1",
"num4": "0"
}
]
into this :
[
{
"id": 1,
"num1": "1",
"num2": "1",
"num3": "1",
"num4": "0"
}
]
Following is my code( I used volley Post request for this ) :
RequestQueue queue = Volley.newRequestQueue(Rele.this);
String url = "https://mysite.dev/fdfh2g/data";
JsonArrayRequest request = new JsonArrayRequest
(Request.Method.POST, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Integer num2val = 1 ;
try {
JSONObject Info = response.getJSONObject(0);
Info.put("num2",num2val);
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
but instead I'm getting this :
[
{
"id": 1,
"num1": "1",
"num2": "1",
"num3": "1",
"num4": "0"
},
{
"id": 2
}
]
Related
I am getting response from API as a JSONarray and I can get the data into my arraymodel but the problem is I need some specific data from one array and I don't have any idea how to do that.
the array is:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name": "a:1:{s:7:\"english\";s:9:\"rent bill\";}",
"img": "shop.png"
}
I want the English, S:9 and the rent bill data from name.
I am posting my code here so you can understand what I have done and what mistake i'm committing.
public void shopListing()
{
showSimpleProgressDialog(this, "Loading...","Fetching Shops History",false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, shopurl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
//if(obj.optString("status").equals("true")){
dataModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("history");
for (int i = 0; i < dataArray.length(); i++) {
shopModel playerModel = new shopModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setId(dataobj.getString("id"));
playerModel.setName(dataobj.getString("name"));
playerModel.setDetails(dataobj.getString("date"));
dataModelArrayList.add(playerModel);
}
setupListview();
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String api = getApi_key();
String user = getUser_key();
Map<String, String> param = new HashMap<> ();
param.put("api_key", api);
param.put("user_key", user);
return param;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Your server response is not good. instead of sending name as a string to you, it should return you "name" as an object like this:
"history": [
{
"id": "20",
"code": "mcw_5b97de588ce0c",
"date": "2018-09-11 17:25:12",
"status": "1",
"name":
{
"s":7,
"subject":"english",
"s":9,
"any_key":"rent bill"
},
"img": "shop.png"
}
I feel like server is returning you code string which you have written to process request from client. Please double check.
I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}
{
"reservation_upto": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"debit": 3,
"doj": "28-05-2018",
"to_station": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"response_code": 200,
"boarding_point": {
"lng": 80.2755685,
"lat": 13.081674,
"code": "MAS",
"name": "CHENNAI CENTRAL"
},
"pnr": "4405474586",
"chart_prepared": false,
"journey_class": {
"code": "3A",
"name": null
},
THIS IS WHAT I HAVE TRIED USING VOLLEY
private void loaddata() {
String url = "https://api.railwayapi.com/v2/pnr-status/pnr/4655474586/apikey/q15rfl3kpz/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
JSONObject obj = null;
try {
String str="";
obj = response.getJSONObject("name");
str = String.valueOf(obj);
TextView tv = (TextView)findViewById(R.id.textView);
tv.append(str);
}
}
}
}
}
JSONObject obj = (JSONObject) object;
String doj = (String) obj.get("doj")
You can use JSONObject obj to find out the value of key doj.
Latter on, if you want to have the doj as any other datatype you can parse in that. May be this could help. I don't have much idea on Volley :)
I have a response form server as :
[
{
"ID": "1",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "71500200",
"IsActive": "yes"
},
{
"ID": "2",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "71500900",
"IsActive": "yes"
},
{
"ID": "3",
"Title": "BIRATNAGAR",
"BankID": "1",
"BranchCode": "0",
"LocationID": "94361117",
"IsActive": "yes"
}
]
I have retrofit api as:
#POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
Call> getBranchListByBank(#Query("api_key") String id);
I have called it as:
RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);
Call<List<BankBranch>> call = service.getBranchListByBank(s);
call.enqueue(new Callback<List<BankBranch>>() {
#Override
public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
try {
List<BankBranch> banks = response.body();
for (int i = 0; i < banks.size(); i++) {
String id = banks.get(i).getTitle();
String name = banks.get(i).getID();
String marks = banks.get(i).getIsActive();
Log.i("ashihs", id + " " + marks + " " + name);
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<List<BankBranch>> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
But I cannot get the list of the bank branch. I get error as :
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Can any one help me?
Thanks in advance.
U probably got bad Api request it schould look like this:
api:
#POST("authapp/Restserver/api/Masterdata/getBranchListByBank")
Call<List<BankBranch>> getBranchListByBank(#Query("api_key") String id);
And the method schould look like this:
Call<List<BankBranch>> response = apiCall.getBranchListByBank(id);
response.enqueue(new Callback<List<BankBranch>>() {
#Override
public void onResponse(Call<List<BankBranch>> call, Response<List<BankBranch>> response) {
List<BankBranch> bankBranch = response.body();
}
#Override
public void onFailure(Call<List<BankBranch>> call, Throwable t) {
}
});
}
make sure Your model BankBranch fit the JSON response;
I use Volley library to make API request to Google Places.
The response is an object like this:
{
"html_attributions": [],
"results": [
{
"address": "Wood Quay, Dublin, Ireland",
"name": "Christ Church Cathedral",
"place_id": "ChIJGw9ASiYMZ0gRy9yiaCZxNZI",
},
{ ... },
{ ... },
],
"status": "OK"
}
Inside the Response.Listener I need to access the "results" array.
I try to get the JSONArray with name "results" as follows:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_URL, null,
new Response.Listener <JSONObject> () {
#Override
public void onResponse(JSONObject response) {
// THE PROBLEM IS HERE - WON'T COMPILE !!!
JSONArray array = response.getJSONArray("results");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//
}
});
But I see an error:
Seems like response.getJSONArray("results"); throws the JSONException. You need to handle that exception by wrapping response.getJSONArray("results"); with a try-catch block.
Something like this:
try {
JSONArray array = response.getJSONArray("results");
} catch (org.json.JSONException exception) {
// handle the exception
}