我有一个游标,叫做passableCursor,包含多个字段,但是一个字段,成分,包含多个值,我无法从中获取所有值。
从名称检索的示例
Log.d("recipeName", passableCursor.getString(passableCursor.getColumnIndex("name")));
游标结构示例
name-> name1
description -> description1
ingredients -> ingredient1, ingredient2, ingredient3.
我一直在名称和描述字段中使用getString
。但是,我正在努力从成分中获得价值。似乎没有getStringArray
的方法。
这是一种方法:
SQLiteDatabase db =null;//Initialize this first
Cursor cursor = db.rawQuery("your query", null);//Replace with your query(e.g. SELECT FROM table WHERE something=2)
String preChanged = cursor.getString(cursor.getColumnIndex("row_name"));//Replace row name with your row name
String[] finalR = preChanged.split(",");//Can be changed to parts
//String[] finalR = new String[parts.length];
//for(int i = 0; i < parts.length; i++){
// finalR[i] = parts[i];//This for-loop is if you have special needs. If you want to convert the String to a different type(integer, boolean, etc), or you want to make sure it contains/does not contain something.
//}//Uncomment if needed
//Now, this needs a special compression method, to ensure correct format;
//raw is the raw array, continuing from up above we use finalR to make sure you as a reader understand the context
StringBuilder builder = new StringBuilder();
for (int i = 0; i < finalR.length; i++) {
if(i != finalR.length - 1)
builder.append(finalR[i] + ",");
else
builder.append(finalR[i]);
}
这也可以转换为一系列方法。
解释其工作原理:
1)获取原始数组输入(在本例中为字符串)
2)创建一个字符串,用,
分隔不同的字符串。对于可能有逗号的较长字符串,您可能需要考虑在逗号中添加一个反斜杠,并在"\","处拆分(两个反斜杠使 Java 将其注册为实际的反斜杠,而不是转义字符)
3) 将字符串保存到数据库
4) 加载字符串
5)它在,
处分裂弦,给你几块。这是数组,应该是(假设您已采取预防措施保护系统免受字符串中逗号(,
)6)可选:优化String数组,通过删除某些内容,添加某些内容,添加对标记的支持(用HTML代码替换[link text](http://example.com)
),更改类型(字符串->整数),无论您需要什么。
注意
这是基本草案。这允许您将基本数组保存到数据库,并在不创建多行的情况下对其进行恢复。如果在字符串数组中保存带有逗号的文本或任何可能尝试导致 SQL 注入的字符,则可能需要对其进行优化。
这可以被细化为与任何其他类型的数组一起使用,例如长整型、整数或布尔值,但保存是相同的(必须将其压缩为字符串),但您添加.parse[Type](input)
以将其转换为所需类型的数组