微调框未清除

时间:2018-11-18 05:51:36

标签: android spinner adapter

我有一个奇怪的错误,我不确定为什么会发生,

我有2个活动:活动A和活动B。

应用启动后,会初始化一次微调器。我参加第二项活动,然后返回<-

活动A的

onRestart()将被调用。我的问题是,即使我清除了微调器并在onRestart()中对其进行了初始化,它仍会继续读取值。

例如,如果在活动B时微调框的值为1/2,然后再回到活动A,则微调框的值为= 1/2/1/2。

我发现这很奇怪,因为当我将微调器适配器设置为null并在从活动B返回活动A时注释掉微调器的初始化时,我的微调器为空。

这是我的代码:

  @Override public void onRestart() {
        super.onRestart();
        Spinner location = findViewById(R.id.spinnerLocation);
        location.setAdapter(null); 


        initSpinner();// if this is commented out spinner is cleared, if not commented the same valus are added again


    }

这是initSpinner的代码(从共享首选项中读取),这不是问题

public void initSpinner(){
        Spinner location = findViewById(R.id.spinnerLocation);
location.setAdapter(null);
        SharedPreferences prefs = this.getSharedPreferences("Locations", Context.MODE_PRIVATE); //preffilename
        SharedPreferences.Editor editor = prefs.edit();
      editor.putString("1","St. Catharines");
      editor.putString("2","Toronto");
      editor.putString("3","Niagara Falls");
        editor.commit();
        int s = prefs.getAll().size();




            for(int f=0;f<25;f++) {
                if (prefs.getString(String.valueOf(f + 1), null) != null) {
                    DefaultLocations.add(prefs.getString(String.valueOf(f + 1), null));


                }
            }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, DefaultLocations);
//set the spinners adapter to the previously created one.
        location.setAdapter(adapter);
    }

1 个答案:

答案 0 :(得分:0)

DefaultLocations.clear()方法内for循环之前的initSpinner(),在添加新值时可能无法清除

相关问题