gpt4 book ai didi

java - 数据库到游标,游标到数组列表和数组列表到名称值对的字符串。

转载 作者:行者123 更新时间:2023-11-29 10:15:58 25 4
gpt4 key购买 nike

我有一个包含八列的数据库表,其中包含以下字段:

|_id|flag|HVID|Vname|Vdate|Vtime|Vcost|Vmedicine|

我正在查询此数据库以提取属于某个“HVID”的所有记录:

public Cursor fetchAllVac(String ID) {

String Key = ID;
Cursor mCursor = mDb.query(DATABASE_TABLE1, new String[] { IDx, FLAG,
HVID1, Vname1, VDate1, Vtime1, Vcost1, Vmedicine1 }, "HVID=?",
new String[] { Key }, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

在 Activity 中,我从游标中获取值并将它们存储在数组列表中:

public void Vacforshare() {
String B = null;
ArrayList<String> mArrayList = new ArrayList<String>();
mCursor = DBHelper.fetchAllVac(IDB);
if (mCursor.moveToFirst()) {
do {
try {
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("_id")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("flag")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("HVID")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("Vname")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("Vdate")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("Vtime")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("Vcost")));
mArrayList.add(mCursor.getString(mCursor
.getColumnIndex("Vmedicine")));
} catch (Exception h) {

}

} while (mCursor.moveToNext());

}
for (int i = 0; i < mArrayList.size(); i++) {
String G = (mArrayList.get(i));
B = B + G;
}
System.out.println("" + B);

}

我在 B 中得到的是一个冗余的(所有行)值字符串(我的记录可以是多行)我想将这些值分成名称-值对,我对如何实现这一点感到困惑。

最佳答案

您可以引入一个新类,它只包含一条记录的值列表,如下所示:

public class Record {
List<String> values = new ArrayList<String>();

public List<String> getValues() {
return values;
}
}

然后在循环中填写记录列表:

ArrayList<Record> mArrayList = new ArrayList<Record>();
do {
try {
Record record = new Record();
List<String> values = record.getValues();

values.add(mCursor.getString(mCursor.getColumnIndex("_id")));
...
mArrayList.add(record);
} catch (Exception h) {

}
}

现在您可以遍历字段名称和每条记录的值来创建您想要的输出:

String[] names = new String[] {"_id", "flag", ....};
for (int i = 0; i < mArrayList.size(); i++) {
Record record = mArrayList.get(i);

String current = "";
List<String> values = record.getValues();
for (int j = 0; j < values.size(); j++) {
String fieldName = names[j];
String s = values.get(j);
current += " " + fieldName + "=" + s;
}
B = B + "[" + current.trim() + "]";
}
System.out.println(B); // will print: [_id=value1 flag=value2 ...][_id=value1 flag=value2 ...] etc

关于java - 数据库到游标,游标到数组列表和数组列表到名称值对的字符串。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17993241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com