I have created a PostgreSQL database schema and I want to connect an android application with the database. I get this error:
"W/System.err: org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections."
Here is my code:
public class Database {
private Connection connection;
private final String host = "localhost";
private final String database = "postgres";
private final int port = 5432;
private final String user = "postgres";
private final String pass = "password";
private String url = "jdbc:postgresql://%s:%d/%s";
private boolean status;
public Database() {
this.url = String.format(this.url, this.host, this.port, this.database);
connect();
//this.disconnect();
System.out.println("connection status:" + status);
}
private void connect() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(url, user, pass);
status = true;
System.out.println("connected:" + status);
} catch (Exception e) {
status = false;
System.out.print(e.getMessage());
e.printStackTrace();
}
}
});
thread.start();
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
this.status = false;
}
}
public Connection getExtraConnection(){
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
}
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Database db = new Database();
}
}
When I run netstat -a, it's all ok, it accepts TCP connections. I can not find anywhere anything that helps for connecting an Android application with a local PostgreSQL database. What is the problem and how can I fix this?