getParams() with JsonArrayRequest - java

I am trying to get the response from the server based on the data I send it, I am able to get a response from the server, but the server doesn't seem to be receiving the values in the getParams().
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
Toast.makeText(getContext(), selectedUniversityItem.getmUniversityValue(), Toast.LENGTH_SHORT).show();
params.put("schoolUniversity", selectedUniversityItem.getmUniversityValue());
params.put("key", key);
return params;
}
};
queue.add(jsonRequest);

The method I would suggest in this case is to pass the parameters in the URL of your code and remove the getParams() method.
So, your modified code looks like;
String url = "myUrl";
RequestQueue queue = Volley.newRequestQueue(getContext());
schoolContributeList = new ArrayList<>();
JsonArrayRequest jsonRequest = new JsonArrayRequest(Request.Method.POST, url+"?schoolUniversity="+selectedUniversityItem.getmUniversityValue()+"&key="+key,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray ja) {
try {
for (int i = 0;i < ja.length();i++) {
JSONObject school = ja.getJSONObject(i);
String schoolId = school.getString("id");
String schoolName = school.getString("name");
universityItem schoolItem = new universityItem(schoolName, schoolId);
Toast.makeText(getContext(),schoolId , Toast.LENGTH_SHORT).show();
schoolContributeList.add(schoolItem);
schoolContributeAdapter = new universityAdapter(getContext(), schoolContributeList);
schoolContributeSpinner.setAdapter(schoolContributeAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
Log.i("error", error.toString());
Toast.makeText(getContext(), "no response", Toast.LENGTH_SHORT).show();
}
}){
};
queue.add(jsonRequest);
Hopefully, this will work. Good Luck :)

Related

Apps need to restarted to refresh profile image

