I am building a registration system for Android. I can add data to the database,which is good. Now I want to add some JSON that will notify the user successful registration or different errors. ie
{
"status":"success",
"message":"Successful Registration"
}
or
{
"status":"fail",
"message":"Please enter your name"
}
etc.
Here is my php script.
<?php
require "init.php";
$j = new stdClass();
$name = $_POST['name'];
$user_name = $_POST['user_name'];
$user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);
if(!$name){
json_encode(array('status' => 'fail', 'message' => 'Please enter your
name'));
}
$sql_query = "insert into user_info
values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query)){
json_encode(array('status' => 'success', 'message' => 'Successfully
registered'));
}else{
json_encode(array('status' => 'fail', 'message' => 'Could not
register'));
}
?>
With this script I can not detect any JSON repsonse from my Java code,even if I add data successfully.
private void registerUser(final String name, final String userName,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST,
"MY_LINK_GOES_HERE", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", "Register Response: " + response.toString());
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
MainActivity.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@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("user_name", userName);
params.put("user_pass", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
The line
Log.d("Response", "Register Response: " + response.toString());
gives me nothing.
Any ideas?
Thank you.
First of all, you should mention in your question that you are using the android-volley
library, or at least use the tag
. Second, if you are trying to parse JSON
response, then you should use the JsonObjectRequest
instance to do that. Assuming your php
script is sending the right JSON
, you could try something simple and straight-forward with volley
like this:
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
response = response.getJSONObject("args");
String site = response.getString("site"), network = response.getString("network");
View view = findViewById(R.id.activity_layout);
Snackbar.make(view, "Site : " + site + " Network : " + network, Snackbar.LENGTH_INDEFINITE).show();
} catch (JSONException e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Error Listener", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(jsonRequest);
This assumes your JSON
is something like this:
{
"args": {
"network": "somenetwork",
"site": "code"
},
"args2": {
...
},
"args3": "...",
"args4": "..."
}
Now depending on the JSON
you are sending, you could try any combination. You could also look into this very useful tutorial . Hope this helps. Let me know if you need more help.
I had encountered the same problemm in my App when i was trying to make a registration. I wanted to check if user registered and if the username is available.
So what i did was:
PHP File:
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo $e->getMessage();
die();
}
$username = $_POST['username'];
$password=$_POST['password'];
$email = $_POST['email'];
$dateCreated = $_POST['dateCreated'];
$android_version= $_POST['android_version'];
$api_level = $_POST['api_level'];
$check = $handler->query("SELECT * FROM table WHERE username = '$username'");
$don = array();
if($check->rowCount() > 0){
$don = array('result' =>TRUE);
die();
}else{
$don = array('result' =>FALSE);
$handler->query("INSERT INTO table(id, username, password, email, dateCreated, activated, Android_Version, API_Level) VALUES('', '$username','$password','$email', '$dateCreated', 0, '$android_version', '$api_level')");
}
echo json_encode($don);
?>
Android:
private class MyInsertDataTask extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(YourActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setMessage(getString(R.string.dialog_rate_data_submit));
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username", uName));
nameValuePairs.add(new BasicNameValuePair("password", pass));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("dateCreated", date));
nameValuePairs.add(new BasicNameValuePair("android_version", release));
nameValuePairs.add(new BasicNameValuePair("api_level", String.valueOf(sdkVersion)));
try
{
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(AppConstant.REGISTER_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
httpEntity = response.getEntity();
is = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
Log.e("Responce", result.toString());
if (result != null) {
data = new JSONObject(result.toString());
usernameExists = data.getBoolean("result");
}
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
return usernameExists;
}
@Override
protected void onPostExecute(Boolean aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (aVoid){
Snackbar.with(YourActivity.this).type(SnackbarType.MULTI_LINE).text(getString(R.string.username_exists_message)).color(Color.parseColor(AppConstant.ENABLED_BUTTON_COLOR)).show(getActivity());
}else {
Toast.makeText(YourActivity.this, getString(R.string.created_successfully), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(YourActivity.this, MainActivity.class);
startActivity(intent);
YourActivity.this.finish();
}
}
}
The result is that if username exists a message pops up saying username already exists otherwise the user registers
Result:
I fixed it! It was a php issue. Here is my solution.
<?php
require "init.php";
header('Content-type: application/json');
$name = $_POST['name'];
$user_name = $_POST['user_name'];
$user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);
$sql_query = "select * from user_info WHERE user_name
='".mysqli_real_escape_string($con, $user_name)."'";
$result = mysqli_query($con, $sql_query);
$results = mysqli_num_rows($result);
if ($results){
$don = array('result' =>"fail","message"=>"Username exists. User
a different one");
}else{
$sql_query = "insert into user_info
values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query)){
$don = array('result' =>"success","message"=>"Successfully
registered!Well done");
}
}
echo json_encode($don);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.