2015-12-01 3 views
0

У меня проблема с удалением элементов из ArrayList. Я пробовал это, возможно, 100 раз, но я не могу это исправить. Сохранение списка - это не проблема, но его очень сложно удалить.Как удалить SharedPreferences из массива

Когда я удаляю ключ SharedPrefs (позиция) В первый раз хорошо, но если я первый раз удаляю первую позицию, он удаляется из списка, но все еще в настройках, поэтому, когда я пытаюсь удалить вторую позицию второй раз, я не могу удалить ее, потому что есть по-прежнему сохраняются предпочтения со значением "", но мне нужно полностью удалить это предпочтение, чтобы первая позиция содержала предпочтения со значением во второй позиции, а не "".

Я попытался сделать несколько изображений для лучшего понимания. То, прежде чем удалить 1-е место: image1

И это после того, как удалить 1-ую позицию

image2

Там мой CustomListAdapter класс

public class CustomListAdapterInterests extends ArrayAdapter <String> { 

    private final Activity context; 
    private final ArrayList <String> mItemInterest; 

    public CustomListAdapterInterests(Activity context, ArrayList <String> itemInterest) { 
     super(context, R.layout.list_item_interests, itemInterest); 

     this.context = context; 
     this.mItemInterest = itemInterest; 
    } 

    @Override 
    public int getCount() { 
     return mItemInterest.size(); 
    } 

    public View getView(int position, View view, ViewGroup parent) { 

     LayoutInflater inflater = context.getLayoutInflater(); 
     View rowView = inflater.inflate(R.layout.list_item_interests, null, true); 

     TextView itemInterestTV = (TextView) rowView.findViewById(R.id.textInterest); 

     itemInterestTV.setText(mItemInterest.get(position)); 
     return rowView; 
    } 
} 

А вот мой фрагмент

public class InterestsFragment extends BaseFragment { 

    private ArrayList <String> mInterestList; 
    private static final int MAX_STORED_LINES_INTERESTS = 50; 
    private FloatingActionButton plusInterestsBTN; 
    private CustomListAdapterInterests adapterInterests; 
    private ListView listInterests; 
    private EditText interestET; 
    private Button confirmInterestBTN; 
    public SharedPreferences sharedPreferences; 

    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     View v = inflater.inflate(R.layout.fragment_interests, container, false); 

     plusInterestsBTN = (FloatingActionButton) v.findViewById(R.id.plusInterests); 
     sharedPreferences = getActivity().getSharedPreferences(Constants.PREFERENCES_INTERESTS, Context.MODE_PRIVATE); 
     mInterestList = new ArrayList <String>(); 
     loadInterestFromPreferences(mInterestList); 
     adapterInterests = new CustomListAdapterInterests(getActivity(), mInterestList); 

     listInterests = (ListView) v.findViewById(R.id.listViewInterests); 
     listInterests.setAdapter(adapterInterests); 

