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

1

2

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?

Slenderize answered 5/4, 2015 at 9:58 Comment(0)
P
4

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:

Phlyctena answered 5/4, 2015 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.