Android Volley Params - android

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.

Related

app returning empty Toast

i am getting an empty Toast as response when i try to register a user to my sql database and no useful error hint is thrown in the logcat.
please what could possibly be the cause of this ?
registerProcess
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
web service
/**
* Adding new user to mysql database
* returns user details
*/
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
There seems to be no error in the code, as far as I can see.
You should check the response you get with curl and see, what is returned.
to get the response from your web service you don't need JSON since you're doing a POST request by Volley. Your toast is empty because simply you're interpreting the response wrong and the objects like this one String errorMsg = jObj.getString("message"); will be empty.
To get the response you should do like this :
if (response.equalsIgnoreCase("yourResponseFromTheWebService")) {
...
Toast
} else if (response.equalsIgnoreCase("OtherPossibleResponse")){
....
Toast
} else{
....
Toast
}
EDIT :
I managed to spot two things in your web service code.
1- why are you trying to get informations from the server of the same user when you just sent them from your app. That doesn't make sense. You should attach your data as extra to your intent as you did with the email.
2- Volley expects a String type response and you giving him different formats at the same time.
So this a modified version of your code :
Web service :
public function storeUser($fname, $lname, $email, $uname, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO users(unique_id, firstname, lastname, email, username, encrypted_password, salt, created_at) VALUES('$uuid', '$fname', '$lname', '$email', '$uname', '$encrypted_password', '$salt', NOW())");
// check for successful store
if ($result) {
echo "successful";
} else {
echo "notsuccessful";
}
}
Android
private void registerProcess(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Functions.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response);
hideDialog();
if (response.equalsIgnoreCase("successful")) {
Functions logout = new Functions();
logout.logoutUser(getApplicationContext());
Bundle b = new Bundle();
//add other informations you need like name ect..
b.putString("email", email);
Intent i = new Intent(RegisterActivity.this, EmailVerify.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtras(b);
startActivity(i);
pDialog.dismiss();
finish();
} else if(response.equalsIgnoreCase("notsuccessful")) {
Toast.makeText(getApplicationContext(),"new user wasn't registered successfully", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
NOTE :
if you wanna know the error from your Mysql request don't show it on your app, just check it in your browser.
I hope this works for you

Volley: [213] BasicNetwork.performRequest: Unexpected response code 415

Im using Restful Java to parse data json with POST method and Volley in android. When I try to insert data from Advanced REST Client, it insert data into db success, but in Android, when I insert data and see that it happen an exception as below:
My Restful (UPDATED):
#Path("/bookticket")
public class BookServiceCalled {
#POST
#Path("/json")
#Produces("application/json;charset=utf-8")
#Consumes("application/x-www-form-urlencoded") // MediaType.APPLICATION_JSON
public static void bookFromUser(#QueryParam("fullname") String fullname,
#QueryParam("birthday") Date birthday,
#QueryParam("address") String address) throws Exception {
Connection connection = null;
PreparedStatement statement = null;
try {
// Config connect mydb
String query = "INSERT INTO order "
+ "(fullname, birthday, address) VALUES "
+ "(?,?,?) ";
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, fullname);
statement.setDate(2, birthday);
statement.setString(3, address);
statement.executeUpdate();
System.out.println("Work !");
}
catch (Exception e) {
// TODO Auto-generated catch block
if (connection != null) {
connection.close();
}
throw e;
}
finally {
if (connection != null) {
connection.close();
}
}
}
}
My activity class:
private static final String URL_BOOK = "http://192.168.1.221:9999/bookticket_service/bookticket/json";
EditText fullname, birthday, address;
fullname = (EditText) findViewById(R.id.fullname);
birthday = (EditText) findViewById(R.id.birthday);
address = (EditText) findViewById(R.id.address);
btnBook = (Button) findViewById(R.id.btnBook);
requestQueue = Volley.newRequestQueue(getApplicationContext());
btnBook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest request = new StringRequest(Request.Method.POST, URL_BOOK, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams() throws AuthFailureError {
Map<String, String> parameter = new HashMap<String, String>();
parameter.put("Content-Type", "application/json; charset=utf-8");
parameter.put("fullname", fullname.getText().toString());
parameter.put("birthday", birthday.getText().toString());
parameter.put("address", address.getText().toString());
return parameter;
}
};
// volley saves the response in its cache and this behavior may cause some strange problem
// request.setShouldCache(false);
requestQueue.add(request);
}
});
Logcat:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'fullname' cannot be null
How to fix the exception, thanks for the help

