简体   繁体   English

为什么我的 android 应用程序无法连接到数据库?

[英]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主活动.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数据库连接.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.我已经尝试编辑postgresql.confpg_hba.conf 文件,添加uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"uses-permission android:name="android.permission.INTERNET"和所有它给了我更多的错误。

I've also tried replacing scram-sha-256 to trust and i got even more errors enter image description here我还尝试将 scram-sha-256 替换为信任,但我遇到了更多错误,请在此处输入图像描述

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.检查,第一个错误(SocketException)主要发生在模拟器中,您必须在真实设备中检查。

Second (PSQLException) it's clear that the connection is not established properly.其次(PSQLException)很明显连接没有正确建立。

Third one (NetworkSecurityConfig), you should use HTTPS not HTTP , if you want to use HTTP connection define your own NetworkSecurityConfig .第三个(NetworkSecurityConfig),你应该使用HTTPS而不是HTTP ,如果你想使用HTTP连接定义你自己的NetworkSecurityConfig

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM