Home > Net >  Can't connect Android application to local PostgreSQL database
Can't connect Android application to local PostgreSQL database

Time:12-28

I have created a PostgreSQL database and I want to connect an android application with the database. I get this error:

"W/System.err: org.postgresql.util.PSQLException: Something unusual has occurred to cause the driver to fail. Please report this exception."

Here is my code:

public class Dataabase {

    public Dataabase() {

        String jdbcUrl = "jdbc:postgresql://localhost:5432/postgres";
        String username = "postgres";
        String password ="password";

        try {
            Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
            System.out.println("Connected to the database.");
        }
        catch (SQLException e) {
            System.out.println("Connection failed.");
            e.printStackTrace();
        }
    }
}
public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Dataabase db = new Dataabase();
    }
}

What is the problem and how can I fix this?

CodePudding user response:

You are missing Class.forName("org.postgresql.Driver"), above DriverManager.getConnection

CodePudding user response:

localhost:5432 is accessible from the device? if you test in a real device your PostgreSQL server must be in your device network or if the device is connected with the USB cable you can use the ADB port forward to connect to the server.

  • Related