【问题标题】:Retrieving multiple data from mySQL in android using JDBC使用 JDBC 从 android 中的 mySQL 检索多个数据
【发布时间】:2018-03-29 07:53:51
【问题描述】:

我正在尝试从我的数据库中检索数据并将其填充到 listView。但是我的代码不起作用,我也尝试添加 Log.e 但我在 logcat 中什么也没有。这是我尝试做的:

顺便说一句,我在这里使用AsyncTask


onPreExecute():

super.onPreExecute();


doInBackground():

 try {
        Connection con = connectionClass.CONN();
        if (con == null) {
            z = "Please check your internet connection";
        } else {

            String query = "select name from medicines";

            Statement stmt = con.createStatement();

            ResultSet rs = stmt.executeQuery(query);

            lv.setAdapter(null);

            while (rs.next()) {

                myArrayList.add(rs.getString("name"));
                Log.e("qwerty","working");
            }
        }
    } catch (Exception ex) {
        isSuccess = false;
        z = "Exceptions" + ex;
    }
    return z;

onPostExecute():

ListAdapter listAdapter = new ArrayAdapter<>(MedicineSearch.this, android.R.layout.simple_list_item_1, myArrayList);
        lv.setAdapter(listAdapter);

就这样,我的 logcat 上什么也没有出现,这意味着我猜代码不起作用,我该如何解决这个问题,或者有其他方法吗?

【问题讨论】:

    标签: android mysql jdbc


    【解决方案1】:

    你正在从 doInBackground() 返回 String 'z' 但你需要返回你的 myArrayList。

    try {
        Connection con = connectionClass.CONN();
        if (con == null) {
            z = "Please check your internet connection";
        } else {
    
            String query = "select name from medicines";
    
            Statement stmt = con.createStatement();
    
            ResultSet rs = stmt.executeQuery(query);
    
            lv.setAdapter(null);
    
            while (rs.next()) {
    
                myArrayList.add(rs.getString("name"));
                Log.e("qwerty","working");
            }
        }
    } catch (Exception ex) {
        isSuccess = false;
        z = "Exceptions" + ex;
    }
    return myArrayList;
    

    然后在 onPostExecute() 中放置一个调试器来查看 myArrayList 是否有一些数据。 OnPosetExecute() 看起来像这样:

    if(myArrayList.size() > 0){
    //your set adapter code
    }
    

    【讨论】:

    • 我无法返回 myArrayList,上面写着 Incopatible types
    • 好的,然后尝试更改您的 onPostExecute() 并在 myArrayList.size() 上放置一个调试器,以查看其中是否添加了任何内容。如果 myArrayList.size() 为 0,那么你知道 doInBackground() 没有按你的意愿工作。
    • 我尝试在 while 循环中添加该调试器,但也没有响应。将其移出循环也不起作用 T.T
    • 好的,这里可能会发生一些事情:否则条件根本没有执行,或者你的 'rs' 是空的,对吗?我建议您再次检查表和列名。确保它们存在并且表中存在一些数据。哦,顺便说一句,您可以从 doInBackground() 中删除 lv.setAdapter(null); 这是不必要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多