使用“共享”首选项保存一个布尔数组 [英] Save an array of booleans using Shared preference

查看:54
本文介绍了使用“共享”首选项保存一个布尔数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的布尔值列表,我想使用共享的首选项将其保存在我的应用程序中,这样我就可以保存许多复选框的状态。我现在已经尝试了几种方法,现在已经厌倦了相同的代码,以至于我什至都愿意寻求帮助。

I have a long list of booleans which i want to save In my app using shared preference, so that i can save the state of a number of checkboxes. i have tried a few approaches now, and am now so sick of the same code, that im even willing to ask for help.

我会发布我的代码,但是在那里太多的绿色文本和多余的信息,我认为这是值得的。

I would post my code, but there is so much greentext and redundant information that i dotn think its worth it. But if it helps.

import java.util.HashMap;
import java.util.Map.Entry;

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class ExpListAdapter extends BaseExpandableListAdapter {

    private Context context;
    // second attempt to hold the values
    private SharedPreferences keyValues;
    private int totalLength;

    private String[] parentList = { "Bedding", "Bedroom Items", "Clothing",
            "Bags", "Stationary", "Documents", "Electronics", "Toiletries",
            "Kitchen Items" };

    // used to retain our checklist values, which for some reason dont stick.
    private boolean[] checkState;

    // multidimensional array for storing the child Strings
    private String[][] childList = {
            { "Single/Double sheets", "Single/Double duvet + Covers",
                    "Pillows + Pillow cases" },
            { "Alarm Clock", "Posters", "Door Wedge", "Lamp", "Small Bin",
                    "Hamper Basket" },
            { "Casual Clothes, i.e T shirts, jeans, hoodies",
                    "Smart clothing for interviews and presentations",
                    "Warm Clothing (especially for newcastle)",
                    "'Party Clothes' clothes for going out",
                    "Underwear and socks", "pyjamas", "Comfortable shoes",
                    "Sports trainers", "Swimwear" },
            { "Everyday bag/backpack", "Gym bag", "Clear Pencil Case",
                    "Purse/Wallet", "Watch" },
            { "Pins", "A4 Notebooks", "Pens/Pencils", "Highlighters", "Ruler",
                    "Rubber", "Selotape", "Hole Puncher", "A4 Binders",
                    "Calculater", "Calender" },
            { "Passport photos", "Passport",
                    "Driving License (some form of id)", "Your NI Card",
                    "Insurance Documents", "NHS Medical Card",
                    "Insurance documents", "Letter of Acceptance",
                    "Scholarship/bursury letters",
                    "Rail Card(if you have one)", "C.V" },
            { "Laptop+Charger", "Mouse", "Phone + Charger", "Ethernet Cables",
                    "USB memory stick", "Headphones", "Digital Camera",
                    "MP3 Player" },
            { "Shampoo", "Razors", "Toothbrush and toothpaste",
                    "Make-up/remover", "HairBrush",
                    "Condoms or other protection!!!" },
            { "Frying Pan", "Wok", "Tin Opener", "Bottle opener", "Glasses",
                    "Cheese Grater", "Knives", "Chopping Board", "Scissors",
                    "Tea Towels", "Tupperware", "Cling Film", "Cutlery",
                    "Crockery" } };


    public ExpListAdapter(Context context) {
        this.context = context;

        int [] lengths = new int [childList.length];

        for (int i=0;i<childList.length;i++){
             lengths[i] = childList[i].length;
             totalLength=totalLength+ lengths[i];
        }
        // initialised check
                checkState = new boolean[totalLength];

    }

    public Object getChild(int groupPosition, int childPosition) {

        return childPosition;
    }

    //
    public long getChildId(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return 0;
    }


    public void loadPrefs(){

        //where i want to put code to load during my constructor

    }


    public static boolean  savePrefs(){

        //where i want to put code to commit data to storage


        }


    public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

        //final int mGroupPosition = groupPosition;
        //final int mChildPosition = childPosition;

        CheckBox checkbox = new CheckBox(context);
        //checkbox.setOnCheckedChangeListener(null);

        for (int i=0;i<totalLength;i++){
            checkState[i]= checkbox.isChecked();

        }

        /*if (checkState.containsKey(mGroupPosition)) {
            boolean getChecked[] = checkState.get(mGroupPosition);
            checkbox.setChecked(getChecked[mChildPosition]);
        } else {
            boolean getChecked[] = new boolean[getChildrenCount(mGroupPosition)];
            checkState.put(mGroupPosition, getChecked);
            checkbox.setChecked(false);
        }
        checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {

                    boolean getChecked[] = checkState.get(mGroupPosition);
                    getChecked[mChildPosition] = isChecked;
                    checkState.put(mGroupPosition, getChecked);

                } else {

                    boolean getChecked[] = checkState.get(mGroupPosition);
                    getChecked[mChildPosition] = isChecked;
                    checkState.put(mGroupPosition, getChecked);
                }

            }
        });*/

        checkbox.setText(childList[groupPosition][childPosition]);
        checkbox.setPadding(40, 0, 0, 0);

        //

        return checkbox;
    }

    // returns the number of children you are having.

    public int getChildrenCount(int groupPosition) {
        // TODO Auto-generated method stub
        return childList[groupPosition].length;
    }

    // returns the number of parents you have.
    public Object getGroup(int groupPosition) {
        return groupPosition;
    }

    public int getGroupCount() {
        // TODO Auto-generated method stub
        return parentList.length;
    }

    public long getGroupId(int groupPosition) {
        // TODO Auto-generated method stub
        return groupPosition;
    }

    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        TextView text = new TextView(context);
        text.setText(parentList[groupPosition]);
        text.setPadding(40, 0, 0, 0);
        return text;
    }

    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return false;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return true;
    }

}


