Reputation: 741
Good day,
The app needs to monitor the incoming SMS even the app killed so I think Service is the best way to do the job but I faced the problem when I trying to call the viewmodel.
I am trying to select, insert, update, delete my room database from the background process using Service to my project. Here is my simple code.
public class ReadIncomingSMS extends Service {
RoomViewModel model;
@Override
public IBinder onBind(Intent intent) { return null; }
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
model = ViewModelProviders.of((FragmentActivity) getApplicationContext()).get(RoomViewModel.class);
}
}
but the logcat says,
java.lang.RuntimeException: Unable to start service com.mgb.textvote.services.ReadIncomingSMS@3ae6b5cf with Intent { cmp=com.mgb.textvote/.services.ReadIncomingSMS }: java.lang.ClassCastException: android.app.Application cannot be cast to androidx.fragment.app.FragmentActivity at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3119)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to androidx.fragment.app.FragmentActivity at com.mgb.textvote.services.ReadIncomingSMS.onStartCommand(ReadIncomingSMS.java:47)
if the application context cannot be cast to fragmentActivity then how can we use the room database inside the service or what is the best way to query in the background process?
Upvotes: 2
Views: 1599
Reputation: 741
Thanks to Antonis answer,
instead of accessing FragmentActivity ViewModel in Service, I change the code like this.
To my MainActivity.java
public class MainActivity extends AppCompatActivity {
public static RoomViewModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
model = ViewModelProviders.of(this).get(RoomViewModel.class);
}
}
then in my Service
instead of
model = ViewModelProviders.of((FragmentActivity) getApplicationContext()).get(RoomViewModel.class);
I changed it to
model = MainActivity.model;
I don't know if this method is a good practice but it seems works for me.
Upvotes: 0
Reputation: 3097
You are trying to access FragmentActivity ViewModel in Service.
Create separate ViewModel for Service and it will work.
Upvotes: 2