Is there any way to get data from json url - android

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) {

Related

How to send ArrayList using volley in android?

How to send ArrayList using volley in android,
How to use ArrayList in HashMap?
like Map<String, ArrayList<String> params ;
Finally I got a easiest and perfect solution:
use this dependency:
implementation 'com.google.code.gson:gson:2.8.2'
and use this line
String data = new Gson().toJson(myArrayList);
Now you can pass this string into volley as string parameters like bellow example.
Example:
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
String data = new Gson().toJson(myArrayList);
params.put("keyName", data);
return params;
}
Working for me.
i don't know How to use ArrayList in HashMap?
BUT!!!
for sending ArrayList using volley you can do this
private void sendData(ArrayList list) throws JSONException {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, YOUR_URL, setJsonObject(list)/*This is the function you need*/, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(LogInActivity.this);
requestQueue.add(jsonObjReq);
}
//create json object that contain ArrayList contents
private JSONObject setJsonObject(َArrayList list) throws JSONException {
JSONObject jsonobject_one = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(int i =0 ; i<list.size ; i++) {
JSONObject jsonobject = new JSONObject();
jsonobject .put("param"+i, list.get(i) );
jsonArray.put(jsonobject);
}
jsonobject_one.put("params_array",jsonArray);
return jsonobject_one;
}

How to create a post request in volley android with parameters

I am building an android application that should communicates with the server using volley, it sends the server a request with data in it that should be processed on server and results, sent back.
I am always getting an error from the server, and It's most probably because I couldn't build the request right.
This is the format of the request :
POST API/{RESOURCE}
Content-type: application/json
{
"documents" :
[
{ "image" : "<base64-encoded image>", "type": "id_front or id_back" },
{ "image" : "<base64-encoded image>", "type": "id_front or id_back" }
…
],
"token" : "<access_token_string>"
}
This is how i tried to achieve it, is it right ? I am not sure if the problem is with this code but it's most probable that it's in it.
JSONObject parameters = new JSONObject();
JSONObject[] jsonObjects;
jsonObjects = new JSONObject[1];
try {
Map<String , String> im = new HashMap<>();
im.put("image",imageStringBase64);
im.put("type","id_front");
jsonObjects[0] = new JSONObject(im);
parameters = parameters.put("token", "****");
parameters= parameters.put("documents", jsonObjects);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, API_URL, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
StringBuilder formattedResult = new StringBuilder();
formattedResult.append(response);
Log.d(TAG, "jsonObjectResponse : " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "ErrorResponse called " + "error code: " + error.networkResponse.statusCode);
}
})
{
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
return headers;
}
};
mQueue.add(jsonObjectRequest);
Try building your request like below:
JSONObject requestObj;
try {
requestObj = new JSONObject();
JSONArray arr = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("image", imageStringBase64);
obj1.put("type","id_front");
JSONObject obj2 = new JSONObject();
obj2.put("image", imageStringBase64);
obj2.put("type","id_back");
arr.put(obj1);
arr.put(obj2);
requestObj.put("documents", arr);
requestObj.put("token", "****");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, requestObj,
listener, errorListener);

Recycler View Not Reading Big Volley data with params in android

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();

How to store volley response into HashMap?

i have created HashMap and JsonArrayRequest object as follows. Response is successfully retrieved but HashMap object url_maps size is zero.I want to use for loop in url_maps.
HashMap<String,String> url_maps = new HashMap<String, String>();
// Creating volley request obj for Banner
JsonArrayRequest bannerReq = new JsonArrayRequest(bannerUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(msg, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
url_maps.put("static key", "static value );
} catch (JSONException e) {
e.printStackTrace();
}
}
// 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(msg, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bannerReq);
maybe you can change:
url_maps.put("static key", "static value );
to:
url_maps.put(obj.getString("static key"),obj.getString("static value"));
Try this.
public static void jsonToMap(String t) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jObject = new JSONObject(t);
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ){
String key = (String)keys.next();
String value = jObject.getString(key);
map.put(key, value);
}
System.out.println("json : "+jObject);
System.out.println("map : "+map);
}

Volley POST REQUEST error 500

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"));
}
}

Categories

Resources