2014-03-27 45 views
1

我有一長串布爾值,我想要保存在我的應用程序中使用共享首選項,以便我可以保存多個複選框的狀態。我現在已經嘗試了幾種方法,現在我已經厭倦了相同的代碼,甚至願意尋求幫助。使用共享首選項保存一組布爾值

我會發布我的代碼,但有這麼多greentext和冗餘信息,我覺得它值得。但如果它有幫助。

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

} 
+0

SharedPreferences是鍵/值配對,沒有任何東西可以保存多個鍵值多個值 – tyczj

+0

我還沒找到在您的代碼中使用SharedPreference的跟蹤。究竟是什麼問題? – kiruwka

+0

您可以通過在SharedPreferences中存儲字符串來完成此操作。我在寫一個解決方案。 – anthonycr

回答

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不支持存儲陣列,所以唯一的方式來存儲一個數組是用一個可辨別的分隔符(在這種情況下| $ | SEPARATOR | $ | ),不會與您正在存儲的數據混淆。另外,因爲沒有辦法存儲數組,所以在將它們存儲到字符串之前,我將它們轉換爲字符串,然後從內存中檢索它們並檢測它是「true」還是「false」,並相應地設置checkState數組。

希望這有助於。我使用一個非常類似的過程來存儲URL數組,並且它完美地工作。

或者,你可以使用SQLiteDatabase來存儲你的數組,但這可能是一個太多的工作,只是爲了存儲一些布爾值。

編輯:本來我認爲toString()會工作在布爾值上,但顯然不在數組上。

+0

該死的兒子,你好。 – user3307142

+0

另外,我開始使用sql,但顯然它對於應用程序來說很糟糕,因爲當您處理僅由用戶更改的數據時。再次感謝 – user3307142

+0

不客氣。是的,SQL並不是真正用於存儲數組,它更適合於存儲大量數據(如聯繫人列表)並經常檢索並添加到數據中,而您只是想爲下次啓動保存一些數據。此外,謝謝你給我超過1000的聲望:) – anthonycr