在我的应用程序中永远不会调用OnSharedPreferenceChangeListener()

时间:2013-07-10 03:45:35

标签: android android-listview android-preferences

我一直在App处理PreferenceActivity,我有一个ListPreference用于排序ListView,位于MainActivity。我已经实现了OnSharedPreferenceChangeListener(),但当我回到MainActivity我有一个listView时,有些时候ListView消失,当我关闭我的应用时然后重新启动它ListView在我的选择中排序,最后一次在PreferenceActivity中选择,我的代码是:

protected SharedPreferences settings = null;
private OnSharedPreferenceChangeListener changeListener;

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

    settings = PreferenceManager
            .getDefaultSharedPreferences(MainActivity.this);

    // Make a Connection to Database... and open it...
    source = new CandidateDataSource(MainActivity.this);
    source.opend_db();

    objects = source.getAllData();

    // adapter = new CandidateAdapter(MainActivity.this, objects, true);

    adapter = initializeList(settings.getString("sort_order",
            CandidateOpenHelper.COL_NAME));

    changeListener = new OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences arg0,
                String arg1) {
            // TODO Auto-generated method stub
            String setPrefs = settings.getString("sort_order", "Not Found");

            adapter = initializeList(setPrefs);
            Log.e("PREFS REFS", "PREF IS " + setPrefs);
        }
    };

    settings.registerOnSharedPreferenceChangeListener(changeListener);

    UIHelper.listHelper(MainActivity.this, R.id.list_container, adapter,
            null, null);

}

private CandidateAdapter initializeList(String sort_order) {
    if (objects != null) {
        objects.close();
    }

    objects = source.getAllData(sort_order);

    return adapter = new CandidateAdapter(MainActivity.this, objects, true);
}

UIHelper.listHelper()方法如下:

static public void listHelper(Activity activity, int id, CandidateAdapter adapter, OnItemClickListener itemClickListener, OnItemLongClickListener longClickListener){
    ListView listView = (ListView) activity.findViewById(id);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(itemClickListener);
    listView.setOnItemLongClickListener(longClickListener);
}

在这种情况下如何使OnSharedPreferenceChangeListener()正常工作。

0 个答案:

没有答案