recently i've made a program that can upload image to mysql database via php, and now i'm gonna put that image to my circleImageView, but i've encountered some issue, if i do image update, the image won't refresh until i close the apps and run it again.
here is my code for displaying the image and others from mysql database
public void putAllUserData(final String username){
StringRequest stringRequest = new StringRequest(Request.Method.POST, databaseURL.viewUserData, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i = 0; i < jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
setUsername.setText(username);
setFullName.setText(object.getString("nama"));
setCountry.setText(object.getString("asal_negara"));
setGender.setText(object.getString("jenis_kelamin"));
prfImage = object.getString("image_path");
if(prfImage.isEmpty()){
Toast.makeText(profileActivity.this, "", Toast.LENGTH_SHORT).show();
}
else {
Picasso.get().load(prfImage).into(profileImage);
}
}
} catch (JSONException e) {
Toast.makeText(profileActivity.this, "Error " + e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(profileActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}){
#Nullable
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}

How to start onResponse method after getParams has been executed with StringRequest in Android Studio Volley?

I am trying to start an JSONArrayRequests after the StringRequest has finished. The StringRequest is POST requet and the JSONArrayRequest is GET request. I want the JSONArray to start when the params of the String is uploaded so as I will be able to retrieve this data again. Below is my code:
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, JSON_URL_UPLOAD_IMAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response.equals("1")) {
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++) {
try {
JSONObject object = response.getJSONObject(i);
String USER_ID = object.getString("user_id");
String POST_DATE = object.getString("post_date");
if (USER_ID.equalsIgnoreCase(CurrentUser)){
Toast.makeText(getContext(), "First if.", Toast.LENGTH_SHORT).show();
if (POST_DATE.equalsIgnoreCase(dateTime)) {
Toast.makeText(getContext(), "Second if.", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Error", error.getMessage());
}
});
requestQueue.add(arrayRequest);
requestQueue.start();
}
}catch (Exception e) {
e.printStackTrace();
Log.d("ERROR", e.getMessage().toString());
Toast.makeText(getContext(), "ERROR:"+e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Nullable
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("post_author", CurrentUser);
if (!details.getText().toString().equalsIgnoreCase("")){
params.put("post_content", details.getText().toString());
params.put("post_excerpt", details.getText().toString());
}else {
params.put("post_content", "");
params.put("post_excerpt", "");
}
params.put("post_date", dateTime);
params.put("post_date_gmt", dateTime);
params.put("post_title", CurrentUser+"-"+CurrentUser+"-"+timeStampStr);
params.put("post_status", "publish");
params.put("comment_status", "closed");
params.put("ping_status", "closed");
params.put("post_name", CurrentUser+"-"+CurrentUser+"-"+timeStampStr);
params.put("post_modified", dateTime);
params.put("post_modified_gmt", dateTime);
params.put("guid", "https://www.selfcial.com/peepso-post/"+CurrentUser+"-"+CurrentUser+"-"+timeStampStr+"/");
params.put("post_type", "peepso-post");
return params;
}
};
requestQueue.add(stringRequest);
requestQueue.start();
What I tried to do is to add a RequestQueue in order to make the requests wait until the other one is finished but it didn't work. The problem I have is that when the inside request starts it doesn't find the "if" statement(namely this:(USER_ID.equals(CurrentUser) && POST_DATE.equals(dateTime)). So, what I can understand is that the second starts before the first has finished with the params. What can I do? Any answer will be appreciated!

volley get response returns value of type java.lang.String cannot be converted to JSONArray

i am trying to authenticate using an api.am getting an error on response, my api returns the following response and am getting the following error.
value of type java.lang.String cannot be converted to JSONArray.
kindly help, am a newbie.
this is what my api returns:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
</string>
this is my code;
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//create a StringRequest
StringRequest request = new StringRequest( Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
int i = 0;
while (i < jArray.length()) {
JSONObject json_data = jArray.getJSONObject(i);
String status = json_data.getString("status");
if (status == "True") {
Intent intent = new Intent(LoginActivity.this, ParentActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "logged in as " + user,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "wrong username or password",
Toast.LENGTH_LONG).show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!!! " + error.toString(),
Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", user);
params.put("password", pass);
return params;
}
};
//add the StringRequest to the RequestQueue
queue.add(request);
}
I was change JSONArray jArray = new JSONArray(response); to JSONObject jObject = new JSONObject(response); and JSONObject json_data = jArray.getJSONObject(i); to String json_data = jObject(i);. Try it, please.
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
//create a StringRequest
StringRequest request = new StringRequest( Request.Method.GET,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
int i = 0;
while (i < jArray.length()) {
String json_data = jObject(i);
String status = json_data.getString("status");
if (status == "True") {
Intent intent = new Intent(LoginActivity.this, ParentActivity.class);
startActivity(intent);
Toast.makeText(LoginActivity.this, "logged in as " + user,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "wrong username or password",
Toast.LENGTH_LONG).show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!!! " + error.toString(),
Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", user);
params.put("password", pass);
return params;
}
};
//add the StringRequest to the RequestQueue
queue.add(request);
}
Is your API returning
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
</string>
or
[{"status":"True","username":"parent","schoolid":"001","category":"3","usercode":"0720994718"}]
?
If the first, then you should extract the JSON string from the XML answer before invoking "JSONArray jArray = new JSONArray(response);", and then do something like "JSONArray jArray = new JSONArray(json_part_of_the_response);".
I think your JSON array is inside XML so you have to parse your XML first using dom parser

Having trouble while consuming PHP Api via Volley library Android

I am able to consume api via volley library which use normal get post method but my php team just changed my api which accept json . i know there is is JsonObjectrequest in volley but i don't know how to put parameters in `JsonObjectRequest. Any help is appriciated.
PHP API
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$data_back = json_decode(file_get_contents('php://input'));
header("Content-type: application/json");
require "conn.php";
$id = $data_back->{"id"};
$address = $data_back->{"address"};
$pincode = $data_back->{"pincode"};
$name = $data_back->{"name"};
$mobile = $data_back->{"mobile"};
$sql = "UPDATE tbl_addressbook SET name = '$name', address = '$address', pincode = '$pincode', mobile = '$mobile' WHERE id = $id";
if(mysqli_query($conn,$sql)){
echo 'Address Book Updated Successfully';
}
else{
echo 'Could Not Update Your Address Book';
}
}
?>
Volley Request
StringRequest stringRequest=new StringRequest(Request.Method.POST, Config.UPDATE_ADDRESS_BOOK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext,"Address Changed",Toast.LENGTH_LONG).show();
list.set(getAdapterPosition(),new AddressBookModel(bookModel.getId(),
etName.getText().toString(),
etAddress.getText().toString(),
etPinCode.getText().toString(),
etPhone.getText().toString(),
bookModel.getDefAddress()));
d.dismiss();
progress.dismiss();
((Activity)mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Something Went Wrong \n ttry again later",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map=new HashMap<String, String>();
map.put("id",bookModel.getId());
map.put("name",etName.getText().toString());
map.put("address",etAddress.getText().toString());
map.put("pincode",etPinCode.getText().toString());
map.put("phone",etPhone.getText().toString());
return checkParams(map);
}
private Map<String, String> checkParams(Map<String, String> map){
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>)it.next();
if(pairs.getValue()==null){
map.put(pairs.getKey(), "");
}
}
return map;
}
};
VolleySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
Easy cheesy lemon squeezy!
Some code
HashMap<String, String> params = new HashMap<String, String>();
params.put("id", "300");
params.put("address", "Mars");
params.put("pincode", "***");
params.put("name", "Jon Skeet");
params.put("mobile", "911");
JsonObjectRequest request = new JsonObjectRequest(
/*URL*/,
new JSONObject(params),
new Response.Listener<JSONObject>(){/*...*/});
First Create your JsonObject like
JSONObject js = new JSONObject();
try {
js.put("email", "adasda");
js.put("address", "adasd");
js.put("pincode", "adadasd");
}catch (JSONException e) {
e.printStackTrace();
}
Then your JSON request, take a careful look at get headers.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST,url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject 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();
}
}) {
/**
* Passing some request headers
* */
#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");
return headers;
}
private void getWalletDetails(){
final ProgressDialog pDialog; // = new ProgressDialog(mcontext);
StringRequest stringRequest;
pDialog = GifDialog.ctor(mcontext);
pDialog.show();
stringRequest = new StringRequest(Request.Method.POST, place your url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
pDialog.dismiss();
//Showing toast message of the response
try {
JSONObject jsonObject = new JSONObject(s);
totbal.setText("\u20B9 "+jsonObject.getString("avail_balance"));
JSONArray jsonArray = jsonObject.getJSONArray("tx_detail");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
mode = new Model_Wallet_Transaction();
mode.setStr1(object.getString("date"));
mode.setStr4(object.getString("insert_time"));
mode.setStr2(object.getString("name"));
mode.setStr3(object.getString("transaction_id_no"));
mode.setAmount(object.getString("amount"));
mode.setTxtype(object.getString("tx_type"));
modlist.add(mode);
}
// Collections.sort(modlist, new StringDateComparator());
adp = new CustomAdapter_Wallet_Transaction(getApplicationContext(), modlist);
list.setAdapter(adp);
} catch (Exception e) {
Log.e("Error", e.toString());
}
// Toast.makeText(Wallet_Transaction.this, s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
pDialog.dismiss();
//Showing toast
//Toast.makeText(Wallet_Transaction.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put("user_id", UserId);
params.put("deviceId", DeviceId);
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}

