I'm developing an android app in android studio and I have a mysql database on my localhost. I'm using XAMPP so I'm using MariaDB and Apache.
When i run the emulator everything works fine but when I use the app in my physical device doesn't work.
I have opened ports 80 and 3306 and give permissions in app manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Java in android activity (I'm using volley for http requests):
public static void Register(String email,String password,Context context){
StringRequest request = new StringRequest(Request.Method.POST, "http://xx.xx.x.x/android/register.php",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
User.setEmail(email);
User.setPassword(password);
Toast.makeText(context, "Registrado con éxito", Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context, MainActivity.class));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Ha ocurrido un error",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);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date());
params.put("date",date);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(request);
}
xx.xx.x.x is my public ip.
register.php:
<?php
if ($_SERVER ['REQUEST_METHOD'] == 'POST'){
require_once("db.php");
$email = $_POST['email'];
$password = $_POST['password'];
$date = $_POST['date'];
$query = "INSERT INTO user (email, password, date) VALUES
('$email','$password','$date')";
$result = $mysql->query($query);
if ($result == TRUE){
echo "user created";
}
else{
echo "user not created";
}
$mysql->close();
}
db.php: The user rafa in my database has all permissions and can connect by any address. (I have tried to change "localhost" to my public ip but it doesn't work either)
<?php
$mysql = new mysqli(
"localhost",
"rafa",
"1234",
"eduk"
);
if ( $mysql->connect_error){
die( "failed to connect" . $mysql->connect_error);
}
And the error I am getting is : Ljava.lang.StackTraceElement;
I readed about the problem and people say that I need a hosting and everything will works fine but why I need it?
The emulator is supposed to act like another device but no physical, it's the only difference. I can access to my apache server with the pyshical device, the problem must be on the connection to database or something. Maybe I need to use other library?