Cant Connect My Android Studio App With Postgresql
I'm starting devolop, and I have this issue. I can connect to a localhost server of postgresql (tested on PGADMIN and run JAVA program on the interface of Android Studio. But when
Solution 1:
Finally it works, the solution is just to extends AsyncTask, cause Android protect the run time enviroment from frozen process, so when you extend AsyncTask start another paralell thread, in resume you have to extends the connection class like this:
public class PostgreSqlJDBC extends AsyncTask <Void, Void, Void> {
static String cadenaConexion = "jdbc:postgresql://YOUR_HOST/YOUR_BDD?" + "user=postgres&password=YOURPASSWORD";
static String respuestaSql= "vacia";
public PruebaConn() {
}
public String getRespuestaSql (){
execute();
return respuestaSql;
}
@Override
public Void doInBackground(Void... params) {
Connection conexion = null;
Statement sentencia = null;
ResultSet resultado = null;
try {
Class.forName("org.postgresql.Driver");
conexion = DriverManager.getConnection(cadenaConexion);
sentencia = conexion.createStatement();
String consultaSQL = "SELECT * FROM activities";
resultado = sentencia.executeQuery(consultaSQL);
respuestaSql = "";
while (resultado.next()) {
int id = resultado.getInt("IdActivity");
String Nombre = resultado.getString("NameActivity");
respuestaSql = respuestaSql + id + " | " + Nombre + "\n";
}
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
System.err.println("Error: Cant connect!");
conexion = null;
} finally {
if (resultado != null) {
try {
resultado.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
if (sentencia != null) {
try {
sentencia.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
if (conexion != null) {
try {
conexion.close();
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getMessage());
}
}
}
System.err.println("----- PostgreSQL query ends correctly!-----");
return null;
}
}
Post a Comment for "Cant Connect My Android Studio App With Postgresql"