簡體   English   中英

為什么我的 android 應用程序無法連接到數據庫?

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

我知道這個問題已經被問過很多次了,但是論壇上的解決方案都沒有對我有用。

我有這兩個文件:

主活動.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();
        }

    }
}

數據庫連接.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;
    }
}

當我想連接到數據庫時,我得到了這個:


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 

我已經嘗試編輯postgresql.confpg_hba.conf 文件,添加uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"uses-permission android:name="android.permission.INTERNET"和所有它給了我更多的錯誤。

我還嘗試將 scram-sha-256 替換為信任,但我遇到了更多錯誤,請在此處輸入圖像描述

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

private final String host = "localhost";

你是在模擬器還是真機上測試? 如果,模擬器,則模擬器不知道您的本地主機。

檢查您的日志:

- 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

檢查,第一個錯誤(SocketException)主要發生在模擬器中,您必須在真實設備中檢查。

其次(PSQLException)很明顯連接沒有正確建立。

第三個(NetworkSecurityConfig),你應該使用HTTPS而不是HTTP ,如果你想使用HTTP連接定義你自己的NetworkSecurityConfig

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM