How to store volley response into HashMap? - android

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

Related

Adding volley response to global variables

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

Is there any way to get data from json url

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

How to send array in params in volley in android

I want to pass data using volley API to server. The parameters be like :
Request:
{
"user_id" : 6,
"package_name": "Personal Package",
"care_type" : ["help in shopping", "Personal care"],
"care_delivered" : "as day care",
"gender" : "F",
"experience" : "4,0",
"skills":"very helpful , caring, etc",
"start_date" : "2018-09-12",
"price": "200-700, day",
"description": "test"
}
In this care_type is an array type. I have done code to send data but each time I am getting error i.e.
onErrorResponse: Error: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
My Code for API is :
private void createPackageApi() {
String tag_json_obj = "json_obj_req";
String url = Constants.CREATE_PACKAGE;
pBar.setVisibility(View.VISIBLE);
Activity activity = getActivity();
if (activity != null && isAdded()) {
sessionManager = new SessionManager(activity);
}
final HashMap<String, String> packageDetail = sessionManager.getPackageDetail();
JSONArray jsonArray;
try {
jsonArray = new JSONArray(required_support_need);
strArr = new String[jsonArray.length()];
Log.e("tag", "package" + required_support_need + " " + strArr);
for (int i = 0; i < jsonArray.length(); i++) {
strArr[i] = "\"" + jsonArray.getString(i) + "\"";
Log.e("TAG", "getInitializedID:String " + strArr[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
final HashMap<String, String> registrationDetail = sessionManager.getSeekerRegistrationDetail();
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", "2");
params.put("package_name", edtPackageNames.getText().toString());
params.put("care_type", Arrays.toString(strArr));
params.put("care_delivered", edtCarePackages.getText().toString());
params.put("gender", edtPreferredGender.getText().toString());
params.put("experience", edtPackageNames.getText().toString());
params.put("skills", edtEssentialSkills.getText().toString());
params.put("start_date", packageDetail.get("start_date"));
params.put("price", edtPackageValue.getText().toString());
params.put("description", edtPackageDescription.getText().toString());
Log.e("TAG", "seekerPackage: " + params);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("package_detail_response", response.toString());
Gson gson = new Gson();
try {
if (response.has("success")) {
CreatePackage createPackage;
createPackage = gson.fromJson(response.toString(), CreatePackage.class);
String status = createPackage.getSuccess();
if (status.equals("success")) {
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(getActivity(), R.string.package_created, Toast.LENGTH_LONG).show();
}
}
pBar.setVisibility(View.GONE);
} else {
ResponseError responseError;
responseError = gson.fromJson(response.toString(), ResponseError.class);
String msg = responseError.getMessage();
Log.e("TAG", "msg " + msg);
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pBar.setVisibility(View.GONE);
VolleyLog.e("Error: " + error.getMessage());
// handle error
}
}) {
#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("Authorization", "Bearer " + registrationDetail.get("api_token"));
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
I have tried to send array in parameters but I am not getting success. Please tell me how to send array in single parameter in volley library.
To post array use below code
JSONArray care_type = new JSONArray();
for(int i=0; i < yourarray.length(); i++) {
care_type.put(yourarray[i]); // create array and add items into that
}
params.put("care_type",care_type.toString());
Add your array in JSONArray and sent it to with the key name
JSONArray dataObject = new JSONArray(filterListing);
paramObject.put("data",dataObject);
Use :
HashMap<String ,String> params=new HashMap<String, String>();
for(int i=1;i<=parms.size;i++){
params.put("params_"+i, arr[i]);
}
Use JJSONArray to send Values .
JSONArray jsonObject=new JSONArray();
for(int i=1;i<=size;i++)
{
arr[i]="userId_"+i+"_"+"ans_"+i;
jsonObject.put("params_"+i,arr[i]);
}
HashMap<String ,String> params=new HashMap<String, String>();
params.put("params",jsonObject.toString());
TO send all values on server side get params and convert to JSON object and iterate to get all values

How to update json data using volley method on Android?

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

Hi, I have issue in my Volley post method

I want to post the data as json formatted,but i dont know how to do that please help me to solve this issue.Normally i use the Volley post method as below (Its not any formatted type),its perfectly working for me,but now my backend developer ask me to post details as json format.
String url=" http://10.10.4.27/teacherapp_dxb/index.php/teacher_app_cn/login?user_id=EMP263&password=thanzeel";
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
}
else {
// order error
String responseMsg = jObj.getString("response");
Toast.makeText(Viewactivity.this,
"ooola kirane"+ responseMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Viewactivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Post product to orderplacing url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id,"EMP263")
params.put("password","thanzeel");
return params;
}
};
// Adding request to queue
AppController.getInstance().addToRequestQueue(strReq);
}
In the above code i send the data wit out any format,but the backend developer need get the data as json format.So please help me to solve this issue.
You can do it like below in your getParams()
Map<String, String> params = new HashMap<String, String>();
params.put("user_id","EMP263");
params.put("password","thanzeel");
JSONObject jsonObjectParam = new JSONObject(params);
Map<String,String > postParams = new HashMap<>();
postParams.put("key",""+jsonObjectParam);
you can ask for this "key" to your backend team.
Hope it helps!
If you want to send data in JSONArray from android app try this way :
public String makeJSON(String s1,String s2,String s3){
JSONArray jsonArray = new JSONArray();
JSONObject data = new JSONObject();
try {
data.put("dataparam1",s1);
data.put("dataparam2", s2);
data.put("dataparam3", s3);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(data);
JSONObject jsonData = new JSONObject();
try {
jsonData.put("dataArray", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String jsonStr = jsonData.toString();
System.out.println("jsonString: "+jsonStr);
return jsonStr;
}
And if you just want to send data in JSONObject try this :
public String createjson(String s1,String s2,String s3)
{
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
jsonObj.put("dataparam1",s1);
jsonObj.put("dataparam2",s2);
jsonObj.put("dataparam3",s3);
jsonArr.put(jsonObj);
jsonObject.put("cartItems", jsonArr);
} catch (JSONException e) {}
return jsonObject.toString();
}

Categories

Resources