Is it Possible to Use PreferenceActivity with SQLi

2019-01-26 00:25发布

The beauty of PreferenceActivity is its tight integration with Android's res/xml. All you need to do achieve the magic of self-managed preference reading/saving, along with the UI, is define:

public class MyPreferenceActivity extends PreferenceActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
  }
}

And define any <PreferenceScreen> structure you need in XML file(s).

But this also seems to be its weakness: It is so tightly integrated, that I have no idea whether it is possible to use PreferenceActivity with SQLite (for a more structured preference management), without re-inventing the while (i.e. re-writing an entire "PreferenceActivity" from scratch).

For example, using OnSharedPreferenceChangeListener may provide a gateway to using PreferenceActivity with SQLite, but it still requires the res/xml definitions to be in place - so really we are still constrained by the limitations of the res/xml method.

Is there a way to "eat the cake and have it too"? i.e. Use PreferenceActivity with SQLite in the same ease as res/xml's.

1条回答
男人必须洒脱
2楼-- · 2019-01-26 00:54

Interesting question.

Short answer: AFAIK, there is no way you can use SQLite with PreferenceActivity without doing significant customization as it is not designed to work in that manner.

The point here is why do you actually need SQLite for managing preferences? SQLite should as-a-rule never be used for lesser data that can be managed without requiring relational structure. For istance, it makes perfect sense to use SQLite when you have multiple instances of similar data like rows in a table.

In case of Preferences, I cannot figure any such instances. Moreover SQLite hits the performance of the application compared to SP. Make your choices wisely.

Update: In case you have multiple Preferences like in the question mentioned above you can use a combination of SQLite and SP. You cannot replace SP with SQLite for sure. What can be done though is that you need to keep a unique key which would become the primary key of the table and then in onPause of the PreferenceActivity you need to fire insert/update query in the SQLite table. You need to be careful and ensure correct SP are displayed and hence in onResume of PreferenceActivity you need to be able to fire fetch query with the unique key and set the SP accordingly.

查看更多
登录 后发表回答