简体   繁体   中英

Why does my android app doesn't connect to the database?

I know that this question was asked multiple times already, but none of the solution on the forum have worked for me.

I have these 2 files:

MainActivity.java

package com.example.motto_app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.TextView;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainActivity extends AppCompatActivity {

    DatabaseConnection db = new DatabaseConnection();


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

    public void GetData(View v) {

        TextView txA = findViewById(R.id.answerAText);
        TextView txB = findViewById(R.id.answerBText);
        TextView txC = findViewById(R.id.answerCText);
        TextView txD = findViewById(R.id.answerDText);
        String txCORR;
        TextView txQUES = findViewById(R.id.textQuestion);

        String query = "Select * From motto";

        try {
            Statement st = db.getExtraConnection().createStatement();
            ResultSet rs = st.executeQuery(query);

            while (rs.next()) {
                txA.setText(rs.getString(1));
                txB.setText(rs.getString(2));
                txC.setText(rs.getString(3));
                txD.setText(rs.getString(4));
                txCORR = rs.getString(5);
                txQUES.setText(rs.getString(1));
            }

        } catch (Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

    }
}

DatabaseConnection.java

package com.example.motto_app;


import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseConnection {

    private Connection connection;

    private final String host = "localhost";
    private final String database = "test";
    private final int port = 5432;
    private final String user = "postgres";
    private final String password = "1234";
    private String url = "jdbc:postgresql://%s:%d/%s";
    private boolean status;


    public DatabaseConnection() {
        this.url = String.format(this.url, this.host, this.port, this.database, "?gssEncMode=disable");
        connect();

        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, password);
                    status = true;
                    System.out.println("connected: " + status);

                } catch (Exception e) {
                    status = false;
                    System.out.println(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("orh.postgresql.Driver");
            c = DriverManager.getConnection(url, user, password);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return c;
    }
}

When i want to connect to the database i get this:


10/18 12:40:23: Launching 'app' on Pixel 5 API 30.
Install successfully finished in 589 ms.
$ adb shell am start -n "com.example.motto_app/com.example.motto_app.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 9985 on device 'Pixel_5_API_30 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ample.motto_ap: Not late-enabling -Xcheck:jni (already on)
I/ample.motto_ap: Unquickening 12 vdex files!
W/ample.motto_ap: Unexpected CPU variant for X86 using defaults: x86
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
I/System.out: The connection attempt failed.
W/System.err: org.postgresql.util.PSQLException: The connection attempt failed.
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:315)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
W/System.err:     at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:225)
        at org.postgresql.Driver.makeConnection(Driver.java:465)
        at org.postgresql.Driver.connect(Driver.java:264)
        at java.sql.DriverManager.getConnection(DriverManager.java:580)
        at java.sql.DriverManager.getConnection(DriverManager.java:218)
W/System.err:     at com.example.motto_app.DatabaseConnection$1.run(DatabaseConnection.java:35)
        at java.lang.Thread.run(Thread.java:923)
    Caused by: java.net.SocketException: socket failed: EPERM (Operation not permitted)
        at java.net.Socket.createImpl(Socket.java:492)
        at java.net.Socket.connect(Socket.java:619)
        at org.postgresql.core.PGStream.createSocket(PGStream.java:231)
        at org.postgresql.core.PGStream.<init>(PGStream.java:95)
        at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:98)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:213)
        ... 8 more
I/System.out: connection status: false
W/ample.motto_ap: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/ample.motto_ap: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xe9a2bc10, tid 10011
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xe9a2d0a0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xe9a2d0a0: ver 3 0 (tinfo 0xe9d79b50) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xe9a2ce70, tid 10011
D/goldfish-address-space: allocate: Ask for block of size 0x100
    allocate: ioctl allocate returned offset 0x3fb2d7000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_3_0 

I've already tried editing postgresql.conf and pg_hba.conf files , adding uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" or uses-permission android:name="android.permission.INTERNET" and all it gave me were more errors.

I've also tried replacing scram-sha-256 to trust and i got even more errors enter image description here

private String url = "jdbc:postgresql://%s:%d/%s";

private final String host = "localhost";

Are you testing in Emulator or real device? If, emulator then emulator doesn't know about your localhost.

Check your logs:

- Caused by: java.net.SocketException: socket failed: EPERM (Operation not permitted)
- W/System.err: org.postgresql.util.PSQLException: The connection attempt failed.
- D/NetworkSecurityConfig: No Network Security Config specified, using platform default

Check, first error (SocketException) mostly occur in emulator, you have to check this in real device.

Second (PSQLException) it's clear that the connection is not established properly.

Third one (NetworkSecurityConfig), you should use HTTPS not HTTP , if you want to use HTTP connection define your own NetworkSecurityConfig .

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