How can I post a parameter through JsonObjectRequest - android

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

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

Android Volley Params

In my project, i pass the firstname of a user in a params from the JSONobject request. It would then get the response and fill the textviews. however i cant figure out why my code does not work.I checked my php and it works fine when i put a predefined firstname in it, so i ruled out a web service problem. does it get the response first and then pass the params? please help
public class ProfileActivity extends AppCompatActivity {
TextView Username, Firstname, Lastname, Birthdate, Barangay;
String firstname;
String json_url = "http://localhost/android/getprofileinfo.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Username = (TextView)findViewById(R.id.usernameprofile);
Firstname = (TextView)findViewById(R.id.firstnameprofile);
Lastname = (TextView)findViewById(R.id.lastnameprofile);
Birthdate = (TextView)findViewById(R.id.birthdayprofile);
Barangay = (TextView)findViewById(R.id.barangayprofile);
final Bundle bundle = getIntent().getExtras();
firstname = bundle.getString(firstname);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, json_url, (String) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Username.setText(response.getString("username"));
Firstname.setText(response.getString("firstname"));
Lastname.setText(response.getString("lastname"));
Birthdate.setText(response.getString("birthdate"));
Barangay.setText(response.getString("barangay"));
}
catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
error.printStackTrace();
} //end of method onErrorResponse
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("firstname", firstname);
return params;
}
};
MySingleton.getmInstance(ProfileActivity.this).addTorequestque(jsonObjectRequest);
}
}
this is the getpropileinfo.php
<?php
$firstname =$_POST["firstname"];
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','mydb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$sql = "SELECT username,firstname,lastname,birthdate,barangay FROM users
WHERE firstname LIKE '".$firstname."'; ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
echo json_encode(array("username"=>$row['username'],
"firstname"=>$row['firstname'],
"lastname"=>$row['lastname'], "birthdate"=>$row['birthdate'],
"barangay"=>$row['barangay']));
}
?>
You are not properly taking the getExtras(), provide the key name which you pass using putExtra() from your calling activity, like this
In the calling activity pass intent like
Intent i = new Intent(FirstActivity.this, ProfileActivity.class);
String strName = "some_name";
i.putExtra("key_username", strName);
startActivity(i);
Then in ProfileActivity,
final Bundle bundle = getIntent().getExtras();
firstname = bundle.getString("key_username");
Convert to JsonArrayRequest
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (String) null,
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject person = (JSONObject) response
.get(0);
Username.setText(person.getString("username"));
Firstname.setText(person.getString("firstname"));
Lastname.setText(person.getString("lastname"));
Birthdate.setText(person.getString("birthdate"));
Barangay.setText(person.getString("barangay"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ProfileActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
error.printStackTrace();
} //end of method onErrorResponse
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("firstname", firstname);
return params;
}
};
May be its issue with your localhost, Go through Genymotion is using your PC IP address. to get your IP address go to:
start -> cmd -> ipconfig
then search for IPv4, copy the IP and paste it in your URL. It should looks like the following:
String YourURL = "http://192.168.0.106:8888/android/getprofileinfo.php";
Hope this works too for you.
Inside the method parameters, remove the string casting for the json object.
null instead of (String) null.
Change your JSONRequest to a StringRequest.

JsonArrayRequest Post Method isn't working

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>() { . . . ..

Volley POST REQUEST error 500

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

Categories

Resources