【问题标题】:Retrieve specific column of data and store it in string array检索特定列的数据并将其存储在字符串数组中
【发布时间】:2012-12-10 02:23:55
【问题描述】:

我有一个 sqlite 数据库,我想检索特定的数据列并将其存储到字符串数组中。数据库内部有两列。会有多行具有相同用户名的数据,我想检索用户的“ContentPath”并将其存储到字符串数组中。但我不知道如何检索该特定列数据...

    public String[] get_contentByEmailID(String emailid){
    String[] returnMsg = null;
    helper = this.getReadableDatabase();

    Cursor c = helper.rawQuery("SELECT tableid, emailid, contentpath" +
            " from w_content where emailid='"+emailid"' ", null);



    int contentpathColumn = c.getColumnIndex("contentpath");


    if (c.moveToFirst()) {
        do {
            returnMsg = new String[2]; 

            String contentpath = c.getString(contentpathColumn);

            returnMsg[0] = emailid_sync;

            returnMsg[1] = contentpath;


        } while (c.moveToNext());
    }
    if (c != null && !c.isClosed()) {
        c.close();
    }
    if (helper!=null){
        helper.close();
    };
    return returnMsg;
}

当我调用这个函数来检索数据时。它提供了 emailid 和 contentpath。

String values[] = helper.get_contentByEmailID(SettingConstant.EMAIL);

任何 cmets 将不胜感激。

【问题讨论】:

    标签: android sqlite arrays


    【解决方案1】:

    数组填充 emailid 和 contentpath 的原因是,因为你总是重置每一行上的 returnMsg 并用这样的值填充它。由于会有不同的行数,因此一般建议您使用ArrayList,而不是构建静态长度数组。

    要修复它,请更改:

    String[] returnMsg = null;
    

    到:

    ArrayList<String> returnMsg = new ArrayList<String>();
    

    然后,在您的 do{} 中,执行以下操作:

    do {
        String contentpath = c.getString(contentpathColumn);
        returnMsg.add(contentpath);
    } while (c.moveToNext());
    

    最后,将您的退货声明更改为:

    return returnMsg.toArray();
    

    【讨论】:

    • 我还有一个问题。最后我的函数变成了 public Object[] get_content(String emailid)。 Object[] 与普通数组有什么不同?
    • Object[] 表示法表示它是一个对象数组。 [] 平均数组。因此,String[] 表示一个字符串数组,依此类推。在这里阅读更多信息:docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html | Object 是 Java 中所有对象的父对象。
    猜你喜欢
    • 1970-01-01
    • 2022-07-20
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多