带有布尔数组的SharedPreference上的ArrayIndexOutOfBoundsException?

时间:2018-07-19 06:18:34

标签: java android arrays sharedpreferences

我对我的布尔数组抛出了异常,但我不知道为什么会这样。我浏览了一些网站,以寻求针对此类问题的建议或解决方案,但是我什么都没找到。

这就是我之所以要求SO的原因,因为我没有找到针对该典型代码解决相同问题的问题。我坐了大约5个小时来实现SharedPreference。

这是我的代码,正在我的PreferenceClass上运行。我试图保存来自用户的Multichoice输入。单击musicPreference后,应用程序崩溃,我被迫关闭。

boolean[] isSelectedMusic;

@Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.main_settings);

    musikPreference = findPreference(getString(R.string.pref_music_key));

    listMusicName = getResources().getStringArray(R.array.music);
    listMusicId = getResources().getStringArray(R.array.music_values);

    isSelectedMusik = new boolean[listMusikName.length];




    /*
        TODO Guck wie sich der Input ändert je nachdem kann man sagen wie man es ändert
     */
    if ((Arrays.equals(getStoredMusik("storedSelectedMusik"), isSelectedMusik))==false) {
        isSelectedMusik = getStoredMusik("storedSelectedMusik");
    }

    musikPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            AlertDialog.Builder musik_dialog_builder = new AlertDialog.Builder(getActivity());
            musik_dialog_builder.setTitle(R.string.pref_title_musik);
            musik_dialog_builder.setMultiChoiceItems(listMusikName, isSelectedMusik, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int position, boolean is_selected) {
                    if (is_selected) {
                        userMusik.add(position);
                        System.out.println("Position des Items: +" + position);
                    } else {
                        userMusik.remove((Integer.valueOf(position)));
                    }
                }

            });

            musik_dialog_builder.setCancelable(false);
            musik_dialog_builder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    String musik = "";
                    for (int i = 0; i < userMusik.size(); i++) {
                        musik = musik + listMusikName[userMusik.get(i)];
                        System.out.println("Z.100 - Z.106\n" +
                                "item: " + musik + "\n" +
                                "i: " + i + "\n" +
                                "id:" + listMusikId[i] + "\n");

                        userMusikID.add(listMusikId[i]);
                        userMusikName.add(listMusikName[i]);

                        isSelectedMusik[i] = true;


                        if (i != userMusik.size() - 1) {
                            musik = musik + ", ";
                            System.out.println("Z.108 - Z.112\n" +
                                    "item: " + musik + "\n" +
                                    "i: " + i + "\n");
                        }
                    }
                    setMusik(musik);
                    storeSelectedMusik(isSelectedMusik,"storedSelectedMusik");

                }
            });

            private void storeSelectedMusik(boolean[] isSelectedMusikList, String arrayName) {
                SharedPreferences mSharedPreferences = this.getActivity().getSharedPreferences("DataOfSelectedMusik", 0);
                SharedPreferences.Editor mEditor = mSharedPreferences.edit();

                mEditor.putInt(arrayName + "_size", isSelectedMusikList.length);

                for (int i = 0; i < isSelectedMusikList.length; i++) {
                    mEditor.putBoolean(arrayName + "_" + i, isSelectedMusikList[i]);
                }


                mEditor.apply();
            }

            private boolean[] getStoredMusik(String arrayName) {
                SharedPreferences mSharedPreferences = this.getActivity().getSharedPreferences("DataOfSelectedMusik", 0);
                int size = mSharedPreferences.getInt(arrayName + "_size", 0);
                boolean[] isSelectedMusikArray = new boolean[size];

                for (int i = 0; i < size; i++) {
                    isSelectedMusikArray[i] = mSharedPreferences.getBoolean(arrayName + "_" + i, false);
                }

                return isSelectedMusikArray;
            }

这是我在Logcat上遇到的异常。

  

07-19 05:41:56.048 4769-4769 / cren.example.com.musiclover E / AndroidRuntime:FATAL EXCEPTION:main
          程序:cren.example.com.musiclover,PID:4769
          java.lang.ArrayIndexOutOfBoundsException:length = 0;索引= 0
              在com.android.internal.app.AlertController $ AlertParams $ 1.getView(AlertController.java:1101)
              在android.widget.AbsListView.obtainView(AbsListView.java:2366)
              在android.widget.ListView.measureHeightOfChildren(ListView.java:1408)
              在android.widget.ListView.onMeasure(ListView.java:1315)
              在android.view.View.measure(View.java:23169)
              在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
              在android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
              在android.view.View.measure(View.java:23169)
              在com.android.internal.widget.AlertDialogLayout.tryOnMeasure(AlertDialogLayout.java:144)
              在com.android.internal.widget.AlertDialogLayout.onMeasure(AlertDialogLayout.java:69)
              在android.view.View.measure(View.java:23169)
              在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
              在android.widget.FrameLayout.onMeasure(FrameLayout.java:185)               在android.view.View.measure(View.java:23169)
              在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
              在android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
              在android.view.View.measure(View.java:23169)
              在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
              在android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
              在com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
              在android.view.View.measure(View.java:23169)
              在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2719)
              在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1545)
              在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1856)
              在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
              在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:7184)
              在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:949)
              在android.view.Choreographer.doCallbacks(Choreographer.java:761)
              在android.view.Choreographer.doFrame(Choreographer.java:696)
              在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:935)
              在android.os.Handler.handleCallback(Handler.java:873)
              在android.os.Handler.dispatchMessage(Handler.java:99)
              在android.os.Looper.loop(Looper.java:193)
              在android.app.ActivityThread.main(ActivityThread.java:6669)
              在java.lang.reflect.Method.invoke(本机方法)
              在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)
              在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

1 个答案:

答案 0 :(得分:2)

length=0

表示您的数组实际上是空的。您正在尝试获取空数组的第一个元素。

我没有从堆栈跟踪中立即看到抛出异常的行,但是可能发生了几次array[index]调用。例如,在这里:

for (int i = 0; i < userMusik.size(); i++) {
                        musik = musik + listMusikName[userMusik.get(i)];
                        System.out.println("Z.100 - Z.106\n" +
                                "item: " + musik + "\n" +
                                "i: " + i + "\n" +
                                "id:" + listMusikId[i] + "\n");

                        userMusikID.add(listMusikId[i]);
                        userMusikName.add(listMusikName[i]);

您确认自己没有超过userMusik的大小,但是没有检查尝试从listMusikIdlistMusikName检索的元素是否存在。