2014-10-21 4 views
1

저는 2 주 이상이 작업에 어려움을 겪고 있습니다. 다중 선택 알림 대화를 지속하기 위해 sharedpreferenes 및 기타 '해킹'에 대한 모든 SO 질문이있었습니다. 하지만 불행히도 나는 여전히 그것을 작동시킬 수 없다.Persist AlertDialog 체크 옵션

누군가이 작품을 만드는 방법을 나에게 설명해 줄 수 있습니까? 내 다중 선택 경보 대화가 작동합니다. 하지만 난 여전히 선택한 항목을 저장할 수 없습니다 ..

내 코드 : 당신의 도움에 대한

public class TimelineSettings extends DialogFragment { 
    Context context; 
    final ArrayList selected_categories = new ArrayList(); 
    final String[]items = {"Fourniture","Nourriture","Voyages","Habillement","Médias","Autres"}; 
    TinyDB tinydb = new TinyDB(context); 
    private SharedPreferences sharedPreference; 
    private SharedPreferences.Editor sharedPrefEditor; 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     // Set the dialog title 
     builder.setTitle("Choisissez vos paramètres") 
       .setMultiChoiceItems(items, null, 
         new DialogInterface.OnMultiChoiceClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int indexselected, 
               boolean isChecked) { 
           if (isChecked) { 
            // If the user checked the item, add it to the selected items 
            selected_categories.add(indexselected); 
           } else if (selected_categories.contains(indexselected)) { 
            // Else, if the item is already in the array, remove it 
            selected_categories.remove(Integer.valueOf(indexselected)); 
           } 
          } 
         }) 
         // Set the action buttons 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int id) { 
        tinydb.putList("selected",selected_categories); 
        } 
       }) 
       .setNegativeButton("Annuler", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int id) { 
        } 
       }); 
     return builder.create(); 
    } 
} 

감사합니다.

추신 : 나는이 작품을 만드는 방법을 설명 할 수 있다면이 answer을 발견했습니다. 당신은 환경 설정에서 Integers을 저장 한 다음 StringsArrayListIntegersArrayList 변환되기 때문에

+0

당신은 대화를, 당신의 선택이 설정되지 않은 두 번째로 실행하면, 그것은 것입니다 : 여기

는 완전한 변경 및 코드인가? – joao2fast4u

+0

먼저 공유 환경 설정에 아무 것도 저장하지 않습니다. 또한 대화 상자를 작성할 때 공유 환경 설정에서 아무 것도 검색하지 않습니다. 빌드시 선택한 설정을 선택하는 것도 아닙니다. 그래서 지금까지 무엇을 시도 했습니까? db에서 정보를 검색하지 않습니다. DB의 상태도 저장하지 않습니다. – greenapps

+0

@greenapps 먼저 공유 목록에 내 arraylist를 저장하려고 했으므로 arraylist를 문자열 집합으로 변환하려고 시도했지만 작동하지 않았습니다.이 tinydb 클래스를 사용하려고했지만 다시는 할 수 없었습니다. 그것을 작동하게하십시오. 내 문제는 정확히 어떻게 sharedprefs를 사용하여 선택한 선택의 배열을 저장하고 검색 할 수 있는지 정확히 알지 못한다는 것입니다. 어떻게 보여 주시겠습니까? – RidRoid

답변

2
조심

. 이로 인해 Exception이 발생할 수 있습니다. 대신 ArrayListsStrings을 사용하십시오.

DialogFragment를 표시하기 전에 저장된 선택 사항을 읽고 DialogFragment에서 확인해야하는 부분이 누락되었습니다.

이 당신이 원하는 일을 가장 쉬운 방법이 있습니다 만의이 방법 보자 :

당신이다시피

에서, setMultiChoiceItems() 방법은 그들이 선택하는 경우 정의하기 위해 DialogFragment의 항목과 boolean []String[]를 수신하거나 아니. 우리는이 배열을 사용하여 선택을 지속 할 것입니다. 이 배열은 items 배열과 길이가 같아야하며 처음에는 false로 설정됩니다.

처음으로 DialogFragment을 실행하면 항목이 확인되지 않습니다. 두 번째로, 이미 아이템을 체크했다면 TinyDB에서 그 선택을 읽고 for 구문으로 부울 배열을 채 웁니다. 그런 다음 DialogFragment 빌더에 피드를 보냅니다.

저장된 항목은 DialogFragment에 확인 된대로 표시됩니다.

public class TimelineSettings extends DialogFragment { 
    ArrayList<String> selected_categories = new ArrayList<String>(); 
    final String[]items = {"Fourniture","Nourriture","Voyages","Habillement","Médias","Autres"}; 
    boolean[] itemsChecked = {false, false, false, false, false, false}; 
    TinyDB tinydb; 
    private SharedPreferences sharedPreference; 
    private SharedPreferences.Editor sharedPrefEditor; 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     tinydb = new TinyDB(getActivity()); 
     selected_categories = tinydb.getList("selected"); 

     for(int i=0;i<itemsChecked.length;i++){ 
      if(selected_categories.contains((String)String.valueOf(i))) 
        itemsChecked[i]=true; 
     } 

     // Set the dialog title 
     builder.setTitle("Choisissez vos paramètres") 
       .setMultiChoiceItems(items, itemsChecked, 
         new DialogInterface.OnMultiChoiceClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int indexselected, 
               boolean isChecked) { 
           if (isChecked) { 
            // If the user checked the item, add it to the selected items 
            if(!selected_categories.contains((String)String.valueOf(indexselected))){ 
             selected_categories.add(String.valueOf(indexselected)); 
             itemsChecked[indexselected]=true; 
            } 
           } else if (selected_categories.contains((String)String.valueOf(indexselected))) { 
            // Else, if the item is already in the array, remove it 
            selected_categories.remove((String)String.valueOf(indexselected)); 
            itemsChecked[indexselected]=false; 
           } 
          } 
         }) 
         // Set the action buttons 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int id) { 
         tinydb.putList("selected",selected_categories); 
        } 
       }) 
       .setNegativeButton("Annuler", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int id) { 
        } 
       }); 
     return builder.create(); 
    } 
} 
+0

답장을 보내 주셔서 감사합니다. 형식에 대한 오류가 실제로있었습니다 (배열을 배열로 변환하려고 할 때). 이제 귀하의 코어를 사용하려고하지만 tinydb 개체를 만들 때 nullpointer 예외가 발생합니다 : ** TinyDB tinydb = new TinyDB (컨텍스트); ** '무엇이 잘못 되었습니까? 코멘트에 오류가있는 my 클래스가 있습니다. https://gist.github.com/RidouaneHicham/f7e07445a76a314d7c0b – RidRoid

+0

컨텍스트 변수가 비어 있으므로 수신중인 NPE입니다. TinyDB 생성자에 유효한 컨텍스트를 제공해야합니다. TinyDB로 시도하십시오. tinydb = 새로운 TinyDB (getActivity()); – joao2fast4u

+0

나는 당신이 당신의 스택 트레이스를 게시하시기 바랍니다 수 내 comment..still NPE :( – RidRoid