Good day, I am trying to send parameters to connect to a database PosgreSQL
from Android
PHP, previously I had already carried out this functionality but using MySQL
as database and using mysqli
in PHP
but now it is different, I am using PostgreSQL
as database and PDO
in PHP
.
Let me explain: I need an application which, when starting, type the name of the database in a EditText
to later connect to the database that has been typed, the database is hosted in PostgreSQL and the connection is already established, now I need that the default variable $db_name
is empty but that the value is assigned when the name of the database is entered in the EditText
from Android
.
I will show the code I have so far:
First I have my script PHP
:
<?php
class Conexion{
function Conectar(){
$db_name = $_POST['db_name'];
try{
$conexion = new PDO("pgsql:host=".'MiHost'.";port=5432;db_name=".$db_name,'MiUsuario','MiContraseña');
return $conexion;
}catch(Exception $error){
die("El error de conexion es: ".$error->getMessage());
}
}
}
?>
-I have created my connection class and my connect function inside the connect function I have created a variable without any data because it is the data that I have to bring fromAndroid
-Then I have the parameters that I am passing: $conexion = new PDO("pgsql:host=".'MiHost'.";port=5432;dbname=".$db_name,'MiUsuario','MiContraseña');
Here there is not much to comment on, it is just a simple connection to PostgreSQL
, however, it should be noted that in this part: dbname=".$db_name
I am passing the variable that I need to obtain from Android
so that the connection is dynamic, until this period I suppose that is already understood but it is as simple as assigning the value EditText
of Android
to the variable of PHP
.
Until here everything would be relatively well from my point of view.
Now we go to Android Studio , as I explained at the beginning, I already had a similar process with MySQL , therefore I have used the same code, which is the following:
It would start by showing Dialog
where you would write the database name:
private void showAlertWithTextInputLayout2(Context context) {
EditText editText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Dirección IP")
.setMessage("Por favor, ingrese el nombre de la base de datos\n\nEvite utilizar otro tipo de caracteres y escriba el nombre de la base de datos de forma correcta")
.setView(editText)
.setPositiveButton("Realizado", (dialogInterface, i) -> {
getBaseDeDatos = editText.getText().toString().trim();
baseDeDatos = getBaseDeDatos;
new Handler().postDelayed(() -> {
Intent i2 = new Intent(SplashPrincipal.this, Login.class);
startActivity(i2);
}, 5000);
try {
enviarParametro();
} catch (IOException e) {
e.printStackTrace();
}
})
.create();
dialog.show();
}
Below the intent I have a method called sendParameter() this is the one that would help us send the parameter to PHP
, which is like this:
public void enviarParametro() throws IOException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://"+SplashPrincipal.host+":8080/conexiones/conexion.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("database", baseDeDatos);
String query = builder.build().getEncodedQuery();
OutputStream output = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
writer.write(query);
System.out.println(query);
writer.flush();
writer.close();
output.close();
connection.connect();
}
Now returning to the first method sendParameter() we realize that in the line Uri.Builder builder = new Uri.Builder().appendQueryParameter("database", baseDeDatos);
I pass two parameters, the first is the variable that is in PHP
-> database
and the second is the variable that I write in in EditText
->baseDeDatos
This is where I have what I have done, and despite the fact that I have done a lot of research and have done different tests, I do not get the expected result, so surely there is another way to PDO
either do something wrong or something I have to change, whatever it is, honestly I don't know what else I could do.
Without further ado I hope someone can help me solve the problem thank you very much in advance!!!
Firstly, it is not advisable to disable the policy to perform operations on the main thread:
you must use for example an AsyncTask, How to use AsyncTask?
The problem is that the host value probably belongs to a url that you can't make the request to.
You must ensure that this url is published and can be used by the device, do not use
localhost
, if it is an IP ensure that it is static.Connection between Android studio and PostgreSQL replace localhost with my ip