Android - Data isn't Being Added to MySQL Database - no errors - java

I have been working on creating a login/register feature for an app I'm working on (NOTE: this app is for my own personal use right now, so I'm not looking to make my passwords super secure as of now). When I click the register button when running my app on an emulated Android device, Android Studio doesn't throw any errors, but nothing shows up when I check PHP MyAdmin. I've used different username and password combos (the ones here are obviously examples), a bunch of different localhost/127.0.0.1/10.0.2.2 combinations, and nothing seems to be working. When testing it online, 10.0.2.2:8080/android_login_api/register.php says the page cannot be displayed. localhost:8080/android_login_api/register.php at least displays, but with errors saying there is an unknown host (being 10.0.2.2:8080). Also, I am using Port 8080 with WAMP. Any help would be greatly appreciated, thank you!
register.php:
<?php
$con = mysqli_connect("10.0.2.2:8080" , "EXAMPLE_USERNAME" , "EXAMPLE_PASSWORD" , "android_api");
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
RegisterRequest.java:
package example.com.musicapptest;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Carter Klein on 6/26/2016.
*/
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://10.0.2.2:8080/android_login_api/register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
RegisterActivity.java:
package example.com.musicapptest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText name = (EditText) findViewById(R.id.name);
final EditText email = (EditText) findViewById(R.id.email);
final EditText password = (EditText) findViewById(R.id.password);
final Button registerButton = (Button) findViewById(R.id.btnRegister);
final Button toLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clickName = name.getText().toString();
final String clickEmail = email.getText().toString();
final String clickPassword = password.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
boolean success = jsonResponse.getBoolean(Integer.parseInt("success"));
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(clickName, clickEmail, clickPassword, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}

Apparently you are trying to connect to an invalid mysql host. In the first line of your PHP code the first parameter should be the MySql server address, not the WebServer address.

Related

User Registration using volley library in Android

