JsonArrayRequest Post Method isn't working - android

I did not use Volley before so I'm a newbie here. I try to do a JSONArrayRequest with Post Parameters.
A PHP script will check these parameters and answer with a JSON Array which is going to displayed in a list.
But somehow the Post Parameters don't send. So my PHP script says that the post parameters are missing.
So what did I do wrong that the post parameters don't send?
Here is my code:
private void getPersonsData(final String PhoneNr, final String Password) {
String url = "http://127.0.0.1:80/android_login_api/getmembers.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Method.POST, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
//Adding a person in the list
if (response.length() > 0) {
personList.clear();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Person person = new Person();
if (!jsonObject.isNull("fullname")) {
person.name = jsonObject.getString("fullname");
}
if (!jsonObject.isNull("location")) {
person.location = jsonObject.getString("location");
}
personList.add(i, person);
}
mAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("phonenr", PhoneNr);
params.put("password", Password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
And here are some parts of my PHP Code:
getmembers.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
if (isset($_POST['phonenr']) && isset($_POST['password'])) { //this goes on false
// receiving the post params
$phonenr = $_POST['phonenr'];
$password = $_POST['password'];
$user = $db->getUserByPhonenrAndPassword($phonenr, $password);
[...]
Would be great when someone finds out my mistake!

The normal $_POST method in php doesn't work in volley. You need to make this in your php file.
$post = json_decode(file_get_contents("php://input"), true);
$my_value = $post['param1'];
param1 is value that you put in volley.
Use this :
final Hashmap<String,String> param1 = new Hashmap<string,string>();
param1.put("param1",your value);
it works for me. You can try it
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Method.POST, url, **new JSonObject(param1)**, new Response.Listener<JSONArray>() { . . . ..

Related

Store JSONArrayRequest response in Android Studio

Good morning! I've been a lot of days searching for an answer similar to this but I couldn't find it, so here I am.
In Android Studio, I've did a function which has a jsonArrayRequest request, which looks like this:
private String requestCoursesInfo() {
RequestQueue requestQueue = Volley.newRequestQueue(this.context);
JsonArrayRequest jsonArrayRequest= new JsonArrayRequest(
Request.Method.GET,
COURSES_URL,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray coursesJsonArray) {
String name;
ArrayList<HashMap> coursesBasicInfoList = new ArrayList<>();
try {
for (int i=0; i < coursesJsonArray.length(); i++){
JSONObject courseInfo = coursesJsonArray.getJSONObject(i);
name = courseInfo.getString("name");
//ArrayList to group all the info
HashMap<String, String> currentCourseInfoList = new HashMap<>();
currentCourseInfoList.put("name", name);
coursesBasicInfoList.add(currentCourseInfoList);
}
} catch (JSONException e) {
//Do something with error
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
}
}
){
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
// Add JsonObjectRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
return "courses";
}
The thing is, as you can see, once I have the response I build a HashMap with the key name and value of the name from the response and I put it all in coursesBasicInfoList ArrayList.
The thing is, this variable (coursesBasicInfoList) is never accessible from outside the request and what I want is to be able to put this arraylist in the "return" that you can see at the end of the function.
I know the request is asynchronous but I suppose it has to be some way to store this data from the response to use it in other methods, isn't it?
Thank you!
You can use LiveData to solve synchronization problem in asynchronous call like volley.
private MutableLiveData<ArrayList<HashMap>> requestCoursesInfo() {
MutableLiveData<ArrayList<HashMap>> mutableCoursesBasicInfoList = new MutableLiveData<>();
RequestQueue requestQueue = Volley.newRequestQueue(this.context);
JsonArrayRequest jsonArrayRequest= new JsonArrayRequest(
Request.Method.GET,
COURSES_URL,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray coursesJsonArray) {
String name;
ArrayList<HashMap> coursesBasicInfoList = new ArrayList<>();
try {
for (int i=0; i < coursesJsonArray.length(); i++){
JSONObject courseInfo = coursesJsonArray.getJSONObject(i);
name = courseInfo.getString("name");
//ArrayList to group all the info
HashMap<String, String> currentCourseInfoList = new HashMap<>();
currentCourseInfoList.put("name", name);
coursesBasicInfoList.add(currentCourseInfoList);
}
} catch (JSONException e) {
//Do something with error
}
//post your result in LiveData
mutableCoursesBasicInfoList.postValue(coursesBasicInfoList);
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
}
}
){
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
// Add JsonObjectRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
//Return MutableLiveData<ArrayList<HashMap>>
return mutableCoursesBasicInfoList;
}
And the observe the LiveData from your Activity/Fragment like below:
requestCoursesInfo().observe(this, new Observer<ArrayList<HashMap>>() {
#Override
public void onChanged(ArrayList<HashMap> hashMaps) {
//Do your operation here with ArrayList<HashMap>
}
});

failed jsonArrayRequest

MY function content to make jsonArrayRequest is:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject1 = response.getJSONObject(0);
JSONObject jsonObject2 = response.getJSONObject(1);
if (jsonObject1.getBoolean("error")) {
ArrayList<String> list = new ArrayList<>();
list.add(jsonObject2.getString("message"));
displayThought(list);
} else {
int count = 0;
ArrayList<String> list = new ArrayList<>();
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
String thought = jsonObject.getString("post");
list.add(thought);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
displayThought(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", "sainiakshay04");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(jsonArrayRequest);
The content of the php it is using is:
require_once '../app/display_personal_account.php';
$response=array();
if(isset($_POST['email'])){
$db = new display_personal_account($_POST['email']);
$res=$db->get_info_added("shared_content");
if($res==1){
$response=$db->display_shared_content();}
else{
$response[]['error']=true;
$response[]['message']="No Content To Display ";}
}
else{
$response[]['error']=true;
$response[]['message']="ERROR: INVALID REQUEST";
}
echo json_encode($response);
?>
but the output it is displaying is ERROR:INVALID REQUEST, although I'm binding email using getParams, isset of php is not working and going to else part.
HELP!
You're checking isset($_POST['email']) but you send null parameter in the JsonArrayRequest.
For now, JsonArrayRequest only supports the JsonArray parameter.
There are two things that you need to do :
Send the email in the JsonArray parameter
JSONObject request = new JSONObject();
request.put("email", userEmail);
JSONArray arrayParam = new JSONArray();
arrayParam.put(request);
....
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, arrayParam, ...
Get the email in the PHP
require_once '../app/display_personal_account.php';
$response=array();
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if(isset($input[0]['email'])){
$db = new display_personal_account($input[0]['email']);
....
After that, you should just work fine :)

Volley not sending the params while using JsonArrayRequest

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.

How can I post a parameter through JsonObjectRequest

I asked this before but I did not get a solution,
I am trying to post a parameter to the php script and get its results as json array however every time I try I get all of the columns in my table. At first I though there is something wrong with my php, however I tried from postman and see that my php works. So there is a problem in my code, problem is I am building a searchview so every time user enters it searches the data from database and shows the result in a listview. But I cannot post my parameter to my php script by using JsonObjectRequest. So how can I do it?
public void findSearchedUsers(String s)
{
HashMap<String, String> params = new HashMap<String, String>();
params.put("keyword",s );
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,"http://ksdb.comlu.com/search.php", new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray= response.getJSONArray("users");
for(int i = 0; i < jsonArray.length(); i ++){
JSONObject user = jsonArray.getJSONObject(i);
String id = user.getString("u_id");
String name = user.getString("u_name");
String surname = user.getString("u_lname");
String email = user.getString("u_email");
String password = user.getString("u_pw");
String department = user.getString("u_dp");
User newUser = new User(id, name, surname, email, password, department);
userArrayList.add(newUser);
}
setUsersListView(userArrayList );
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
RequestQueue queue = Volley.newRequestQueue(MainUserPage.this);
queue.add(req);
}
here is my php code and I and I also changed the android code too
<?php
// include connect class
$response = array();
// include connect class
require_once 'connect.php';
// connecting to db
$db = new DB_CONNECT();
// connecting to db
$keyword=$_GET["keyword"];
$result = mysql_query("SELECT * FROM user WHERE u_name LIKE'%$keyword%' LIMIT 0, 20")
or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
$response["users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$users= array();
$users["u_id"] = $row["u_id"];
$users["u_name"] = $row["u_name"];
$users["u_lname"] = $row["u_lname"];
$users["u_email"] = $row["u_email"];
$users["u_pw"] = $row["u_pw"];
$users["u_dp"] = $row["u_dp"];
array_push($response["users"], $users);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No idioms found";
// echo no users JSON
echo json_encode($response);
}
?>
You should override the "getParams()" method on your request object.
If it doesn't work for a JSONObjectRequest, then try using a StringRequest and override the getParams() method.
Here's an example from their help.
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user",userAccount.getUsername());
params.put("pass",userAccount.getPassword());
params.put("comment", Uri.encode(comment));
params.put("comment_post_ID",String.valueOf(postId));
params.put("blogId",String.valueOf(blogId));
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;
}
};

How to use HTTP Auth with Volley

I am using Volley's JsonArrayRequest to get JSON data from my webpage.
Now I have added Basic HTTP Authentication to my webpage. How can I use HTTP Auth with Volley?
And further if I add Digest HTTP Authentication to my webpage, How can I deal with it in android?
My JsonArrayRequest code:
JsonArrayRequest loadMoreRequest = new JsonArrayRequest(url,new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response)
{
try
{
for (int i = 0; i < response.length(); i++)
{
JSONObject obj = response.getJSONObject(i);
//Some Logic
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show();
}
});
requestQueue.add(loadMoreRequest);
Use RequestQueue and StringRequest instead like so
RequestQueue queue = Volley.newRequetQueue(context);
StringRequest myReq = new StringRequest(Method.POST, "http://ave.bolyartech.com/params.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<string, string=""> getParams() throws com.android.volley.AuthFailureError {
Map<string, string=""> params = new HashMap<string, string="">();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);

Categories

Resources