1

I'm doing a project at school where I need to connect a website and my android app to a PostgreSQL database, I have tried to connect directly using JDBC, but it didn't work at all. I also have read about using some API, but I didn't understand how to do it I'm clueless about what to do now Does anyone know how to connect an android app to PostgreSQL? I will be eternally grateful I really need to do finish this project.

Edit : The problem with jdbc is that console always printed "Connection failed" Here is my JDBC attempt

import java.sql.DriverManager

class Database {
    private var connection: Connection? = null
    private val host = "i replaced this so i dont lose controll over the database*eu-west-1.compute.amazonaws.com" // For Google Cloud Postgresql
    private val database = "*****mcl8"
    private val port = ****
    private val user = "****wwzntag"
    private val pass = "*****2c82a7dd7"
    private var url = "jdbc:postgresql://xhlgovzwwzntag:ccf199dc***********cb6a1865e87e7532da842c82a7dd7@ec2-34-255-134-200.eu-west-1.compute.amazonaws.com:5432/d2rlvf0bcqmcl8"
    private var status = false
    private fun connect() {
        val thread = Thread {
            try {
                Class.forName("org.postgresql.Driver")
                connection = DriverManager.getConnection(url, user, pass)
                status = true
                println("connected:$status")
            } catch (e: Exception) {
                status = false
                print(e.message)
                e.printStackTrace()
            }
        }
        thread.start()
        try {
            thread.join()
        } catch (e: Exception) {
            e.printStackTrace()
            status = false
        }
    }

    val extraConnection: Connection?
        get() {
            var c: Connection? = null
            try {
                Class.forName("org.postgresql.Driver")
                c = DriverManager.getConnection(url, user, pass)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return c
        }

    init {
        url = String.format(url, host, port, database)
        connect()
        //this.disconnect();
        println("connection status:$status")
    }
}```
4
  • JDBC is the only option i know to connect it directly, another way is using web services. Maybe SO can help with your JDBC connection. Commented May 6, 2021 at 20:14
  • ok i talked with some people and they recommended using some web service for security reasons could u guide me trough it? link a video or some documentation about it? i have searched it and i didnt understand at all how to use it Commented May 6, 2021 at 20:17
  • You need to create a REST API Commented May 6, 2021 at 21:17
  • @cutiko thanks man! Commented May 6, 2021 at 21:36

1 Answer 1

1

The answer is quite simple, just like @cutiko said i needed to create a rest API (that is a backend website that connects directly with the database, then i send the data to the website and the site does the rest of the communication with the database) [image that explains how it works][1]

To make the Api i used node.js, express and sequilize, here is a link that explains how to do it: https://scotch.io/tutorials/getting-started-with-node-express-and-postgres-using-sequelize

here is an example of how i made the connection from android studio (Kotlin) to the api: this is a simple login request where the database returns a bool (false if the user cant login, true if the user can) the following image shows the API returning the data (false or true), i wrote an email and a password that obviously doesnt exist, if i wrote an email and a password that exists in the database the API would return true instead [API returning the data][2]

                mQueue = Volley.newRequestQueue(this);
                var url = "https://thisismylink.herokuapp.com" + "/utilizador/login/" + email + "/" + password
                val request = JsonArrayRequest(Request.Method.GET, url, null, Response.Listener { response ->
                    try {

                        var jsonArray = JSONArray()
                        jsonArray = response.getJSONArray(0)
                        for (i in 0 until jsonArray.length()) {
                            val jsonObject: JSONObject? = jsonArray.getJSONObject(i)
                            //val user = jsonArray.getJSONObject(i)
                            //val bool = jsonObject.getBoolean("login")
                            val boo: Boolean = jsonObject!!.getBoolean("login")

                            if (boo == false) {
                                Toast.makeText(this, "Credenciais Inválidas", Toast.LENGTH_SHORT).show();
                                dialog.hide()
                            } else if (boo == true) {
                                //Toast.makeText(this, email, Toast.LENGTH_SHORT).show();
                                //Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
                                val intent = Intent(this, Home::class.java)
                                startActivity(intent)
                                finish()
                            }
                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }, Response.ErrorListener { error -> error.printStackTrace() })
                mQueue?.add(request)```


Edit: I also used heroku that hosts databases and entire sites [https://www.heroku.com/][3]


  [1]: https://i.sstatic.net/1V9WR.png
  [2]: https://i.sstatic.net/p5S3f.png
  [3]: https://www.heroku.com/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.