I am using volley for parsing. This are the parameters i am passing as post request.
{
"typeName": "MANUFACTURER",
"typeId": 22,
"tempId": 308,
"sortBy": "productname",
"sortOrder": "desc",
"filter":[
{
"filterId":101,
"typeName":"CAT_ID",
"filterId":102,
"typeName":"CAT_ID"
}
]
}
Now the issue is that if I am adding tempId then I am not getting response. but if i remove tempId I am getting proper response. I check my webservice in postman and other tools. There is no issue with Webservice . Can any one help me to solve this issue? There are no any crash log.
public void Productlistcall()
{
showpDialog();
/* Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");*/
Map<String, String> jsonParams = new HashMap<String, String>();
/* object.put("typeName","MANUFACTURER");
object.put("typeId","22");
object.put("tempId","308");
object.put("sortBy","productname");
object.put("sortOrder","desc");*/
if(filter_items!=null)
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
JSONArray array=new JSONArray();
JSONObject obj=new JSONObject();
String filtersepid = null;
System.out.println("FILTER LIST DATA IS NOT NULL");
array.put(obj);
jsonParams.put("filter",obj.toString());
for(int i=0;i<filter_items.size();i++)
{
filtersepid=filter_items.get(i);
System.out.println("filtersepid"+filtersepid);
try {
obj.put("filterId",filter_items.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
try {
obj.put("typeName","CAT_ID");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
System.out.println("FILTER LIST DATA IS NULL");
}
System.out.println("DRAWER PARAMS" + jsonParams);
JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("response Productlist-->> " + response.toString());
productlist = new ArrayList<ProductListModel>();
ch_list = new ArrayList<String>();
color_list=new ArrayList<String>();
try {
JSONObject drawerdatas = (JSONObject) response.getJSONObject("Data");
JSONArray products=drawerdatas.getJSONArray("products");
JSONArray filtersdata=drawerdatas.getJSONArray("filtersList");
JSONArray sortingdata=drawerdatas.getJSONArray("sortingList");
String headerText=drawerdatas.getString("headerText");
String productCount=drawerdatas.getString("productCount");
productlist = new ArrayList<ProductListModel>();
for (int j = 0; j < products.length(); j++) {
JSONObject jo = products.getJSONObject(j);
ProductListModel ch = new ProductListModel();
ch.setProduct_Id(jo.getString("productId"));
ch.setProduct_Name(jo.getString("productName"));
ch.setProduct_Img(jo.getString("productImage"));
ch.setProduct_Price(jo.getString("productSP"));
ch.setProduct_RatingImgPath(jo.getString("productRatingImage"));
ch.setProduct_pRating(jo.getString("productRatingCount"));
/* if(jo.getString("productOfferText").equals("null"))
{
ch_list.add(" ");
System.out.println("text is null");
}
else
{
JSONArray txtdetail=jo.getJSONArray("productOfferText");
System.out.println("txtdetailarray"+txtdetail);
StringBuilder sb = new StringBuilder();
for(int k=0;k<txtdetail.length();k++)
{
JSONObject jdetail=txtdetail.getJSONObject(k);
disptext=jdetail.getString("displayText");
dispclr=jdetail.getString("displayColor");
//ch_list.add(disptext);
color_list.add(dispclr);
// sb.append(disptext);
System.out.println("clr" + color_list.get(k).toString());
colors=color_list.get(k);
String string = colors;
String[] parts = string.split("\\*");
int part1 = Integer.parseInt(parts[0]);
int part2 = Integer.parseInt(parts[1]);
int part3 = Integer.parseInt(parts[2]);
hex = String.format("#%02X%02X%02X", part1, part2, part3);
sb.append(addColor(disptext.trim(), hex));
System.out.println("hexa"+hex);
}
detailtext=sb.toString();
ch_list.add(detailtext);
System.out.println("Output: " + sb.toString().replaceAll("\\\\n", "\n"));
}
*/
productlist.add(ch);
}
filterlist = new ArrayList<ModelUser>();
for(int c=0;c<filtersdata.length();c++)
{
JSONObject jo = filtersdata.getJSONObject(c);
JSONArray filters=jo.getJSONArray("filters");
String groupName=jo.getString("groupName");
String typeName=jo.getString("typeName");
for(int g=0;g<filters.length();g++)
{
JSONObject jos = filters.getJSONObject(g);
ModelUser flm = new ModelUser();
flm.setId(Integer.parseInt(jos.getString("filterId")));
flm.setUserName(jos.getString("filterName"));
filterlist.add(flm);
}
}
sortlist=new ArrayList<SortingListModel>();
for(int d=0;d<sortingdata.length();d++)
{
JSONObject jo = sortingdata.getJSONObject(d);
SortingListModel scm = new SortingListModel();
scm.setSort_text(jo.getString("text"));
scm.setSort_value(jo.getString("value"));
sortlist.add(scm);
}
rvAdapter = new RecyclerViewAdapter(getActivity(),productlist);
recyclerView.setAdapter(rvAdapter);
pronames.setText(headerText);
if(productlist.size() < 2)
{
procounts.setText(String.valueOf(productlist.size() + " Product"));
}
else
{
procounts.setText(String.valueOf(productlist.size() + " Products"));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Handle Error
hidepDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("API_Version","1.0");
headers.put("deviceName","ANDROID");
return headers;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
}
You are using this
jsonParams.put("tempId","308");
Try this
jsonParams.put("cityId","308");
Rearrange and use below code in the if else condition. You are not generating json in right order
if(filter_items!=null)
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
JSONArray array=new JSONArray();
String filtersepid = null;
System.out.println("FILTER LIST DATA IS NOT NULL");
for(int i=0;i<filter_items.size();i++)
{
JSONObject obj=new JSONObject();
filtersepid=filter_items.get(i);
System.out.println("filtersepid"+filtersepid);
try {
obj.put("filterId",filter_items.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
try {
obj.put("typeName","CAT_ID");
} catch (JSONException e) {
e.printStackTrace();
}
array.put(obj);
}
jsonParams.put("filter",array);
}
else
{
jsonParams.put("typeName", "MANUFACTURER");
jsonParams.put("typeId", "22");
jsonParams.put("tempId","308");
jsonParams.put("sortBy", "productname");
jsonParams.put("sortOrder", "desc");
System.out.println("FILTER LIST DATA IS NULL");
}
I solved it with the use of
compile 'com.android.volley:volley:1.0.0'
I was using this one
compile 'com.mcxiaoke.volley:library:1.0.19'
Related
I created the functions like the json file in the picture. When I send a post request, the response is "Unexpected response code 500" for. I think the problem is caused by json arrays, I don't understand exactly why this error is coming. Server url works fine, successfully post on swift. Thanks
json_array_requested_from_me
private void CreditCardParams(Map<String, String> requestParameters) {
JSONArray creditCardItems = new JSONArray();
JSONObject item_creditCardItems = new JSONObject();
try {
item_creditCardItems.put("CC_NUMBER", "1111");
item_creditCardItems.put("EXP_MONTH", “11”);
item_creditCardItems.put("EXP_YEAR", “1111");
item_creditCardItems.put("CC_CVV", “111”);
item_creditCardItems.put("CC_OWNER", “TEST USER”);
item_creditCardItems.put("INSTALLMENT_NUMBER", "1");
} catch (JSONException e) {
e.printStackTrace();
}
creditCardItems.put(item_creditCardItems);
requestParameters.put("CreditCard", (creditCardItems.toString()));
}
private void CustomerParams(Map<String, String> requestParameters) {
JSONArray CustomerItems = new JSONArray();
JSONObject item_Customer = new JSONObject();
try {
item_Customer.put("FIRST_NAME", "Firstname");
item_Customer.put("LAST_NAME", "Lastname");
item_Customer.put("MAIL", "test#test.com");
item_Customer.put("PHONE", "+11111111");
item_Customer.put("CITY", "Test");
item_Customer.put("STATE", "Test");
item_Customer.put("ADDRESS", "Test");
item_Customer.put("CLIENT_IP", "111.11.11.11”);
} catch (JSONException e) {
e.printStackTrace();
}
CustomerItems.put(item_Customer);
requestParameters.put("Customer", (CustomerItems.toString()));
}
private void ProductParams(Map<String, String> requestParameters) {
JSONArray ProductItems = new JSONArray();
JSONObject item_Product = new JSONObject();
try {
item_Product.put("PRODUCT_ID", "1");
item_Product.put("PRODUCT_NAME", “1”);
item_Product.put("PRODUCT_CATEGORY", “Elec.”);
item_Product.put("PRODUCT_DESCRIPTION", “Info”);
item_Product.put("PRODUCT_AMOUNT", 15.00);
} catch (JSONException e) {
e.printStackTrace();
}
ProductItems.put(item_Product);
requestParameters.put("Product", (ProductItems.toString()));
}
private void ConfigParams(Map<String, String> requestParameters) {
JSONArray configItems = new JSONArray();
JSONObject item = new JSONObject();
try {
item.put("MERCHANT", "TEST1234");
item.put("MERCHANT_KEY", “123”);
item.put("BACK_URL", "localhost");
item.put("PRICES_CURRENCY", "USD");
item.put("ORDER_REF_NUMBER", "RFN0001");
item.put("ORDER_AMOUNT", 15.00);
} catch (JSONException e) {
e.printStackTrace();
}
configItems.put(item);
requestParameters.put("Config", (configItems.toString()));
}
private void post_func(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
}
){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String,String>();
CreditCardParams(params);
CustomerParams(params);
ProductParams(params);
ConfigParams(params);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
As you know, 500 server error is an error caused by an exception in the server. If you don't get an error when you send the JSON file you showed from an http request sender program like postman, the problem is in the JSON object you sent to the server.
I'm using JSONObject to parse the JSON file and get its contents. Everything goes fine but tags aren't showing in the RecyclerView.
Here's the code :
private void direct_url(){
v_title = findViewById(R.id.vid_title);
String url = kw_url_holder.getText().toString();
String server_tag_url = "https://server.com/json.json";
StringRequest request = new StringRequest(Request.Method.GET, server_tag_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
String title,views,likes,dislikes,publishedon,duration;
JSONObject object=new JSONObject(response);
title = object.getString("title");
v_title.setText(title);
JSONArray tagsJsonArray = object.getJSONArray("tags");
for(int i=0; i<tagsJsonArray.length();i++){
try {
JSONObject tagObj = new JSONObject();
tagObj = tagsJsonArray.getJSONObject(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tagObj.getString(String.valueOf(i)));
url_result.add(tagUrlResultsModel);
}catch (JSONException e){
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
url_queue = Volley.newRequestQueue(tags.this);
url_queue.add(request);
}
The JSON:
{
"title": "The Title",
"tags": ["tag1", "tag2"]
}
An error in the logs:
Error: java.lang.String cannot be converted to JSONObject
The problem is inside your for loop in:
JSONObject tagObj = new JSONObject();
tagObj = tagsJsonArray.getJSONObject(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tagObj.getString(String.valueOf(i)));
url_result.add(tagUrlResultsModel);
It should be
String tag;
tag = tagsJsonArray.getString(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tag);
url_result.add(tagUrlResultsModel);
Using getString() instead of getJSONObject() as the content of that JSONArray is just strings.
That's why you are getting in that catch:
Error: java.lang.String cannot be converted to JSONObject
So I am beginning programming Java Android and I'm trying to parse a JSON string that I created. So, I want to parse it to a ListView and I need people to help me.
My experimental JSON file:
[
{
"HoTen":" Nguy\u1ec5n V\u0103n A",
"NamSinh":1999,
"DiaChi":"H\u00e0 N\u1ed9i"
},
{+},
{+},
{+},
{+},
{+},
{+},
{+},
{+}
]
My code but it not working:
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
JSONObject jsonObject = new JSONObject(s);
for (int i =0;i<=jsonObject.length();i++)
{
JSONObject object = jsonArray.getJSONObject(i);
//HoTen.getString("HoTen");
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
Hope this will help you
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
ArrayList<String> mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
//HoTen.getString("HoTen");
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
String result = String.format("HoTen: %s, NamSinh: %s, DiaChi: %s",
HoTen, NamSinh, DiaChi);
mangLV.add(result);
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
It doesn't seem like you're using your JSONObject jsonObject = new JSONObject(s);. Your for should be for(int i = 0; i<=jsonArray.length();i++), thus making your jsonObject obsolete. Also, you're passing your adapter an empty list! You never add anything to your mangLV list.
Try out this code:
protected void onPostExecute(String s) {
//Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
try {
mangLV = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(s);
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String HoTen = object.getString("HoTen");
int NamSinh = object.getInt("NamSinh");
String DiaChi = object.getString("DiaChi");
String result = "HoTen " + HoTen + " | NamSinh " + NamSinh + " | DiaChi " + DiaChi;
mangLV.add(result); //After fetching the values, add the objects to your list
}
ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mangLV);
lvSinhVien.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
This should add to your ListView objects that look like this:
HoTen Nguy\u1ec5n V\u0103n A | NamSinh 1999 | DiaChi H\u00e0 N\u1ed9i
I'm new in JSON, but I try to use all answers and didn't work. Help please, what I doing wrong.
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
editText.setText(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray resultArray = jsonObject.getJSONArray("query");
addresses = new ArrayList<String>();
for (int i = 0; i<resultArray.length(); i++){
addresses.add(resultArray.getJSONObject(i).getString("Name"));
Log.d("DTA",resultArray.getJSONObject(i).getString("Name"));
}
refreshAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
It's my JSON for parsing.
{
"query":{
"count":2,
"created":"2016-10-04T19:50:08Z",
"lang":"ru",
"results":{
"rate":[
{
"id":"USDRUB",
"Name":"USD/RUB",
"Rate":"62.8240",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"62.8416",
"Bid":"62.8240"
},
{
"id":"EURRUB",
"Name":"EUR/RUB",
"Rate":"70.3460",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"70.3740",
"Bid":"70.3460"
}
]
}
}
}
That's because query is not an array, it is an object. I guess you want to get the objects from rate, this is how to do it:
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject resultsObject = jsonObject.getJSONObject("results");
JSONArray resultArray = resultsObject.getJSONArray("rate");
... etc... now iterate
I am trying to parse a JSONArray into and ArrayList in my android app. The PHP script correctly retuns the expected results, however the Java fails with a null pointer exception at resultsList.add(map)
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = (JSONObject) json.get(i);
//Fill map
Iterator iter = c.keys();
while(iter.hasNext()) {
String currentKey = (String) iter.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
try like this may help you,
public void agencySearch(String tsearch) {
// Setting the URL for the Search by Town
String url_search_agency = "http://www.infinitycodeservices.com/get_agency_by_city.php";
// Building parameters for the search
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("City", tsearch));
// Getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url_search_agency, params);
ArrayList<HashMap<String, String>> resultsList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < json.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
try {
JSONObject c = json.getJSONObject(position);
//Fill map
Iterator<String> iter = c.keys();
while(iter.hasNext()) {
String currentKey = it.next();
map.put(currentKey, c.getString(currentKey));
}
resultsList.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
};
MainActivity.setResultsList(resultsList);
}
Use custom method which convert your JSONArray to List instead of iterate and build List.
How to call :
try {
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>) toList(json);
} catch (JSONException e) {
e.printStackTrace();
}
Convert json array to List :
private List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
Convert json to Object :
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
Convert json to map :
public Map<String, String> jsonToMap(JSONObject object) throws JSONException {
Map<String, String> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)).toString());
}
return map;
}