Having trouble while consuming PHP Api via Volley library Android - java

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

Related

How to change a StringRequest into a JsonArrayRequest?

I want to change my StringRequest to a JsonArrayRequest in order to separate the return into different variables.
As I run this code below:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("res", response);
if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "Ungültige Anmeldedaten", Toast.LENGTH_SHORT).show();
} else {
TV.setText(response);
//ID = Integer.parseInt(response);
//switchToMain();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("email", email);
data.put("password", password);
return data;
}
};
requestQueue.add(stringRequest);
I return the response:
[{"id":"6","Username":"a","Email":"a","Password":"0cc175b9c0f1b6a831c399e269772661","Status":"Online"}]
, which is a JsonArray, isn´t it?
When I try to make a JsonArrayRequest I receive errors:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonArrayRequest queue = new JsonArrayRequest(Request.Method.POST,URL,null,new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
if (response.equals("null")) {
Toast.makeText(MainActivity.this, "Ungültige Anmeldedaten", Toast.LENGTH_SHORT).show();
} else {
//ID = Integer.parseInt(response);
//switchToMain();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("email", email);
data.put("password", password);
return data;
}
};
requestQueue.add(queue);
I receive the following error:
com.android.volley.ParseError: org.json.JSONException: End of input at character 0 of
Where is my mistake?

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

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

getParams() with JsonArrayRequest

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

How to return serverAnswer?

How do I return serverAnswer behind onResponse?
Because in onResponse, serverAnswer gets data, but behind onResponse it's an empty variable...
For example, if I try to show a Toast with serverAnswer in onResponse, it's alright, serverAnswer has data from JSON string. But if try to show a Toast with serverAnswer behind onResponse - I get an empty Toast.
And addUser returns an empty String too.
public String addUser(final String username, final String email, final String password, final Context context) {
StringRequest request = new StringRequest(
Request.Method.POST,
REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonObject = new JSONObject(response);
final JSONObject status = jsonObject.getJSONObject("Result");
serverAnswer = status.getString("Server answer");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
serverAnswer = error.getMessage();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_USERNAME, username);
params.put(KEY_EMAIL, email);
params.put(KEY_PASSWORD, password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
return serverAnswer;
}

Categories

Resources