Is it safe to rely on the call to onDataSetChanged() after onCreated() in RemoteViewsFactory of an AppWidget
Asked Answered
W

1

6

I developed my AppWidget according to the android doc, loading my cursor in onCreate() and reloading it in onDataSetChanged(), and everything worked fine, until I set some breakpoints in my RemoteViewsService.RemoteViewsFactory and surprisingly found that onDataSetChanged() is always called after the call to onCreate(), which made my cursor loaded twice when first created. I'm on Android 4.4.3.

According to the Api doc,

public abstract void onDataSetChanged ()

Added in API level 11

Called when notifyDataSetChanged() is triggered on the remote adapter. This allows a RemoteViewsFactory to respond to data changes by updating any internal references. Note: expensive tasks can be safely performed synchronously within this method. In the interim, the old data will be displayed within the widget.

Seems that this call is only triggered by manually calling notifyDataSetChanged() ourselves.

However acccording to the Appwidget guide,

In onCreate() you setup any connections / cursors to your data source. Heavy lifting, for example downloading or creating content etc, should be deferred to onDataSetChanged() or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.

By saying deferred, is it implying that onDataSetChanged() will be called after onCreate()? I'm not so sure... However it does say I should setup my cursor inside onCreate().

I tried to investigate this issue myself, however the available source code is using Binder so the remote caller remains unknown, thus I cannot inspect its source.

Do you have any idea?

Wirehaired answered 12/8, 2014 at 8:56 Comment(0)
S
5

As you can see in your linked guide, onDataSetChanged is every time called after onCreate:

Data flow

(App Widgets | Android Developers)

So it's safe to load your cursor in onDataSetChanged

Scolopendrid answered 23/8, 2015 at 8:22 Comment(2)
Part of the problem is that the relationship between notifyAppWidgetViewDataChanged and onDataSetChanged is not well described. They appear to reference the wrong method name or an old name for the method. The only hint to the solution is given using an easily overlooked link: developer.android.com/reference/android/widget/…Swot
@Auroratic: You seem very expert on widgets, can I ask your opinion on a question?Shallow

© 2022 - 2024 — McMap. All rights reserved.