the app is connecting with api but data is not being entered into database it error message on unseccesful success.
how to solve it?
This is my register.php code.
if ($_SERVER['REQUEST_METHOD'] =='POST') {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$emailid = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'uconnection.php';
$sql = "INSERT INTO user (firstname, lastname, email, password, confirmpassword) VALUES ('$fname', '$lname', '$emailid', '$cpassword')";
if ( mysqli_query($conn, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
This is my android mainactivity code of android app.
public class MainActivity extends AppCompatActivity {
private EditText fname,lname,emailid,password,cpassword;
private Button buttonregister;
private ProgressDialog pDialog;
private static String URL_REGISTER = "http://192.168.68.74:80/loginregistervollyphp/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fname = findViewById(R.id.edtxt_fname);
lname = findViewById(R.id.edtxt_lname);
emailid = findViewById(R.id.edtxt_emailid);
password = findViewById(R.id.edtxt_password);
cpassword = findViewById(R.id.edtxt_cpassword);
buttonregister = findViewById(R.id.btn_r_signup);
buttonregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register_user();
}
});
}
/**
* Display Progress bar while registering
*/
private void displayLoader() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Signing Up.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
private void register_user(){
displayLoader();
final String fname = this.fname.getText().toString().trim();
final String lname = this.lname.getText().toString().trim();
final String emailid = this.emailid.getText().toString().trim();
final String password = this.password.getText().toString().trim();
final String cpassword = this.cpassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
Log.d("sucs",success);
if (success.equals("1")){
Toast.makeText(MainActivity.this, "Register Successful :) ", Toast.LENGTH_SHORT).show();
}
else if (success.equals("0")){
Toast.makeText(MainActivity.this, "Register Error!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error :( "+ e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Register Error :("+ error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("fname",fname);
params.put("lname",lname);
params.put("email",emailid);
params.put("password",password);
params.put("cpassword",cpassword);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Make changes in your code as follows :
header("Content-Type: application/json"); //add this in your php code
if ( mysqli_query($conn, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
} else {
$result["success"] = "0";
$result["message"] = "error";
}
echo json_encode($result);
mysqli_close($conn);
Related
When I try to add new user in registration form I have an error and nothing to add in users_table. Also this error when I try to login.
I use xampp for phpmyadmin, running MySQL, Apache and PHP. I tried to realize registration and login with database and have error 404. Please help fix this.
public class registration extends AppCompatActivity {
private TextView loginReg;
private EditText email, username, password;
private Button signUp;
private static String URL_REGIST = "http://XXX.XX.XX.X/android_register_login/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
loginReg = (TextView) findViewById(R.id.loginReg);
email = findViewById(R.id.emailReg);
username = findViewById(R.id.usernameReg);
password = findViewById(R.id.passwordReg);
signUp = findViewById(R.id.signUp);
loginReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openLogin();
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Register();
}
});
}
public void openLogin(){
Intent intent = new Intent(this, com.example.myfirstjavaapp.MainActivity.class);
startActivity(intent);
}
private void Register(){
final String email = this.email.getText().toString().trim();
final String username = this.username.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(registration.this,"Register success!", Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(registration.this,"Register error!"+ e.toString(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(registration.this,"Register error!"+ error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
This is PHP code.
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$username = filter_input(INPUT_POST, 'username');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO users_table (username, email, password) VALUES ('$username', '$email', '$password')";
if ( mysqli_query($conn, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
?>
E/Volley: [696] BasicNetwork.performRequest: Unexpected response code 404 for http://XXX.XX.XX.X/android_register_login/register.php
the api login.php is correct but some problem in java code in android studio but not understanding the problem?need help in code?
I have tried my method but it dosen't solve my problem.
this is my login.php code.
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
require_once 'uconnection.php';
$data = json_decode(file_get_contents("php://input"));
if (!$data) {
$result['success'] = "0";
$result['message'] = "Login payload missing. Send email and password in the request header.";
echo json_encode($result);
mysqli_close($conn);
} else {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $data->email;
$password = $data->password;
if ($email != null && $password != null) {
$sql = "SELECT * FROM user WHERE email='" . $email . "' AND password='" . $password . "' ";
$response = mysqli_query($conn, $sql);
// var_dump($response);
// echo $response->num_rows;
// echo "--";
// echo mysqli_num_rows($response);
// echo "--";
$result = array();
$result['login'] = array();
// echo "OUTSIDE";
if (mysqli_num_rows($response) > 0) {
// echo "Found";
$row = mysqli_fetch_assoc($response);
print_r($row);
// echo $row["password"];
if ($email == $row["email"] && $password == $row["password"]) {
// echo "VERIFIED";
$index['firstname'] = $row['firstname'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}
} else {
$result['success'] = "0";
$result['message'] = "Incorrect username and/or password";
echo json_encode($result);
mysqli_close($conn);
}
} else {
if ($email == null) {
$result['success'] = "0";
$result['message'] = "email missing";
echo json_encode($result);
mysqli_close($conn);
}
if ($password == null) {
$result['success'] = "0";
$result['message'] = "password missing";
echo json_encode($result);
mysqli_close($conn);
}
}
} else {
$result['success'] = "0";
$result['message'] = "only POST request possbile";
echo json_encode($result);
mysqli_close($conn);
}
}
And this is android java login class code.
private EditText emailid,password;
private Button buttonlogin,buttonregister1;
private ProgressDialog pDialog;
String emailid_login, password_login;
private static String URL_LOGIN = "http://192.168.68.74:80/loginregistervollyphp/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailid = findViewById(R.id.etxt_email);
password = findViewById(R.id.etxt_password);
buttonlogin = findViewById(R.id.btn_login);
buttonregister1 = findViewById(R.id.btn_register);
buttonregister1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i1 = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i1);
finish();
}
});
buttonlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailid_login = emailid.getText().toString().trim();
password_login = password.getText().toString().trim();
if (!emailid_login.isEmpty() && !password_login.isEmpty()){
login(emailid_login,password_login);
}
else {
emailid.setError("Please insert Email id");
password.setError("Please insert Password");
}
}
});
}
private void displayLoader() {
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Loging In... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
private void login(final String email, final String password){
displayLoader();
StringRequest stringRequest = new StringRequest(Request.Method.POST,URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
Log.d("LOGINSUCCESS", String.valueOf(jsonObject));
if (!success.equals("0")){
String email2 = jsonObject.getString("email").trim();
String fname = jsonObject.getString("firstname").trim();
Intent intent = new Intent(LoginActivity.this,UserDashboard.class);
intent.putExtra("email",email2);
intent.putExtra("firstname",fname);
startActivity(intent);
}else if (success.equals("0")){
Toast.makeText(LoginActivity.this, "Error! Logging In", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(LoginActivity.this, "Error Loging in: "+e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(LoginActivity.this, "Error Loging in: "
+error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I'm running an app quiz with 2 table like this https://gyazo.com/641f6e45006ab4f6d962a81d60e1ba69 , https://gyazo.com/be10c2f550f63b4ebc55eda61c3f0f15.
My register -login activity works fine but the issue is when I try to send the score value to database. No errors and no message that's running. Can you help me please?
public class Results extends AppCompatActivity implements OnClickListener {
private Button bt_save;
private TextView tv_label;
int totalscore ;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
tv_label = (TextView) findViewById(R.id.tv_label);
Button bt_Begin = (Button) findViewById(R.id.bt_Begin);
bt_save = (Button)findViewById(R.id.bt_save);
bt_save.setOnClickListener(this);
SharedPreferences sharedPreferences = getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
Integer result = sharedPreferences.getInt("rightAnswerCount", 0);
SharedPreferences sharedPreferencess = getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
Integer results = sharedPreferencess.getInt("rightAnswerCountt",0);
totalscore=(result+results);
tv_label.setText("" +totalscore);
}
private void saveRequest() {
final String score = tv_label.getText().toString().trim();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Registrating user...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.RESULT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> key = new HashMap<>();
key.put("totalscore", score+"");
return key;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View view) {
if (view == bt_save)
saveRequest();
}
this is my php file dbOp1
<?php
class dbOperation1{
private $con;
function __construct(){
require_once dirname(__FILE__).'/connect.php';
$db = new connect();
$this->con = $db->connect();
}
public function saveScore($score){
$stmt = $this->con->prepare("INSERT INTO `test_score`(`id`,`score`) VALUES(NULL, ?);");
$stmt->bind_param("i",$score);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
?>
And this is my Result php:
<?php
error_reporting(0);
require_once 'dbOp1.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
isset($_POST['score']))
{
$db = new dbOperation1();
$result = $db->saveRequest(
$_POST['score']
);
if($result == 1){
$response['error'] = false;
$response['message'] = "User registered sussessfully";
}elseif($result == 2){
$respone['error'] = true;
$response['message'] = "Some error";
}
}
}
echo json_encode($response);
I have a php script for handling very basic registration. its in a folder in my localhost; http://(ipaddress/localhost):3306/testing/Register.php. Android studio points to this URL but i get no error output when i run the emulator. When i open the PHP script in the browser, everything looks good.
Here is the registerrequest java script:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://(ipaddress/localhost):3306/testing/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
here is my createuser script
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
finally, here is my PHP script, Register; m
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
if(!$statement) { printf("Prepare failed: %s\n", mysqli_error($con)); }
if(!$statement) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
mysqli_stmt_bind_param($statement, "ssi",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
if(mysqli_error($statement)) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
Im using xampp (apache and mysql turned on) and my Register is in a folder in Htdocs.
Thank you in advance for any help!
You could modify constructor of RegisterRequest:
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener() errListener){ //add error listener
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
......
}
And in CreateUser class file, add below:
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, String.valueOf(error), Toast.LENGTH_SHORT).show();
}
}
Then:
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,
responseListener,errorListener);
Now, run again and when error occured, you could see it in error listener.
I'm creating registration form on my localhost, form works as it should, I can register user when using Postman, but when I try to register user from my Android app I only get blank Toast message and user is not registered.
Here's my code:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private EditText editTextUsername, editTextEmail, editTextPassword;
private Button buttonRegister;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
progressDialog = new ProgressDialog(this);
buttonRegister.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonRegister){
registerUser();
}
}
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String username = editTextUsername.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
progressDialog.setMessage("Registering user...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
Constants.java
public class Constants {
private static final String ROOT_URL = "http://192.168.56.2/Android/v1/";
public static final String URL_REGISTER = ROOT_URL+"registerUser.php";
}
RequestHandler.java
public class RequestHandler {
private static RequestHandler mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private RequestHandler(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized RequestHandler getInstance(Context context) {
if (mInstance == null) {
mInstance = new RequestHandler(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
What am I doing wrong?
First of all give Internet permission to your project.
Then use a php script like this one adapted to your needs:
<?php
$connect = mysqli_connect("mysql.hostinger.gr", "u305474665_xxxxx", "xxxxxxxx", "u305474665_xxxxx");
$name = isset($_POST["name"]) ? $_POST["name"] : '';
$username = isset($_POST["username"]) ? $_POST["username"] : '';
$age = isset($_POST["age"]) ? $_POST["age"] : '';
$password = isset($_POST["password"]) ? $_POST["password"] : '';
function registerUser() {
global $connect, $name, $age, $username, $password;
$statement = mysqli_prepare($connect, "INSERT INTO User (name,username,age, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $name, $username, $age, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
};
function usernameAvailable() {
global $connect, $username;
$statement = mysqli_prepare($connect, "SELECT * FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
if ($count < 1){
return true;
}
else {
return false;
}
};
$response = array();
$response["success"] = false;
if (usernameAvailable()){
registerUser();
$response["success"] = true;
}
print_r(json_encode($response));
?>
Last but very important: Define a retry policy Recursively on your error Listener.