推荐答案

为了将布尔值数组保存到内存中,建议您按如下所示从布尔值构建一个字符串:

In order to save an array of booleans to memory, I suggest you build a string from the booleans as follows:

初始化

private boolean[] checkState;
private Editor mEditPrefs;
private SharedPreferences mPreferences;
//initialize checkState array and mEditPrefs and mPreferences

保存数组

String save = "";
for (int n = 0; n < checkState.length; n++) {
    if (checkState[n] != null) {
                if(checkState[n]) {
                    save = save + "true" + "|$|SEPARATOR|$|";
                } else {
                    save = save + "false" + "|$|SEPARATOR|$|";
                }
    }
}
mEditPrefs.putString("memory", save);
mEditPrefs.commit();

获取数组

String mem = mPreferences.getString("memory", "");
mEditPrefs.putString("memory", "");
String[] array = getArray(mem); //see below for the getArray() method
checkState = new boolean[array.length];
for(int n = 0; n < array.length; n++){
    if(array[n].equals("true"){
        checkState[n] = true;
    } else {
        checkState[n] = false;
    }
}

getArray()方法

public static String[] getArray(String input) {
    return input.split("\\|\\$\\|SEPARATOR\\|\\$\\|");
}

这不是一个明智的解决方案,但是SharedPreferences不支持存储数组,因此存储数组的唯一方法是使长字符串由可辨别的分隔符(在这种情况下| $ | SEPARATOR | $ |)分隔,该分隔符不会与要存储的数据混淆。而且,由于没有办法存储数组,我先将布尔值转换为字符串,然后再存储它们,然后从内存中检索它们,并检测它是 true还是 false,并相应地设置checkState数组。

This isn't an elegent solution, but SharedPreferences doesn't support storing arrays, so the only way to store an array is to make a long string separated by a discernible separator (in this case |$|SEPARATOR|$| ) that won't be confused with the data you are storing. Also, since there's no way to store arrays, I converted the booleans to strings before storing them and then I retrieve them from memory and detect if it is "true" or "false" and set the checkState array accordingly.

希望这会有所帮助。我使用了非常相似的过程

Hope this helped. I use a very similar process for storing an array of URLs and it works perfectly.

或者,您可以使用SQLiteDatabase来存储数组,但是仅存储起来可能会有点麻烦一些布尔值。

Alternatively you could use an SQLiteDatabase to store your array, but that might be a little too much work just to store some booleans.

编辑:最初,我认为 toString()适用于布尔值,但显然不适用于数组。

Originally I thought that toString() would work on a boolean, but apparently not on an array.

这篇关于使用“共享”首选项保存一个布尔数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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