Android:SQLite 保存字符串数组?
我需要将字符串数组保存到数据库,但它不允许我这样做。这就是我所拥有的:
public long createEntry(String startTime, String endTime, String[] states) {
ContentValues initialValues = new ContentValues();
initialValues.put(START_KEY_TIME , startTime);
initialValues.put(END_KEY_TIME , endTime);
initialValues.put(KEY_STATE, states );
return databaseConnect.insert(DATABASE_TABLE, null, initialValues);
}
但是如果我放入 string[]
状态,它表示内容值无法接受参数。我该如何解决这个问题?我在想我的状态有 7 个东西,我可以有 7 个单独的字符串并在每个字符串中存储内容,然后将所有字符串放回到字符串数组中吗?或者这是不好的做法?
I need to save a string array to the database but it won't let me. This is what I have:
public long createEntry(String startTime, String endTime, String[] states) {
ContentValues initialValues = new ContentValues();
initialValues.put(START_KEY_TIME , startTime);
initialValues.put(END_KEY_TIME , endTime);
initialValues.put(KEY_STATE, states );
return databaseConnect.insert(DATABASE_TABLE, null, initialValues);
}
But if I put string[]
states in, it says that content values is not able to take an argument. How do I get around that? I was thinking I have 7 things in states, could I like have 7 separate strings and store stuff in each and then afterwards put all the strings back into an string array? Or would that be bad practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您无法将字符串数组保存到数据库中。但你可以使用这个技巧。
1) 所以你必须使用
convertArrayToString(String[] array)
方法将其转换为简单的字符串。这将使用“逗号”连接字符串的所有元素。2) 当您从数据库检索此字符串时,您可以使用
convertStringToArray(String str)
方法将其转换回字符串数组。此方法将从“逗号”中分割字符串,您将得到原始数组。You cannot save String array into Database. But you can use this trick.
1) So you have to convert it into simple String using
convertArrayToString(String[] array)
method. This will concatenate all elements of string using 'comma'.2) When you would retrieve this String back from Database you could convert it back to String array using
convertStringToArray(String str)
method. This method will split the string from 'comma' and you will get your original array back.基于穆罕默德的答案,但处理
String
的List
而不是数组,并使用StringBuilder
而不是分配许多String
在值串联期间:Based on Muhammed's answer but handles
List
ofString
s instead of array and usesStringBuilder
instead of allocating manyString
s during values concatenation:将其转换为单个字符串以将其保存在 sqlite 中。
稍后,从 sqlite 将其作为单个字符串检索回来,并将其转换回字符串数组。
Convert it to single String to save it in sqlite.
Later, retrieve it back from sqlite as a single string and convert it back to Array of String.
如果将字符串数组转换为 JSONArray,使用 toString 然后通过首先解析为 JSONArray 来检索它,然后将其转换为字符串数组,会更容易
It would be easier if you convert the array of Strings to JSONArray, use toString and then, retrieve it by parsing first into JSONArray and then, convert it into array of Strings
看来您的数据库没有按应有的设计。如果要将布尔数据存储在 SQLite 数据库中,可以将布尔值存储为整数 0(假)和 1(真)
It looks like your database is not designed as it should be. If you want to store the boolean data in SQLite database you can store the Boolean values as integers 0 (false) and 1 (true)