Best practice for loose coupling between data & UI in Android - Adapter, Filter, CursorLoader and ContentProvider

大城市里の小女人 提交于 2019-12-23 02:35:42

问题


Assume we have an Activity with n TextViews that represent one line notes. These notes are stored somewhere (local database, network etc), and each time onResume() being called, the proper number of TextViews are drawn according to that stored data.

Now, lets say the user want to delete a note, what would be the best way the resolve the specific TextView, back to its storage entity?

At the moment, the only way I know is by using View.Tag, and having some manager to translate it to data entity, but it look rather messy.

Are there any other options?


回答1:


In Android, the Adapter acts a bridge between the view and the data model. You could display the n TextViews in either a ListView or a GridView, and when the user adds or deletes a note, the local or server database is first updated. Upon completion of the web service call and/or the local database update, the new data is added to the underlying Adapter. The View is then refreshed by calling adapter.notifyDataSetChanged(). This would be the way to do it.

Approaches:

  • If updating the local SQLite database, you could consider using a CursorAdpater to hold the data for the View, as it directly maps the entries in the local database to the View.
  • If making use of a ContentProvider, it is even possible to combine a CursorAdapter with a LoaderManager and a CursorLoader: these plug into the Activity / Fragment life-cycle and monitor the underlying ContentProvider for changes that are published automatically to the View on a separate thread.
  • It is also possible to use a Filter in conjunction with the Adapter to define a dynamic mechanism that sorts the data entries on-the-fly. The filtering is performed by the Filter on a separate thread, as per a query entered by the user, possibly in an AutoCompleteTextView.

References:

  • See the Retrieving a List of Contacts tutorial. The example here retrieves a set of contacts from the contacts ContentProvider based on a dynamic, alphabetical search by the user. It makes use of CursorAdapter, CursorLoader and LoaderManager to monitor and update the data, and it displays the search results in a ListView.
  • See also the Android Realtime (Instant) Search with Filter Class example, which shows how a Filter is to be used.
  • Android AutoCompleteTextView with Custom Adapter filtering.
  • Android AutocompleteTextView using ArrayAdapter and Filter.


来源:https://stackoverflow.com/questions/29456136/best-practice-for-loose-coupling-between-data-ui-in-android-adapter-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!