Android volley posting null values to database

My app is supposed to send some data to my php script and the php script will in turn push it to my online db. But the app keeps sending null values and have tried my php script using a simple HTML form and it's working perfectly and posting to database.
Am still new to using the volley library.
Here is my registration class:
private void registerfunc(final String name, final String email, final String phone, final String address) {`
String url ="http://circleincoprated.com/apps/register.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JSon data... ", response);
if (response.trim().equals("success")) {
pd.hide();
Toast.makeText(first_run.this, "registration Successful", Toast.LENGTH_LONG).show();
Intent in = new Intent(first_run.this, MainActivity.class);
startActivity(in);
} else {
pd.hide();
Toast.makeText(first_run.this, "registration Failed" + response, Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Log.d("JSon Error... ", error.toString());
Toast.makeText(first_run.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> params = new Hashtable<>();
//Adding parameters
params.put("name", name);
params.put("phone", phone);
params.put("email", email);
params.put("address", address);
//returning parameters
return params;
}
};
new MySingleton(first_run.this).addToRequestQueue(stringRequest);
}
While this is my php script:
<?php
extract($_POST);
if(isset($name)){
$resp='';
include 'config.php';
$sql = "INSERT INTO users (id,name,phone,email,address)
VALUES ('','".$name."', '".$phone."', '".$email."','".$address."')";
if ($conn->query($sql) === TRUE) {
$resp="success";
echo($resp);
$sql = "INSERT INTO log (id,response) Values('','".$resp."')";
$conn->query($sql);
}else {
$resp= "Error: " . $sql . "<br>" . $conn->error;
$conn->query($sql);
echo($resp);
}}else{
echo "Empty data";
}
?>

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 convert String to JSONObject?

I have an obstacle by changing the data string into a jsonobject, is his org.json.JSONException script error: Value
This coding I am trying
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = inputUser.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (username.trim().length() > 0 && password.trim().length() > 0) {
Map<String,String> params = new HashMap<>();
params.put("username", inputUser.getText().toString());
params.put("password", inputPassword.getText().toString());
sendPostRequest(params);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Silahkan Masukan Username dan Password!", Toast.LENGTH_LONG)
.show();
}
}
});
public void sendPostRequest(Map<String, String> params) {
showDialog();
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.chris-chris.webege.com/login.php";
mCustomRequest = new CustomRequest(Request.Method.POST,
url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(Login.this,
Coba.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
hidepDialog();
Toast.makeText(Login.this, "Belum Terhubung Internet! ", Toast.LENGTH_SHORT).show();
}
});
mCustomRequest.setRetryPolicy(new DefaultRetryPolicy(Template.VolleyRetryPolicy.SOCKET_TIMEOUT,
Template.VolleyRetryPolicy.RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mCustomRequest);
}
There are two conditions to convert a string to JSONObject :
1 . The string should be in proper Json format .
2 . Put code in try catch block .
Example:
String jsonString = "{"status":"1","message":"Login successfully","data":{"uid":"1","email":"baleshwar#gmail.com","password":"202cb962ac59075b964b07152d234b70","name":"","role":"1","gender":"","address":"","image":"","is_active":"0","last_login":"0000-00-00 00:00:00","device_id":"0","created_at":"2015-06-03 06:01:02","updated_at":"2015-06-03 11:01:02","location":"","dob":"0000-00-00","descriptions":""}}"
Now convert this string to JSONObject
try{
JSONObject jsonResponse = new JSONObject(result);
}catch(Exception e){
e.printStackTrace();
}
Try this,
If you call your service and try to paste that code inside your isSucsess part
JSONObject jObject = jsonObject.getJSONObject("jsonobjectname");
tvTitle.setText(jObject.getString("your string name"));

Categories

Resources