I am using volley to receive the data from a data source, the problem is with the recycler view if I do something on a query like adding parameters it does not work. It there is any problem with the Volley?
public void getting locations() {
String url = "URL REMOVED";
RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // this = context
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject status = null;
try {
JSONObject jObj = new JSONObject(String.valueOf(response));
JSONArray jr = jObj.getJSONArray("products");
for(int i=0;i<jr.length();i++)
{
JSONObject jb1 = jr.getJSONObject(i);
String title = jb1.getString("title");
Log.d("Title",""+title);
String img = jb1.getString("featured_src");
JSONArray a = jb1.getJSONArray("categories");
String category = "";
lstBook.add(new Book(title,"rAJA","Description book",img));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("EROOOOOOOOOOOOOOOOOOOOOR", "Error: " + error.getMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjReq);
}
The problem is if the URL is products it will show the data otherwise it will not.
Declare myAdapter as a private variable and change the code as mentioned below.
Add the line myAdapter.notifyDataSetChanged(); after lstBook.add(new Book(title,"rAJA","Description book",img)); and myrv.setAdapter(myAdapter);
for(int i=0;i<jr.length();i++)
{
JSONObject jb1 = jr.getJSONObject(i);
String title = jb1.getString("title");
String img = jb1.getString("featured_src");
JSONArray a = jb1.getJSONArray("categories");
String category = "";
lstBook.add(new Book(title,"rAJA","Description book",img));
myAdapter.notifyDataSetChanged();
}
and
myAdapter = new RecyclerViewAdapter(this,lstBook);
myrv.setLayoutManager(new GridLayoutManager(this,2));
myrv.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
Related
I'm working on android and I'm trying to parse json data from url to get the string from array.
I have tried using volley but i'm not getting the expected result.
{
code: 200,
status: "OK",
data: [
{
timings: {
Fajr: "04:13 (+04)",
Sunrise: "05:36 (+04)",
Dhuhr: "12:14 (+04)",
Asr: "15:42 (+04)",
Sunset: "18:51 (+04)",
Maghrib: "18:51 (+04)",
Isha: "20:15 (+04)",
Imsak: "04:03 (+04)",
Midnight: "00:14 (+04)"
},
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
//JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject o = jsonArray.getJSONObject(i);
ModelActivity modelActivity = new ModelActivity(
o.getString("Fajr")
o.getString("Dhuhr"),
o.getString("Asr"),
o.getString("Maghrib"),
o.getString("Isha")
);
modelActivityList.add(modelActivity);
}
I want fajr dhuhr asr magrhrib isha timings
any help will be appreciated
If your request returns the posted JSON then the problem is not volley library that does the request but the way you try to parse it.
In the JSON representation the {} mean that you have an object.
And the [] that there is an array.
So you should check at the first json object for the data element and then in this array for each object look for the timings and then the items.
Although I haven't compiled or run the code the parsing should be something like the following:
JSONObject jsonObject = new JSONObject(response);
JSONArray data = jsonObject.getJSONObject("data");
for(int j=0; j<data.length(); j++){
JSONObject jObj = data.getJSONObject(j);
JSONArray jsonArrayTimings = new JSONArray(jObj.getJSONObject("timings"));
for(int i=0; i<jsonArray.length(); i++){
JSONObject o = jsonArray.getJSONObject(i);
ModelActivity modelActivity = new ModelActivity(
o.getString("Fajr")
o.getString("Dhuhr"),
o.getString("Asr"),
o.getString("Maghrib"),
o.getString("Isha")
);
modelActivityList.add(modelActivity);
}
}
For extra details on json parsing you should go through this link
You should be using the JsonObjectRequest instead of the StringRequest. Here is an example:
public void getRate(String tripDate) {
Rate = 0.54;
String url = "https://myserver/api/rates/" + tripDate;
JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.GET,url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// since response is a JSONObject use getJSONArray to
// get the JSONArray out of the JSONObject
JSONArray rates = response.getJSONArray("rates");
} catch (Exception e) {
e.printStackTrace();
Rate = 0.54;
Log.i("Test", "Default Rate:" + Rate);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Test", "Response Error: " + error.getLocalizedMessage());
Rate = 0.54;
Log.i("Test", "Default Rate:" + Rate);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String authValue = "Bearer ";
headers.put("Authorization", authValue);
headers.put("Accept", "application/json; charset=utf-8");
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
MyApplication.getInstance().addToRequestQueue(postRequest);
}
If your API returns a JSONArray, then you could use the JSONArrayRequest instead...
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
Request.Method.GET,
mJSONURLString,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
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);
}
Android Code:
private void registerUser(){
final String username = "subrata";
final String password = "banerjee";
final String email = "test_email";
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERNAME,username);
params.put(KEY_PASSWORD,password);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm trying to send http request using Android Volley to my node.js server (expressjs). Its hitting the server and getting the response but when I'm printing the req.body in node.js its shows {} (empty). I'm new to Android and unable to figure out the reason. Please someone guide me.
Call this method in OnResponse GetResponse(response);
And the method will be
private void GetResponse(String res){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(res);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String temp = jo.getString("what_ever");
String temp1 = jo.getString("what_ever_1");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This will get you the response in String format fetched from json.
private void registerUser(){
JSONObject jsonBodyObj = new JSONObject();
try{
jsonBodyObj.put("mAtt", "+1");
jsonBodyObj.put("mDatum","+2");
jsonBodyObj.put("mRID","+3");
jsonBodyObj.put("mVon","+4");
}catch (JSONException e){
e.printStackTrace();
}
final String requestBody = jsonBodyObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
return headers;
}
#Override
public byte[] getBody() {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
requestBody, "utf-8");
return null;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
i am using volley library for post data over api...in here the Content-Type is "application/json" ....
how can i implement this type of json data :
URL: Base_URL + dorequisition
{
"submitted_by_employee_id": 1,
"name": "Technolive SF for TC",
"bags_thana_wise": [
{
"tiger": "10000",
"extreme": "5000",
"opc": "3000",
"three_rings": "4000",
"buffalo_head": "2000",
},
],
"free_bag": "500",
"landing_price": "450",
"transport_cost_ex_factory_rate": "450",
"amount_taka": "four hundred fifty",
"bank_name": "IFIC Bank Limited",
"delivery_point": "Banani",
"upto_today": "450",
"bag_type": "swing",
"remark": "Good Cement",
"token": "2cbf1cefb6fe93673565ed2a0b2fd1a1"
}
api implementation sample :
public void APIRetailVisitInfo() {
for (int i = 0; i < retailVisitInfoList.size(); i++) {
System.out.println("token id:::" + token + " :::"+employee_id);
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("submitted_by_employee_id", employee_id);
jsonParams.put("retailer_name", retailVisitInfoList.get(i).getRetails_name());
jsonParams.put("retailer_phone", retailVisitInfoList.get(i).getRetailer_contact_no());
jsonParams.put("retailer_address", retailVisitInfoList.get(i).getRetails_address());
jsonParams.put("remarks", retailVisitInfoList.get(i).getRemarks());
jsonParams.put("token", token);
JsonObjectRequest myRequest = new JsonObjectRequest(
Request.Method.POST,
"http://technolive.co/retailvisitinfo",
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
code = response.getString("code");
//token = response.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
if (code.equals("200")) {
System.out.println("APICompetetorBasedOnMArketPrice:::" + code + " :::");
}
// System.out.println("token:::" + token+" :::");*/
// verificationSuccess(response);
System.out.println("APICompetetorBasedOnMArketPrice:::" + response + " :::");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// verificationFailed(error);
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = token;
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", "My useragent");
// headers.put("Authorization", auth);
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(RetailVisitInfoActivity.this);
requestQueue.add(myRequest);
// MyApplication.getInstance().addToRequestQueue(myRequest, "tag");
}
}
can anyone help me please........
It is rather simple. First let's start with bags_thana_wise. bags_thana_wise is a JSONArray. It contains one object. So lets create the object.
JSONObject json1 = new JSONObject();
json1.put("tiger","10000";
json1.put("extreme","5000";
and so on..Now put this json object into an array
JSONArray jsonArray = new JSONArray();
jsonArray.put(json1);
Now just add this array and other values to another json object
JSONObject finalObject = new JSONObject();
finalObject.put("submitted_by_employee_id","1");
finalObject.put("name","Technolive SF for TC");
//put the jsonArray
finalObject.put("bags_thana_wise",jsonArray);
finalObject.put("free_bag","500");
.
.
.
finalObject.put("token","2cbf1cefb6fe93673565ed2a0b2fd1a1");
Now make the following volley request
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
myURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Handle response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PopupActivity.this,"Can not reach server",Toast.LENGTH_LONG).show();
}
}){
#Override
public String getBodyContentType(){
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() {
try {
return finalObject == null ? null: finalObject.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
};
RequestQueue requestQueue = Volley.newRequestQueue(RetailVisitInfoActivity.this);
requestQueue.add(jsonRequest);
JSON:
{
"isRegistrationSuccess":"true"
}
This what my backend should provide while user successfully register in system. I am sending Name, Email and Password as parameters. I am getting 500 error.
/Volley: [188] BasicNetwork.performRequest: Unexpected response code 500 for http://100.100.202.200/mobile/register?name=admin&email=admin#nomail.com&password=admin123
Although, I can see the user information in my backend. Here is my code:
RequestQueue queue = Volley.newRequestQueue(this);
String url_to_parse = getLink(name,email,password).trim();
StringRequest stringReq = new StringRequest(Request.Method.POST, url_to_parse, new Response.Listener<String>() {
#Override
public void onResponse(String response){
try{
Log.d("Response",response);
JSONArray obj = new JSONArray();
boolean isLoginSuccess = Boolean.parseBoolean(obj.getString(0));
if(isLoginSuccess){
onSignupSuccess();
}else{
onSignupFailed();
}
}catch (JSONException e){
e.printStackTrace();
onSignupFailed();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
onSignupFailed();
Log.e("Error",String.valueOf(error.getMessage()));
}
});
queue.add(stringReq);
I am not sure what is wrong I am doing here? How can I solve it?
POST data is given in a protected Map getParams () and not the URL:
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("parametr1","value1");
params.put("parametr2","value2");
params.put("parametr3","value3");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
Fix your url and use JsonObjectRequest
You want to parse a array into a boolean, you have to loop through the array like this:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray= jsonObject.getJSONArray("example");
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
boolean isLoginSuccess = Boolean.parseBoolean(jo.getString("exampleString"));
}
}