Assume we have an Activity
with n
TextView
s that represent one line notes. These notes are stored somewhere (local database, network etc), and each time onResume()
being called, the proper number of TextView
s 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?
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.