使用共享偏好保存boolean数组(Save an array of booleans using

2019-10-19 17:03发布

我有我要救我的应用程序使用共享的喜好,这样我可以节省一些复选框的状态布尔的一个长长的清单。 我已经尝试了几种方法,现在,现在真讨厌相同的代码,即IM甚至愿意寻求帮助。

我会后我的代码,但是有这么多greentext和我dotn认为它值得的冗余信息。 但是,如果它帮助。

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;
    }

}

Answer 1:

为了节省布尔内存数组,我建议你建立从布尔值的字符串,如下所示:

初始化

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不支持存储阵列,使存储阵列的唯一办法就是让一个明显的分隔符分隔长字符串(在这种情况下| $ |分离器| $ |)赢得“T与你存储数据混淆。 此外,由于没有办法来存储阵列,我转换的布尔为字符串存储在他们面前,然后我从内存中检索它们并检测它是否是“真”或“假”,并设置相应的checkState阵列。

希望这有助于。 我用一个非常类似的过程,用于存储的URL的数组,它完美的作品。

另外,您可以使用一个SQLiteDatabase来存储您的阵列,但可能是有点太多的工作只是存放一些布尔值。

编辑:原本我以为的toString()将一个布尔工作,但显然不是一个阵列上。



文章来源: Save an array of booleans using Shared preference