简体   繁体   中英

How to connect android app kotlin to Postgresql

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")
    }
}```

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.stack.imgur.com/1V9WR.png
  [2]: https://i.stack.imgur.com/p5S3f.png
  [3]: https://www.heroku.com/

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