I want to select data on room database with livedata from service class. How to cast the LifecycleOwner when observe it?
repositoryDatabase.getTimeline().observe(this, timelineList -> {
if (timelineList != null && timelineList.size() >= 10) {
JSONArray arrayTimeline = new JSONArray();
for (TimelineEntity timeline : timelineList) {
JSONObject objectTimeline = new JSONObject();
try {
objectTimeline.put("doku", timeline.getIdDokumen());
objectTimeline.put("entrydate", timeline.getEntryDate());
objectTimeline.put("lat", timeline.getLat());
objectTimeline.put("lng", timeline.getLng());
arrayTimeline.put(objectTimeline);
} catch (JSONException e) {
e.printStackTrace();
}
}
onUpdateLocation(arrayTimeline.toString());
}
});
Every Activity has a Lifecycle. This Activity will be a Lifecycle Owner(any activity or fragment can be called a lifecycle owner). When an activity is initialized LifecycleOwner is the one that will be constructed initially. Any class that implements the LifeCycleOwner interface indicates that it has Android LifeCycle.
ProcessLifecycleOwner. Class that provides lifecycle for the whole application process. A class that has an Android lifecycle. These events can be used by custom components to handle lifecycle changes without implementing any code inside the Activity or the Fragment.
When using a ViewModel exposing LiveData s for a Fragment , there are currently two LifecycleOwners that can be used to oberve: the Fragment itself or. the Fragment 's property mViewLifecycleOwner .
You can use LifecycleService
like this:
Add this dependency to your app/build.gradle file:
dependencies {
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
}
Extend your service with LifecycleService
:
class MyService extends LifecycleService {
...
}
After that you will be able to observe your LiveData
.
Add this dependency to your app/build.gradle file:
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
As mentioned in the androidx.lifecycle release page
Version 2.2.0 ~~ January 22, 2020 ~~ Important changes since 2.1.0
lifecycle-extensions Artifact Deprecation: With the above deprecation of ViewModelProviders.of(), this release marks the deprecation of the last API in lifecycle-extensions and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such as lifecycle-service if you’re using LifecycleService and lifecycle-process if you’re using ProcessLifecycleOwner) rather than lifecycle-extensions as there will not be a future 2.3.0 release of lifecycle-extensions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With