Isaac Bosca
Isaac Bosca

Reputation: 1648

How to perform a database operation when onMessageReceived is triggered?

I'm trying to update my Room database when Firebase Cloud Messaging executes onMessageReceived.

The problem comes when my app is closed, because in this scenario, my database connection is not created yet, so this throws an Exception.

I'm creating the Room database connection instance from MainActivity which is launched every time that user launch the application, using this line:

db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database").build();

This db var is public and static, so normally I access it from anywhere in my app, since always is available.

But, in this situation is not available, I also tried, with no success, to create a new connection instance from onMessageReceived, but it's not posible since I can't use getApplicationContext() method, because there are no Activity.

There are any workaround? Thank you in advance!

Upvotes: 0

Views: 491

Answers (1)

Salaudeen Abdulrahman
Salaudeen Abdulrahman

Reputation: 129

onMessageReceived is a method in FirebaseMessagingService which is obviously a service. And a service is also a context. So it is not a must to use your MainActivity as the context.

In your onMessageReceived method, simply use:

Room.databaseBuilder(this, AppDatabase.class, "database").build();

Upvotes: 2

Related Questions