     listInterests.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView <? > arg0, View v, int position, long arg3) { 


       if (sharedPreferences.contains(Constants.INTEREST + position)) { 
        SharedPreferences.Editor editor = sharedPreferences.edit(); 
        mInterestList.remove(position); 
        adapterInterests.notifyDataSetChanged(); 
        editor.remove(Constants.INTEREST + position); 



        editor.commit(); 
       } 
      } 
     }); 

     listInterests.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {@Override 
      public boolean onItemLongClick(AdapterView <? > arg0, View arg1, 
      final int position, long id) { 
       onShowDialogSetItem(position); 
       return true; 
      } 
     }); 

     plusInterestsBTN.setOnClickListener(new View.OnClickListener() {@Override 
      public void onClick(View v) { 
       onShowDialogAddItem(); 
      } 

     }); 

     listInterests.setOnScrollListener(new AbsListView.OnScrollListener() {@Override 
      public void onScrollStateChanged(AbsListView view, int scrollState) { 

       int btn_initPosY = plusInterestsBTN.getScrollY(); 

       if (scrollState == SCROLL_STATE_TOUCH_SCROLL) { 
        plusInterestsBTN.animate().cancel(); 
        plusInterestsBTN.animate().translationXBy(350); 
       } else { 
        plusInterestsBTN.animate().cancel(); 
        plusInterestsBTN.animate().translationX(btn_initPosY); 
       } 
      } 

      @Override 
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { 

      } 
     }); 
     return v; 
    } 

    private void loadInterestFromPreferences(ArrayList <String> mInterestList) { 
     for (int x = 0; x < 5; x++) { 

      String interests = sharedPreferences.getString(Constants.INTEREST + x, Constants.DEFAULT); 

      Toast.makeText(getActivity(), interests, Toast.LENGTH_SHORT).show(); 

      if (interests != "") { 
       mInterestList.add(interests); 
      } 


     } 
    } 


    private void onShowDialogSetItem(final int position) { 
     final Dialog dialogInterest = new Dialog(getActivity()); 
     dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top; 
     dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName; 

     LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false); 

     dialogInterest.setCanceledOnTouchOutside(true); 
     dialogInterest.setContentView(view); 

     final EditText interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest); 
     Button confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest); 
     TextView title = (TextView) dialogInterest.findViewById(R.id.textView2); 
     title.setText("Edit Interest"); 
     interestET.setText(mInterestList.get(position)); 

     confirmInterestBTN.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Log.d("2", "" + position); 
       String interest = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT); 



       SharedPreferences.Editor editor = sharedPreferences.edit(); 
       editor.putString(Constants.INTEREST + position, interestET.getText().toString()); 
       editor.commit(); 
       String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT); 

       mInterestList.set(position, interestET.getText().toString()); 


       Toast.makeText(getActivity(), "Upravené: " + interests, Toast.LENGTH_SHORT).show(); 
       adapterInterests.notifyDataSetChanged(); 
       dialogInterest.dismiss(); 

      } 
     }); 
     dialogInterest.show(); 
    } 
    private void onShowDialogAddItem() { 

     if (mInterestList.size() >= MAX_STORED_LINES_INTERESTS) { 
      return; 
     } 
     final Dialog dialogInterest = new Dialog(getActivity()); 
     dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top; 
     dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE); 
     dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName; 

     LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false); 

     dialogInterest.setCanceledOnTouchOutside(true); 
     dialogInterest.setContentView(view); 

     interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest); 
     confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest); 

     confirmInterestBTN.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       int position = listInterests.getAdapter().getCount(); 
       SharedPreferences.Editor editor = sharedPreferences.edit(); 
       editor.putString(Constants.INTEREST + position, interestET.getText().toString()); 
       editor.commit(); 
       String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT); 
       Toast.makeText(getActivity(), "Přidané: " + interests, Toast.LENGTH_SHORT).show(); 
       mInterestList.add(interestET.getText().toString()); 
       //adapterInterests.notifyDataSetChanged(); 

       dialogInterest.dismiss(); 
      } 
     }); 
     dialogInterest.show(); 
     adapterInterests.notifyDataSetChanged(); 
    } 
} 

Благодарим за помощь. Извините за мой английский. Если вы поможете мне, я смогу сделать любое приложение для дизайна материалов для вас или для игры в google play. Спасибо. Если есть немного информации, пожалуйста, скажите мне.

ответ

0

Я думаю, если вы сохраните все ваши список строк для одного свойства предпочтений будет упростить управление.

посмотреть образец:

//for save 
StringBuilder sb = new StringBuilder(); 
for (String interest : mInterestList) { 
    sb.append(interest).append(","); 
} 
prefsEditor.putString("MyInterests", sb.toString()); 
prefsEditor.commit(); 

//for read 
String [] interests= sharedPreferences.getString("MyInterests"); 
mInterestList = new ArrayList<String>(Arrays.asList(interests)); 

в каждом изменении в вашей mInterestList просто сохранить его снова. нет необходимости удалять и добавлять. измените свой mInterestList и сохраните снова в общих настройках.

0

Похоже, что ваш адаптер работает от mInterestList. Я не вижу, что вы удаляете элемент данных из mInterestsList, когда вы удаляете предпочтение?

+0

Здравствуйте, я теперь отредактировал мой код (ниже remove prefs) Я добавил 'mInterestList.remove (position); adapterInterests.notifyDataSetChanged(); ' Но ничего не меняет Благодарим за ответ :). –

+0

Вы уже создали адаптер. Попробуйте позвонить adapterInterests.remove() – mjstam

+0

Я попробовал, но снова он не работает. Я думаю, что он удаляется из списка, но я думаю, что есть проблемы с предпочтениями .. или я не знаю, мне нужна помощь –

0

Вместо того, чтобы проверить, содержит ли общие предпочтения, увидеть, если он установлен в нуль вместо или нет, то есть сделать,

if (sharedPreferences.getString(Constants.INTEREST + position)!=null) { 
       SharedPreferences.Editor editor = sharedPreferences.edit(); 
       mInterestList.remove(position); 
       adapterInterests.notifyDataSetChanged(); 
       editor.remove(Constants.INTEREST + position); 



       editor.commit(); 
      } 
Смежные вопросы