简体   繁体   English

无法将我的Android Studio应用与PostgreSQL连接

[英]Cant connect my Android Studio App with PostgreSQL

I'm starting devolop, and I have this issue. 我正在启动devolop,并且遇到了这个问题。 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; 我可以连接到postgresql的本地服务器(在PGADMIN上测试并在Android Studio的界面上运行JAVA程序。但是,当我尝试在我的APP(在虚拟的Android仿真器中)创建相同类的实例时,我得到了原木猫;

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.405 11469-11469 / setup.hola2 I / System.out:***** PostgreSQL JDBC连接测试***** 06-27 01:16:49.407 11469-11469 / setup.hola2 I / System.out:PostgreSQL JDBC驱动程序已注册! 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:连接失败,检查控制台||||||||||||||||| 06-27 01:16:49.424 11469-11469/setup.hola2 W/System.err﹕ Something unusual has occurred to cause the driver to fail. 06-27 01:16:49.424 11469-11469 / setup.hola2 W / System.err:发生异常情况导致驱动程序出现故障。 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 06-27 01:16:49.543 11469-11485 / setup.hola2 W / EGL_emulation:eglSurfaceAttrib未实现06-27 01:16:49.543 11469-11485 / setup.hola2 W / OpenGLRenderer:无法在表面0xa5479360上设置EGL_SWAP_BEHAVIOR = EGL_SUCCESS

So in resume the connection works outside of the Android App... 因此,在恢复连接时,该连接在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? 我猜可能会发生这种情况,因为我必须在类上使用“扩展AsyncTask”类,但是我不能...有人可以在这里给我一些帮助吗?

On the MainActivity.java: 在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: 终于成功了,解决方案是扩展AsyncTask,使Android保护运行时环境免受冻结进程的影响,因此,当您扩展AsyncTask启动另一个paralell线程时,在恢复中您必须扩展连接类,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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