GA_Lazy 2019-11-14 01:51 采纳率: 0%
浏览 2372

安卓开发JDBC连接数据库No static method metafactory错误怎么解决?

直接上代码
JdbcUtil类

package com.example.myapplication;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class JdbcUtil {
    private static JdbcUtil instance;

    public static JdbcUtil getInstance(){
        if (instance ==null){
            instance = new JdbcUtil();
        }
        return instance;
    }
    public Connection getConnection(String dbName,String name,String password) {
        try {
            new com.mysql.cj.jdbc.Driver();
            String url = "jdbc:mysql://localhost:3306/"+dbName;
            return DriverManager.getConnection(url,name,password);
        } catch (Exception e) {
            return null;
        }
    }

    public Connection getConnection(String file){
        File f = new File(file);
        if(!f.exists()){
            return null;
        }else {
            Properties pro = new Properties();
            try {
                Class.forName("com.mysql.jdbc.Driver");
                pro.load(new FileInputStream(f));
                String url = pro.getProperty("url");
                String name = pro.getProperty("name");
                String password = pro.getProperty("password");
                return DriverManager.getConnection(url,name,password);
            }catch (Exception e){
                return null;
            }
        }
    }
}

UserDao类

package com.example.myapplication;

import android.util.Log;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static android.content.ContentValues.TAG;

public class UserDao {

    JdbcUtil jdbcUtil = JdbcUtil.getInstance();
    //第一个参数为数据库名称,第二个参数为数据库账号 第三个参数为数据库密码
    Connection conn = jdbcUtil.getConnection("test","root","LHMbdbqandr2015");
    //注册
    public  boolean register(String name,String password){
        if (conn==null){
            Log.i(TAG,"register:conn is null");
            return false;
        }else {
            //进行数据库操作
            String sql = "insert into user(name,password) values(?,?)";
            try {
                PreparedStatement pre = conn.prepareStatement(sql);
                pre.setString(1,name);
                pre.setString(2,password);
                return pre.execute();
            } catch (SQLException e) {
                return false;
            }finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //登录
    public boolean login(String name,String password){
        if (conn==null){
            Log.i(TAG,"register:conn is null");
            return false;
        }else {
            String sql = "select * from user where name=? and password=?";
            try {
                PreparedStatement pres = conn.prepareStatement(sql);
                pres.setString(1,name);
                pres.setString(2,password);
                ResultSet res = pres.executeQuery();
                boolean t = res.next();
                return t;
            } catch (SQLException e) {

                return false;
            }

        }
    }
}

MainActivity文件

package com.example.myapplication;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.os.Trace;


import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
    private static  final  String TAG="MainActivity";
    private EditText name;
    private EditText password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = findViewById(R.id.name);
        password = findViewById(R.id.password);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                requestPermissions(new String[]{Manifest.permission.INTERNET},1);
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return;
            }
        }
    }
    //用户根据点击事件来找到相应的功能
    public void fun(View v){
        switch (v.getId()){
            case R.id.register:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String n = name.getText().toString().trim();
                        String psw = password.getText().toString().trim();
                        UserDao ud = new UserDao();
                        boolean result =ud.register(n,psw);
                        if (!result){
                            Looper.prepare();
                            Toast toast = Toast.makeText(MainActivity.this,"注册成功!",Toast.LENGTH_SHORT);
                            toast.show();
                            Looper.loop();
                        }
                        Log.i(TAG,"fun"+result);

                        //以上为jdbc注册
                    }
                }).start();
                break;
            case R.id.login:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String n = name.getText().toString().trim();
                        String psw = password.getText().toString().trim();
                        if (n.equals("")||psw.equals("")){
                            Looper.prepare();
                            Toast toast = Toast.makeText(MainActivity.this,"输入不能为空!",Toast.LENGTH_SHORT);
                            toast.show();
                            Looper.loop();
                        }
                        UserDao ud = new UserDao();
                        Boolean result = ud.login(n,psw);
                        if (!result){
                            Looper.prepare();
                            Toast toast=Toast.makeText(MainActivity.this,"用户名不存在或密码错误!",Toast.LENGTH_SHORT);
                            toast.show();
                            Looper.loop();
                        }else{
                            Looper.prepare();
                            Toast toast=Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT);
                            toast.show();

                            //一下代码为跳转界面
                            // Intent intent=new Intent(MainActivity.this,info.class);
                            //intent.putExtra("name",n);
                            // startActivity(intent);
                            Looper.loop();

                        }

                        //以上为jdbc登录
                    }
                }).start();

        }

    }
}

