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;
}
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) {
Hi am new to android am trying to pass a json response to arraylist using jsonarray request but i am getting this error :
Error:
volley error org.json.JSONException: Value < br of type java.lang.String cannot be converted to JSONArray
Php code:
$userid=$_POST["userid"];
$semester=$_POST["semester"];
$level=$_POST["level"];
$stmt="SELECT coursecode,coursetitle,grade,credithrs,marks FROM tblresults WHERE userid = '$userid' and semester = '$semester' and level = '$level'";
$result=mysqli_query($conn,$stmt);
$responsea=array();
while($respons=mysqli_fetch_array($result)){
$response["coursecode"]=$respons['coursecode'];
$response["coursetitle"]=$respons['coursetitle'];
$response["grade"]=$respons['grade'];
$response["credithrs"]=$respons['credithrs'];
$response["marks"]=$respons['marks'];
$responsea[]=$response;
}
echo json_encode($responsea);
Php response:
[{"coursecode":"csc234","coursetitle":"Information Security","grade":"A","credithrs":"3","marks":"80.00"},{"coursecode":"csc300","coursetitle":"Cryptography","grade":"B","credithrs":"3","marks":"65.00"}]
android code:
public ArrayList<resultInstance> extractresult() {
CheckResultFragment checkResultFragment=new CheckResultFragment();
final String gsem=checkResultFragment.gsem;
final String glev=checkResultFragment.glev;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, jsonurl, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int i=0;
while (i<response.length()){
try {
JSONObject jsonObject=response.getJSONObject(i);
resultInstance resultinstance =new resultInstance(
jsonObject.getString("coursecode"),
jsonObject.getString("coursetitle"),
jsonObject.getInt("credit"),
jsonObject.getDouble("marks"),
jsonObject.getString("grade"));
results.add(resultinstance);
i++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("userid",guid);
params.put("level",glev);
params.put("semester",gsem);
return params;
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return results;
}
Any Help will be greatly appreciated!!
Do debug and set breakpoints, your API call php response is not in a format of JSONArray. Send proper JSONArray format as a response to the API call request.
I wanna send a notification using Volley to FCM.
The method expects to get the message information under "data".
The problem is that when i use "put" in volley - like here:
JSONObject notificationTitleObject = new JSONObject().put("message_title",notificationTitle);
The line above is deleted from "data".
I have tried to use JsonArray and then putting it as the value of "data".
It didn't work.
If I was writing the desirable result in Json, it will look like that:
{ "data": {
"message_title": "XXXX",
"message": "XXXXX"
"message_image_url": "XXX"
},
"to" : "/topics/Notifications_For_Event_Items"
}
The full code is here:
private void sendNotifToServer() throws JSONException {
rootObject = new JSONObject();
JSONObject notificationTitleObject = new JSONObject().put("message_title",notificationTitle);
JSONObject notificationMessageObject = new JSONObject().put("message",itemName.getText().toString());
JSONObject notificationImageObject = new JSONObject().put("message_image_url",imageUrl);
try {
rootObject.put("to","/topics/Notifications_For_Event_Items");
rootObject.put("data",notificationTitleObject);
rootObject.put("data",notificationMessageObject);
rootObject.put("data",notificationImageObject);
// rootObject.put("data",new JSONObject().put("fragmentType","1"));
}catch (JSONException e){
e.printStackTrace();
}
RequestQueue queue = Volley.newRequestQueue(AddEventItemsActivity.this);
StringRequest request = new StringRequest(Request.Method.POST, notificationUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return rootObject.toString().getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type","application/json");
headers.put("Authorization","key="+notifApiKey);
return headers;
}
};
I think the correct JSONObject is the following:
rootObject = new JSONObject();
JSONObject dataObject = new JSONObject();
dataObject.put("message_title", notificationTitle);
dataObject.put("message", itemName.getText().toString());
dataObject.put("message_image_url", imageUrl);
rootObject.put("data", dataObject);
rootObject.put("to","/topics/Notifications_For_Event_Items");
The Android code is not sending the parameters when using JsonArrayRequest.
If I use StringRequest instead of JsonArrayRequest how do I convert the response from String to JSONObject to display it in a RecyclerView?
Intent intent = getIntent();
final String userID = intent.getExtras().getString("userID");
recyclerView = (RecyclerView)findViewById(R.id.display_expenses_recycler_view_id);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, expensesDisplay_url, (String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
Log.i("Response", String.valueOf(response));
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
ExpensesDetails expensesDetails = new ExpensesDetails(jsonObject.getString("Expenses"),
jsonObject.getString("Description"), jsonObject.getString("datetime"));
arrayList.add(expensesDetails);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayExpenses.this, "Error", Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", userID);
return params;
}
};
Log.i("Array", String.valueOf(arrayList));
MySingleton.getMyInstance(DisplayExpenses.this).addToRequestQueue(jsonArrayRequest);
adapter = new RecyclerAdapterExpenses(arrayList);
recyclerView.setAdapter(adapter);View.setAdapter(adapter);
This is the result sent from the server:
[
{
"Expenses":"0",
"Description":"car",
"datetime":"2016-10-25 21:10:57"
},
{
"Expenses":"2000",
"Description":"Car",
"datetime":"2016-10-25 21:46:05"
},
{
"Expenses":"5000",
"Description":"House payment",
"datetime":"2016-10-25 21:47:11"
},
{
"Expenses":"200",
"Description":"",
"datetime":"2016-10-26 20:51:42"
},
{
"Expenses":"500",
"Description":"",
"datetime":"2016-10-26 23:55:21"
}
]
Are you sure the user ID isn't being given? You have an empty RecyclerView until the Volley request finishes. And your Log.i statement happens before Volley completes, so you'll see an empty list...
You need an adapter.notifyDataSetChanged() within the onResponse call after the while loop to tell the adapter to display the data you added.
Not too sure what View is here... but you likely don't need the same adapter on two views.
recyclerView.setAdapter(adapter);View.setAdapter(adapter);
if i tried to use StringRequest instead of JsonArrayRequest how will i convert the string response from String to JSONObject to display them in a RecyclerView
You have a String response from onResponse, so use the constructor for JSONArray that takes a String.
JSONArray array = new JSONArray(response);
Note: that requires a try-catch.
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"));
}
}