使用Set <string>和sharedPreferences更新列表适配器不起作用

时间:2015-05-05 16:23:49

标签: android sharedpreferences custom-adapter

我正在使用带文本和按钮的自定义适配器。文本以SharePreferences中的Set形式存储。 (使用editor.putStringSet()方法)

每当我更新这组字符串时,我都会调用notifyDataSetChanged(),但它不会更新列表。

请参阅下面的活动:

public String[] teamsToProgress()
{
    Arrays.sort(teams);
    String[] teamsToProgress = new String[2];
    for (int i=0; i<2 ; i++)
    {
        teams[i] = teamsToProgress[i];
    }
}

}

以下是适配器: -

public class FunctionaScreen extends ActionBarActivity {
private Button button;
private EditText edit;
SharedPreferences prefs;
Set<String> nums;
private ArrayAdapter<String> listAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_functiona_screen);

    prefs = getApplicationContext()
            .getSharedPreferences("CALLBACKPREFS", 0);

    button = (Button) findViewById(R.id.button1);
    edit = ((EditText) findViewById(R.id.editText1));
    nums = prefs.getStringSet("nums", new HashSet<String>(Arrays.asList("")));
    listAdapter = new NumbersAdapter(this, nums.toArray((new String[nums.size()])));

    final ListView mainListView = (ListView) findViewById(R.id.listView1);
    mainListView.setAdapter(listAdapter);

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            SharedPreferences.Editor editor = prefs.edit();
            nums.add(edit.getText().toString());
            editor.putStringSet("nums", nums);
            editor.commit();
            mainListView.invalidateViews();
            listAdapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), "Number updated !!", 0)
                    .show();

        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.functiona_screen, menu);
    return true;
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

请注意为什么我无法在活动按下按钮时更新列表,或按下删除按钮(在适配器中)。

1 个答案:

答案 0 :(得分:1)

在适配器中修改活动或数组中的Set不会修改ArrayAdapter中的数据存储。

您应该使用 ArrayAdapter 添加删除方法: http://developer.android.com/reference/android/widget/ArrayAdapter.html#add(T) http://developer.android.com/reference/android/widget/ArrayAdapter.html#remove(T)

编辑器的 commit 方法也可以阻止用户界面看看应用方法。