In my app, when a Broadcast Receiver does what it does, I want to start a database operation as well, but the class that handles the database operation reqiures an instance of the DB singleton, which I usually hold in the application object, which is not accessible through the service context
Here is what happens:
This is my database handler:
public class DatabaseManager extends SQLiteOpenHelper {
// Its a good practice for DBTools to be a singleton. Do not instantiate it with "new DBTools(context)" but with
// DBTools.getInstance(context) instead
private static DatabaseManager sInstance;
public SQLiteDatabase database;
public static DatabaseManager getInstance(Context context) {
if (sInstance == null) {
sInstance = new DatabaseManager(context);
}
return sInstance;
}
public DatabaseManager(Context context) {
super(context, Preferences.LOCAL_SQLITE_DATABASE_NAME, null, 1);
}
In my Application Class I instatiate it this way:
// SQLite Database Handler
public DatabaseManager databaseManager;
@Override
public void onCreate() {
super.onCreate();
databaseManager = DatabaseManager.getInstance(this);
in my receiver I want to start a database operation:
public class PushNotificationReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//DatabaseManager databaseManager = DatabaseManager.getInstance(context); -> This didnt work when the database was closed in onDestroy of my app.
new IncrementProgressIntoDB(context, eventId).execute();
and this is IncrementProgressIntoDB
public class IncrementProgressIntoDB extends AsyncTask<Void, Void, Boolean> {
private int eventId;
private Context context;
public IncrementProgressIntoDB(Context context, int eventId) {
this.context = context;
this.eventId= eventId;
}
@Override
protected Boolean doInBackground(Void... params) {
((MyApplication) context).databaseManager.database.beginTransaction();
and in this last line, I get the following exception:
06-02 10:45:00.552: E/AndroidRuntime(7778):
Caused by: java.lang.ClassCastException: android.app.ReceiverRestrictedContext
cannot be cast to com.asdqwe.asd.MyApplication
I tried the solution from here: Static way to get 'Context' on Android?
but the context that I got was unable to resolve the databaseManager as a field.