安卓:sqlite的储蓄字符串数组? [英] Android: Sqlite saving string array?

查看:191
本文介绍了安卓:sqlite的储蓄字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要字符串数组保存到数据库中,但它不会让我,这是我有:

I need to save string array to the database but it wont 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);
        }

但是,如果我把字符串[]国家在它说,cotentvalues​​不能拿一个参数。我如何得到解决的。我想我已经7东西,国家可以,我喜欢有7 sepearte字符串和存储的东西,在每个然后后把所有字符串转换回字符串数组或会是这样不好的做法?

but if i put string[] states in it says that cotentvalues is not able to take an argument. how do i get around that. I was think i have 7 things in states could i like have 7 sepearte string and store stuff in each and then after put all strings back into an string array or would that be bad practice?

推荐答案

您不能保存字符串数组到数据库中。但是你可以用这一招。

You cannot save String array into Database. But you can use this trick.

1)所以,你必须使用 convertArrayToString(String []数组)方法将其转化为简单的String。这将使用'逗号'串联字符串的所有元素。

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):当您检索此字符串从数据库回来,你可以使用 convertStringToArray(字符串str)方法将其转换回String数组。这个方法将分割字符串从'逗号',你会得到你的原始数组回来。

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.

public static String strSeparator = "__,__";
public static String convertArrayToString(String[] array){
    String str = "";
    for (int i = 0;i<array.length; i++) {
        str = str+array[i];
        // Do not append comma at the end of last element
        if(i<array.length-1){
            str = str+strSeparator;
        }
    }
    return str;
}
public static String[] convertStringToArray(String str){
    String[] arr = str.split(strSeparator);
    return arr;
}

这篇关于安卓:sqlite的储蓄字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