I have created a widget application, in which I use SQLite database object which is initialized when user enable his widget. I declare Database object as static as in other case it become null just after onReceive() method called and my application crashes.
Now I am using mDatabase object in onReceive() method and everything works except:
- Is it normal to keep static member of Database in the Widget or there is more correct way to do that?
- After some time of using application (one day or two) my application crashes, look like some members become null (may be
mDatabase), I think if you answer my first question it will be answer for second too 🙂
Code example
public class Widget extends AppWidgetProvider {
private static DatabaseObject mDatabase = null;
private static int mIndex = 0;
@Override
public void onEnabled(Context context) {
mDatabase = new DatabaseObject (context);
mDatabase.initialize("Some data");
}
@Override
public onReceive(Context context, Intent intent)
{
// Some code ....
mDatabase.getItemAtIndex(mIndex);
mIndex++;
}
};
You are not supposed to do long lasting operations in
onReceive(). You should start a service (IntentService) that updates your widget and do your DB work there. Also keep in mind that your app’s activities and services can be killed at any time, so you need to handle this. If you need to access your DB helper class (DatabaseObject) make it a singleton and it will be available for the while lifecycle of your process.