简体   繁体   中英

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 I try to make an instance of the same class on my APP (in a virtual Android emulator), I got this log cat;

06-27 01:16:49.405 11469-11469/setup.hola2 I/System.out﹕ ***** PostgreSQL JDBC Connection Testing ***** 06-27 01:16:49.407 11469-11469/setup.hola2 I/System.out﹕ PostgreSQL JDBC Driver Registered! 06-27 01:16:49.424 11469-11469/setup.hola2 W/System.err﹕ Connection Failed, Check console |||||||||||||||| 06-27 01:16:49.424 11469-11469/setup.hola2 W/System.err﹕ Something unusual has occurred to cause the driver to fail. Please report this exception. 06-27 01:16:49.543 11469-11485/setup.hola2 W/EGL_emulation﹕ eglSurfaceAttrib not implemented 06-27 01:16:49.543 11469-11485/setup.hola2 W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5479360, error=EGL_SUCCESS

So in resume the connection works outside of the Android App...

I guess that this can happen cause I have to use the class "extends AsyncTask" on my Class, but I couldn't... can someone give me some help here?

On the MainActivity.java:

@Override
public void onSelectedDayChange(CalendarView view, int year, int month,
                            int dayOfMonth) {
//Toast.makeText(getApplicationContext(), ""+dayOfMonth, 0).show();// TODO                Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hola !!!", 0).show();// TODO Auto-generated method stub
txtConsulta = consulta1.iniciar();
miEditText.setText(txtConsulta);
}

And the connection class is this:

package setup.hola2;

import android.os.AsyncTask;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

public class PostgreSqlJDBC {

private static final String DB_DRIVER = "org.postgresql.Driver";


public static void main(String[] argc) {
    String x = iniciar();
}

public static String iniciar()  {

    System.out.println("***** PostgreSQL JDBC Connection Testing *****");

    try {
        Class.forName(DB_DRIVER);
    } catch (ClassNotFoundException e) {
        System.err.println("Please add PostgreSQL JDBC Driver in your Classpath ");
        System.err.println(e.getMessage());
        return "Please add PostgreSQL JDBC Driver in your Classpath ";
    }

    System.out.println("PostgreSQL JDBC Driver Re`enter code here`gistered!");

    Connection connection1;
    Statement stmt = null;

    try {

        String url = "jdbc:postgresql://localhost:5432/ulife";
        connection1 = DriverManager.getConnection(url, "postgres","XXXXX");

    } catch (SQLException e) {
        System.err.println("Connection Failed, Check console ||||||||||||||||");
        System.err.println(e.getMessage());
        return e.getMessage();
    }

    if (connection1 == null) {
        System.out.println("Connection Failed !");
    } else {
        System.out.println("Connection established!");


        try {
            stmt = connection1.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM activities");

            while (rs.next()) {
                int id = rs.getInt("IdActivity");
                String Nombre = rs.getString("NameActivity");

                System.out.println("Id = " + id);
                System.out.println("Nombre = " + Nombre);
                System.out.println("------------------------");
            }

            rs.close();
            stmt.close();

            return "String desde clase";

        } catch (SQLException e) {
            System.out.println("Falló conexión a la Bdd Ulife");
            e.printStackTrace();
            return "Falló conexión a la Bdd Ulife";
        }
    }
    return "fin";
   }
}

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM