I want to make 7 JSON Requests in one single activity. Is there any way to do it?
If there is any way to achieve it using volley?
You can run parallel JSONObjectRequests by setting their tags. For example lets say you want to send requests using loop. You will do something like following:
for (int i = 0; i < requestSize; i++)
{
StringRequest request = new StringRequest(Request.Method.POST,
AppUrls.URL_SAVE_SAVE_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String status = "";
JSONObject json = null;
try {
json = new JSONObject(response);
if(json != null && json.has(JSONParsor.STATUS))
status = json.getString(JSONParsor.STATUS);
if(status != null && status.length() > 0 && status.equalsIgnoreCase("success"))
{
}
else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(JSONParsor.DATA_STRING, jsonObject.toString());
return params;
}
};
request.setTag("TAG_" + i);
addToRequestQueue(request);
}
In response, you can return the request id and then you can match, which request belongs to which tag.
Hope this helps.
Related
I want to send some bulk data to my php server so I constructed JSON Array. But how to send it using volley in Android. Could you anybody help. I already tried many ways but didnt work.
Below is my code for the dataset
JSONArray jsData = new JSONArray();
JSONObject others = new JSONObject();
while(crsrallansr.isAfterLast() == false) {
JSONObject Inner = new JSONObject();
try {
Inner.put("qid",crsrallansr.getString(crsrallansr.getColumnIndex("qid")));
Inner.put("qstn",crsrallansr.getString(crsrallansr.getColumnIndex("qid")));
Inner.put("result",crsrallansr.getString(crsrallansr.getColumnIndex("qid")));
} catch (JSONException e) {
e.printStackTrace();
}
jsData.put(Inner);
crsrallansr.moveToNext();
xx++;
}
Fixed the problem using StringRequest like :
reqPostanswers = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("posting info :",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.i("posting error :",error.toString());
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("user", thisuser);
params.put("answers",jsData.toString());
params.put("lickey","1761");
return params;
}
};
answerpostQueue = Volley.newRequestQueue(getApplicationContext());
answerpostQueue.add(reqPostanswers);
At the server side ( php ); the code is as follows :
$answers=json_decode($_POST['answers']);
foreach ($answers as $answer) {
$answer=json_encode($answer);
echo $answer;
$answer=json_decode($answer);
$uname=$_POST['user'];
$qid=$answer->qid;
$result=$answer->result;
$qstn=$answer->qstn;
I am using Volley for networking and connect to my REST API. The following code shows the onCreate method of my MainActivity. Here I want to make a GET request to my url and receive the JSON information. But it's not working. I made different debug points all over the code. The last thing which is executed is the initialization of the arrReq. onResponse and onErrorResponse are not executed and I don't know what is the matter.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupToolBar();
setupPagerAdapter();
setupFloatingButton();
getDeviceId();
JsonArrayRequest arrReq = new JsonArrayRequest(com.android.volley.Request.Method.GET, "http://localhost:8888/api/entities", null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Check the length of our response (to see if there are any entities)
if (response.length() > 0) {
// There are entities so let's loop through them all.
for (int i = 0; i < response.length(); i++) {
try {
// Get each entity
JSONObject jsonObj = response.getJSONObject(i);
String locData = jsonObj.get("entity").toString();
} catch (JSONException e) {
// If there is an error then output this to the logs.
Log.e("Volley", "Invalid JSON Object.");
}
}
} else {
// There aren't any entities. So do nothing!
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// If there a HTTP error then add a note to our list.
Log.e("Volley", error.toString());
}
}
);
}
When I execute the url in my browser on my device the JSON code is received:
{
"status":"success",
"data":[
{
"entity":"(17,)"
},
{
"entity":"(21,)"
},
{
"entity":"(201,)"
}
],
"message":"Retrieved entities"
}
The log does not show any error.
JsonArrayRequest request = new JsonArrayRequest (Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(JSONArray response) {
if (!response.equals(null)) {
Log.e("Your Array Response", response);
} else {
Log.e("Your Array Response", "Data Null");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error is ", "" + error);
}
}) {
//This is for Headers If You Needed
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
//Map<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=UTF-8");
// params.put("Authorization", "bearer " + token);
return params;
}
//Pass Your Parameters here
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
/*params.put("User", UserName);
params.put("Pass", PassWord);*/
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Try this one
It might be a permission issue,
did you add your manifest.xml file the following code:
<uses-permission android:name="android.permission.INTERNET" />
Finally I got it. The problem was that I get a JSONObject as response but instanciated a JSONArrayRequest. When I change that into a JSONObjectRequest it works perfectly.
The code which does not work is below. See anything wrong with this code , why it is not sending parameters. I am new to Android.
private void sendParams()
{
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_Q_RECIPIES,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Recipie movie = new Recipie();
movie.setRecipieName(obj.getString("recipie_name"));
movie.setId(obj.getInt("id"));
// build the image URL here
String s = AppConfig.URL_IMAGE + obj.getInt("id") + ".jpeg";
movie.setImageURL(s);
movie.setPrimaryIngrediant(obj.getString("prim_ingr"));
movie.setUrl(obj.getString("url"));
// adding movie to movies array movie is nothing but recipie
movieList.add(movie);
} 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) {
Log.e(TAG, "Filter error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hidePDialog();
}
}) {
#Override
protected Map<String, String> getParams () {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("ind_ajwain", Integer.toString(session.isAjwainChecked()));
//params.put("ind_asaftide", Integer.toString(session.isAsaftideChecked()));
params.put("rec_name", "chicken"); /// change this
params.put("ind_ginger", "0");
//params.put("password", password);
return params;
}
};
Log.d(TAG, movieReq.toString());
//movieReq.
AppController.getInstance().addToRequestQueue(movieReq);
}
I followed this link to get coding don : Source: https://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
I have not made much changes above, only changing parameters.
For sending data to server using Volley refer below code.
Step1 : Use POST method to send data.
Create below method :
private void makeJsonSend() {
StringRequest jsonObjReq = new StringRequest(Request.Method.POST,Const.ServiceType.URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response:forgot", response);
jsonParseResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//show error message here
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("email","email");
//pass parameter here
Log.i("request send data", params.toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
//If you have header parameter then set here
return headers;
}
};
AppController.getInstance().addToRequestQueue(movieReq);
}
Step 2: Response method where you have get response of that operation.
private void jsonParseResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("200")) {
cc.showToast(jsonObject.getString("message"));
} else {
cc.showToast(jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Forgot Error",e.toString());
}
}
You didn't pass any request method in new JsonArrayRequest. You have to pass Request.Method.POST or Request.Method.GET
friends. I have a problem with my volley POST request with parameters. I need fetch the data from my remote MySQL DB and display it in recycler view. For this, I have using volley network request. Without parameters, it loads all the data from my DB. But when I add getParams() method it returns a null array even though corresponding DB entries are available according to the passing parameters. Here is my code..
public void setDonorsList(final VolleyCallBack volleyCallBack) {
if (Utility.isNetworkEnabled) {
final ArrayList<Donor> listOfDonors = new ArrayList<>();
final ProgressDialog progressDialog = new ProgressDialog(FindDonorResult.this);
progressDialog.setMessage("Loading Donors List. Please wait");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
listOfDonors.clear();
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < 10) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
Donor donor = new Donor(
jsonObject.getString("fName"), jsonObject.getString("sName"), jsonObject.getString("emailid"),
jsonObject.getString("pass"), jsonObject.getString("mobile"), jsonObject.getString("blood"),
jsonObject.getString("age"), jsonObject.getString("gender"), jsonObject.getString("country"),
jsonObject.getString("location"), jsonObject.getString("latitude"), jsonObject.getString("longitude"),
jsonObject.getString("picname"), jsonObject.getString("pic")
);
int roundedDistance = (int) distance(Double.parseDouble(donor.getLatitude()),
Double.parseDouble(latitude), Double.parseDouble(donor.getLongitude()),
Double.parseDouble(longitude));
donor.setDistance(roundedDistance);
listOfDonors.add(donor);
count++;
}
Log.e("listOfDonors", String.valueOf(listOfDonors.size()));
volleyCallBack.onSuccess(listOfDonors);
} catch (JSONException e) {
e.getMessage();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.getMessage();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", "A+");
return params;
}
};
NetworkRequestSingleTon.getOurInstance(FindDonorResult.this).addToRequestQue(stringRequest);
} else {
Toast.makeText(FindDonorResult.this, "No active internet connection.", Toast.LENGTH_SHORT).show();
}
}
try using this
JSONObject jObj = new JSONObject(response)
JSONArray area = jObj.getJSONArray("");
maybe this will help
Finally, I figured it. The problem was in setDonorsList() method. I have hard coded the condition while(count < 10). This produces a JSON exception called "index out of range" since my DB doesn't have 10 entries. I changed the value like while(count < jsonArray.length()). Now everything is perfect. Guys thank you so much for your time and concern.
I have a big problem with volley request sequence and making json array out of first request response for second request.
this is the code :
JSONObject imageAddedResponse = new JSONObject();
JSONArray imagesAddedResponse = new JSONArray();
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
first request post to CMS and get some information for images posted and then I need to add those information to next post to make entity based on response I got back from first post request.
int totalSuccesfulImagePost = 0; //this variable increment when each succesful response from multipart-request
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages.getJSONObject(0));
totalSuccesfulImagePost++; //here we increase the count
postRequest(token); //call this method and check wheather all the image uploaded or not
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
}
//make this as seperate method and call when all multipart-request call succesful
public void postRequest(String token){
if(totalSuccesfulImagePost != mImages.size()) {
//this means not all the images posted yet, hence return the method
return;
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();.getJSONObject(0)
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
updated your code. Hope this may help you.
I've created new method for JsonObjectRequest with the name postRequest();
totalSuccesfulImagePost variable holds the no. of succesfull response for image upload
new method postRequest() calls at each multipart-request response
postRequest() methods check if not all response process yet than skip the 2nd api call
Also see how fb do this batch request https://developers.facebook.com/docs/android/graph/ -> Batch Reqest
Note -
Ive increment the variable totalSuccesfulImagePost and handle in each response, although you need to Response.ErrorListener()
Although you can go with the ThreadPoolExecutor option where each thread is created to handle each multipart-request upload and after all thread execution , call the method postRequest()
Work-around using ThreadPoolExecutor
a) Create ThreadPoolExecutor & initialize min/max pool size
b) Asign each mulitpart-request to upload image to each thread
c) Add all thread (contain image upload multipart-request) to ThreadPoolExecutor
d) Execute pool
e) call postRequest() method when ThreadPoolExecutor is empty i.e. this means all the thread execution is done and ready to call postRequest()
it is possible using Priority Of each Request.
private Priority priority = Priority.HIGH;
StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#Override
public Priority getPriority() {
return priority;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);