How to use POST and GET method in Volley library?

I am using volley for login authentication,I passed values to the url by using JSON. Is it Correct Way? if not please tell me how to use POST and GET method in volley Library.i want to authentication to be done using volley library by passing string to the url
String loginurl = "http://www.souqalkhaleejia.com/webapis/login.php?email="+user+"&password="+pass;
Log.i("logurl", loginurl);
JsonObjectRequest loginreq = new JsonObjectRequest(Request.Method.POST, loginurl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("Success")) {
String lomsg = response.getString("message");
String userid = response.getString("userid");
loginsession = new Session(getApplicationContext());
loginsession.createLoginSession(user, pass);
logineditor.putString("uid", userid);
logineditor.commit();
if (rememberme.isChecked()) {
logineditor.putBoolean("saveboolean", true);
logineditor.putString("uname", user);
logineditor.putString("pass", pass);
logineditor.commit();
} else {
logineditor.clear();
logineditor.commit();
}
Intent lognext = new Intent(MainActivity.this, Homescreen.class);
startActivity(lognext);
Toast.makeText(MainActivity.this, ""+lomsg,Toast.LENGTH_SHORT).show();
} else {
String errmsg = response.getString("message");
Toast.makeText(MainActivity.this,""+errmsg,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error,Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(loginreq);
}
You should pass the params like this
RequestQueue queue = Volley.newRequestQueue(context);
Map<String, String> jsonParams = new HashMap<String, String>();
jsonParams.put("userId", UserSingleton.getInstance(context).getUserId());
//jsonParams.put("userId", alert.getUser().getUserId());
// Request a string response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL , new JSONObject(jsonParams), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Response OK
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Error
}
});

Categories

Resources