Today, we will be working on a software connection program for Android with databases located on remote servers. In this example, I used the PostgreSQL 9.4 database. Our server works here as a Client of this database. The example is trivially simple because the application retrieves one value from one table and displays that value on the console. This only demonstrates the solution and the way it works.
I assume the reader of this publication can use JDBC in ordinary Java applications and has some experience in creating even simple Android applications.
First, I run PGAdmin3 and create a table in the database and add three entries to it:
In the project properties I add the downloaded lib to the postgres:
I put it here too:
… until now. We go to the site.
The AsyncTask class extends here. What’s going on? Unlike ordinary Java applications, external (and any other network) connections to Android applications must be covered by a separate thread. Attempting to directly call a DAO method referencing a database and using connectors would end up with an error message (look for the fragment: StrictMode $ androidBlockGuardPolicy). The AsyncTask abstract allows you to run a base reference in a separate thread. The basic operation to be done is described in the “doInBackground” method. The AsyncTask class is described in an article on multithreading. Parameters <String, Void, Double>:
First – Specifies the data type of the input parameter for the doInBackground method. The second specifies the type of the input parameter in the unused method here onProgressUpdate. You must specify the data type returned by the doInBackground method.
In all cases, these could be classes defined by us or object tables. Calling the DAO method must be wrapped in the doInBackground method of the AsyncTask extension class. The additional getKurs (String symbol) method is used here to simplify the call, not necessary.
The call itself is simply calling the method from the site class object:
We must still remember to add the appropriate permissions – we connect to the network. So we add an entry to our manifest file:
After launching, we should see LogCat this type of entry: