【问题标题】:connect android to mysql database [closed]将android连接到mysql数据库[关闭]
【发布时间】:2014-07-08 15:34:03
【问题描述】:

我不明白为什么我的应用程序崩溃了......

import android.annotation.SuppressLint;    
import android.app.Activity;    
import android.os.Bundle;    
import android.os.StrictMode;    
import android.util.Log;    
import android.view.Menu;    
import android.view.MenuItem;    
import android.view.View;    
import android.widget.*;    
import java.sql.*;    
import java.util.*;

public class MyActivity extends Activity {

    EditText e;    
    Button bt;    
    ListView lv;    
    Connection connect;    
    SimpleAdapter sm;

    public void declere() {    
        e = (EditText) findViewById(R.id.txt_buscar);    
        bt = (Button) findViewById(R.id.btn_buscar);    
        lv = (ListView) findViewById(R.id.list_output);    
    }

    public void initilize() {    
        declere();    
        e.setText("SELECT * FROM TipoLugar");    
        connect = CONN("root", "teste", "teste_DB", "192.168.5.154:3306");    
    }

    @SuppressLint("NewApi")    
    private Connection CONN(String user, String pass, String db, String server) {    
        StrictMode.ThreadPolicy policy = new     
        StrictMode.ThreadPolicy.Builder().permitAll().build();    
        StrictMode.setThreadPolicy(policy);    
        Connection conn = null;    
        String connUrl = null;

        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");

            connUrl = "jdbc:jtds:sqlserver://" + server + ";" + "databaseName=" + db + ";user=" + user + ";password=" + pass + ";";

            conn = DriverManager.getConnection(connUrl);    

        } catch (SQLException se) {
             Log.e("ERROR", se.getMessage());    
        } catch (ClassNotFoundException cl) {    
            Log.e("ERROR", cl.getMessage());    
        } catch (Exception e) {    
            Log.e("ERROR", e.getMessage());
        }

        return conn;    
    }    

    public void querySQL(String COMMANDSQL) {    
        ResultSet rs;

        try {
            Statement statement = connect.createStatement();    
            rs = statement.executeQuery(COMMANDSQL);    
            List<Map<String, String>> data = null;    
            data = new ArrayList<Map<String, String>>();

            while (rs.next()) {    
                Map<String, String> datanum = new HashMap<String, String>();    
                datanum.put("a", rs.getString("code"));    
                datanum.put("b", rs.getString("descricao"));    
                data.add(datanum);
            }

            String[] from = {"a", "b"};    
            int[] to = {R.id.txt_titulo, R.id.txt_conteudo};    
            sm = new SimpleAdapter(this, data, R.layout.modelo, from, to);    
            lv.setAdapter(sm);    
        } catch (Exception e) {    
            Log.e("ERROR", e.getMessage());
        }    
    }

    public void onCreate(Bundle b) {    
        super.onCreate(b);    
        setContentView(R.layout.activity_my);    
        initilize();

        bt.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
              // TODO Auto-generated method stub
              querySQL(e.getText().toString());
            }
        });
    }

log cat 中的错误是这样的(你知道这是什么吗?:))

07-08 16:51:29.200      632-632/app2.francisco.app2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: println needs a message
        at android.util.Log.println_native(Native Method)
        at android.util.Log.e(Log.java:231)
        at app2.francisco.app2.MyActivity.querySQL(MyActivity.java:88)
        at app2.francisco.app2.MyActivity$1.onClick(MyActivity.java:103)
        at android.view.View.performClick(View.java:4084)
        at android.view.View$PerformClick.run(View.java:16966)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

07-08 16:51:31.420 632-632/app2.francisco.app2 I/Process:发送信号。 PID:632 SIG:9

【问题讨论】:

    标签: java android database connection database-connection


    【解决方案1】:

    看来e.getMessage()catch 方法的querySQL 块内的null,所以Log.enull 传递给println,这是在抛出NullPointerException

    为什么异常消息是null,我不能说,但您可以通过检查null 并提供默认值来解决此问题:

    public void querySQL(String COMMANDSQL) {
        ...
        try {
            ...
        } catch (Exception e) {
            String errorMessage = (e.getMessage() != null) ? e.getMessage() : "Unknown error";
            Log.e("ERROR", errorMessage);
       }
    }
    

    【讨论】:

    • 这显示一个错误。 String errorMessage = (e.getMessage() != null) e.getMessage() : "未知错误";
    • @user3816937 对不起.. 是我的错字,遗漏了三元运算符最重要的部分。现已修复。
    • 它落在那个错误上......和SQLEXCEPTION......你知道为什么吗?谢谢@LimbSoup
    • @user3816937 这听起来像是另一个问题,因为您的NullPointerException 应该被修复。如果不知道查询是什么、架构......等,就不可能根除SqlException 的原因。
    • LimbSoup thx 这是我的错误.....查询是错误的,用户也是.....抱歉,但是谢谢所有人
    【解决方案2】:

    似乎 rs 为空,这意味着您设置它的部分不起作用 statement.executeQuery(COMMANDSQL);为null,因此您需要遵循逻辑并找出导致它等于null的原因,这可能是您的sql语法,因为您将其设置为等于文本字段输入,executeQUery和execute也是不同的东西,并返回不同的值,我建议查看 API 以确保你得到你想要的 http://developer.android.com/reference/java/sql/Statement.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-12
      • 2015-01-26
      • 1970-01-01
      • 2010-09-24
      • 2014-08-18
      • 2012-07-12
      • 1970-01-01
      相关资源
      最近更新 更多