Using a volley library I am sending a post request to a file register.php which should perform user registration and return JSONResponse after success. The code I have written is working fine in the local server(MAMP) but is not working in the live server. Logcat shows {success = 0} in the live server.
package com.example.androidregisterandlogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText name, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
RequestQueue requestQueue;
private static String URL_REGIST = "https://domainname.com.np/mentordai/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();
}
});
}
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.email.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{
Log.d("TAG",response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")) {
Toast.makeText(MainActivity.this, "Register Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Server code
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO student_users_table (name, email, password) VALUES ('$name', '$email', '$password')";
if ( mysqli_query($connection, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($connection);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($connection);
}
}
?>
```
I'm not an php expert but it looks like your server is the one who return the 'success=0'
And it looks like you have some problem with the if ( mysqli_query($connection, $sql) ) statement, your code going to the else who return the success = 0.
Try to debug the server to see what happens when you send register request.
I think you should put validation at both end (Client as well as server end) on all of your form field . If any one of the field is kept empty your query will not be able to run.
For Validation in server use this at the start of your code
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']))
{
}
To Validate data in Client side use
if(this.name.getText().toString().trim().equals(""))
{
Toast.makeText(MainActivity.this, "Please Enter Name " + e.toString(), Toast.LENGTH_SHORT).show();
}
also for password and email

Login not working on androip app

Hi i'm building an app on android studio which requires register and login,
My registration working fine while i'm having troubles with my login,I'm getting false boolean instead of true even if the username and password are correct,
Here my PHP file:
`$con = mysqli_connect("localhost", "id1013905_trhtkv", "my password",` "id1013905_user");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUserID, $colName, $colUsername, $colAge, $colPassword);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
$response["success"] = true;
$response["name"] = $colName;
$response["age"] = $colAge;
}
}
echo json_encode($response);
?>
My login activity:
package com.ben.owner.say_something;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
final EditText etUsername = (EditText)findViewById(R.id.etUsername);
final EditText etPassword = (EditText)findViewById(R.id.etPassword);
final Button bLogin = (Button)findViewById(R.id.bLogin);
final TextView registerLink = (TextView)findViewById(R.id.tvRegisterHere);
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
final 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){
String name = jsonResponse.getString("name");
int age = jsonResponse.getInt("age");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name",name);
intent.putExtra("username",username);
intent.putExtra("age",age);
LoginActivity.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username,password,responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
And my login request:
package com.ben.owner.say_something;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by owner on 09/03/2017.
*/
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "https://saysomething.000webhostapp.com/Login.php";
private Map<String, String> params;
public LoginRequest(String username,String password, Response.Listener<String> listener){
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
To find your bug I just would suggest to retrieve server values in the responce.
I mean
instead of
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
$response["success"] = true;
$response["name"] = $colName;
$response["age"] = $colAge;
}
}
echo json_encode($response);
use
$response = array();
$response["success"] = false;
echo $statement;//or something like
while(mysqli_stmt_fetch($statement)){
if (password_verify($password, $colPassword)) {
echo $password;
echo $colPassword;
$response["success"] = true;
$response["name"] = $colName;
$response["age"] = $colAge;
}
}
echo json_encode($response);
or debug your server side. It seems your server code is wrong.
check this example
http://php.net/manual/en/mysqli-stmt.fetch.php

Sending data from Android to SQL database using PHP

I was following this tutorial in which I was building login and registration app:
https://www.youtube.com/watch?v=T7Z4GVFaT4A
I've changed PHP and tested it by passing some arguments through address field, but when I'm clicking register button nothing happens.
There are some things in OnResponse function that should be doing something, something should be added to database, but nothing happens.
I was wondering if maybe anything at all is being send from app if I'm not getting any response.
Also, what's troubling me, function OnResponse is never called, but it should be.
Instead of using some ASP I create server using WAMP. Below there are Java and PHP files that are crucial to this problem.
RegisterRequest.java
package com.example.dominik.praca;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Dominik on 28.12.2016.
*/
public class RegisterRequest extends StringRequest {
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.ugu.pl/Register.php";
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.byethost3.com/Register2.php";
private static final String REGISTER_REQUEST_URL = "http://127.0.0.1/kulturnik/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
RegisterActivity.java
package com.example.dominik.praca;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etName = (EditText) findViewById(R.id.etName);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.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(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
AlertDialog.Builder builderSuccess = new AlertDialog.Builder(RegisterActivity.this);
builderSuccess.setMessage("Rejestracja zakończona powodzeniem")
.create()
.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Błąd rejestracji")
.setNegativeButton("Ponów", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
And Register.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$con = mysqli_connect("localhost", "root", "", "kulturnik");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
print_r(json_encode($response));
?>
Use Async task for faster send & retrieval to/fro server. Just create an object of the class and use execute function to pass parameters and start asynchronous sending and retrieval to/fro the server.
eg:- SendtoPhp stp = new SendtoPhp();
stp.execute(tname, phone)
public class SendtoPhp extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String tname = params[0]; //parameters you need to send to server
String phone = params[1];
String data = "";
int tmp;
try {
URL url = new URL("http://your.server.com/"); //url to php code
String urlParams = "tname=" + tname + "&tphone=" + phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
//System.out.println(data);
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
try {
//You might receive something on server code execution using JSON object
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Registration data not being sent to my database

My login is working properly, but my registration seems to not add the data to my database. I have tried to solve the problem for a long time with no luck. Maybe some of you "bright" people can help my dumb ass lol! Nevertheless here is everything: If you do help me, thanks in advance, btw I think it is a problem in the Register.php!
LoginActivity.java:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
final Button bLogin = (Button) findViewById(R.id.bSignIn);
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
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) {
String name = jsonResponse.getString("name");
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
LoginRequest.java:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class LoginRequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "https://mysite567356ht7ieyjr6u7je.000webhostapp.com/Login.php";
private Map<String, String> params;
public LoginRequest(String username, String password, Response.Listener<String> listener) {
super(Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Login.php:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name, $username, $password);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["name"] = $name;
$response["username"] = $username;
$response["password"] = $password;
}
echo json_encode($response);
?>
RegisterActivity.java:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.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(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
RegisterRequest.java:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "https://mysite567356ht7ieyjr6u7je.000webhostapp.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Register.php:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
mysqli_stmt_bind_param($statement, "siss", $name, $username, $password);
In this line change siss to sss.

Login/Register app using volley

I am making an android application using android studio for Login/Register and i failed to send the Register information to the .php file.
Here is my code:
For LoginActivity :
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
final String password = etPassword.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(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
For RegisterActivity:
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
final String password = etPassword.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(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
For RegisterRequest:
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://mydomain.hostei.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, int age, String password, Response.Listener<String> listener) {
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("age", age + "");
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
And the Register.php:
$con = mysqli_connect("mysql10.000webhost.com", "a3288368_user", "abcd1234", "a3288368_data");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, age, username, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $age, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
The communication between my database and the Register.php file working properly putting values by hand in the Register.php file.
But when i am waiting the values form the POST method i failed to communicate between my application and the Register.php
I have added internet permission to my project already,also compiled the volley library.
Any ideas what is going wrong?
Maybe there is a mistake on my Java code?
Thanks
Problem fixed.The error was on the php code
I changed echo json_encode($response);
with print_r(json_encode($response));

Categories