现在遇到的问题如下


11/14 01:40:49: Launching 'app' on Nexus 5X API 29 x86.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 23852 on device '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/e.myapplicatio: Not late-enabling -Xcheck:jni (already on)
E/e.myapplicatio: Unknown bits set in runtime_flags: 0x8000
W/e.myapplicatio: Unexpected CPU variant for X86 using defaults: x86
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
W/RenderThread: type=1400 audit(0.0:129): avc: denied { write } for name="property_service" dev="tmpfs" ino=8368 scontext=u:r:untrusted_app:s0:c130,c256,c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0 app=com.example.myapplication
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
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/: HostConnection::get() New Host Connection established 0xd7d24f50, tid 23910
D/: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 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_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_1 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
D/EGL_emulation: eglCreateContext: 0xe3340b60: maj 3 min 1 rcv 4
D/EGL_emulation: eglMakeCurrent: 0xe3340b60: ver 3 1 (tinfo 0xe338bc10)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
    glUtilsParamSize: unknow param 0x000082da
W/Gralloc3: mapper 3.x is not supported
D/: createUnique: call
D/: HostConnection::get() New Host Connection established 0xd7d26ad0, tid 23910
    HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 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_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_1 
D/eglCodecCommon: allocate: Ask for block of size 0x1000
D/eglCodecCommon: allocate: ioctl allocate returned offset 0x3ffff6000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xe3340b60: ver 3 1 (tinfo 0xe338bc10)
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
I/AssistStructure: Flattened final assist data: 1788 bytes, containing 1 windows, 10 views
W/e.myapplicatio: Accessing hidden method Ljava/lang/invoke/LambdaMetafactory;->metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; (blacklist, linking, denied)
E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.myapplication, PID: 23852
    java.lang.NoSuchMethodError: No static method metafactory(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; in class Ljava/lang/invoke/LambdaMetafactory; or its super classes (declaration of 'java.lang.invoke.LambdaMetafactory' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at com.mysql.cj.conf.ConnectionUrl.buildConnectionStringCacheKey(ConnectionUrl.java:246)
        at com.mysql.cj.conf.ConnectionUrl.getConnectionUrlInstance(ConnectionUrl.java:185)
        at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:204)
        at java.sql.DriverManager.getConnection(DriverManager.java:580)
        at java.sql.DriverManager.getConnection(DriverManager.java:218)
        at com.example.myapplication.JdbcUtil.getConnection(JdbcUtil.java:22)
        at com.example.myapplication.UserDao.<init>(UserDao.java:15)
        at com.example.myapplication.MainActivity$1.run(MainActivity.java:53)
        at java.lang.Thread.run(Thread.java:919)
D/EGL_emulation: eglMakeCurrent: 0xe3340b60: ver 3 1 (tinfo 0xe338bc10)
D/AutofillManager: onActivityFinishing(): calling cancelLocked()
Process 23852 terminated.

在网上百度了很多方法都没有解决,起初以为是驱动的问题,但是换了一个仍然不好用,求求大神赐教

  • 写回答

1条回答 默认 最新

  • chickenmay 2019-11-22 16:27
    关注

    你的驱动j 能获取到localhost目录下面的数据库吗? 安卓是放到assets目录下吧 或者手机的安装环境

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办