这是正常使用静态成员的Android窗口小部件类? [英] Is it normal to use static members in Android widget class?
问题描述
我已经创建了一个Widget应用,在我使用的时候用户实现他的控件,它被初始化SQLite数据库对象。我宣布Database对象为静态在其他情况下,它成为空
刚过名为的onReceive()
方法和我的应用程序崩溃
现在我使用 mDatabase
对象的onReceive()
方法,一切工作除了:
- 这是正常的,保持数据库的静态成员在Widget或有做吗? 更正确的方法
- 后,使用应用程序(一两天)我的应用程序崩溃的一段时间,像一些成员成为空(可
mDatabase
),我如果你回答觉得我第一个问题,这将是第二个答案过于:)
code例如
公共类的Widget扩展AppWidgetProvider { 私有静态DatabaseObject mDatabase = NULL;
私有静态诠释MINDEX = 0; @覆盖
公共无效onEnabled(上下文的背景下){
mDatabase =新DatabaseObject(背景);
mDatabase.initialize(一些数据);
} @覆盖
公众的onReceive(上下文的背景下,意图意图)
{
//有些code ....
mDatabase.getItemAtIndex(MINDEX);
MINDEX ++;
}};
您不应该做的长久运营的的onReceive()
。你应该开始( IntentService
),更新你的widget服务,做您的数据库在那里工作。也请记住,你的应用程序的活动和服务可以在任何时候被杀死,所以你需要处理这个问题。如果您需要访问数据库的辅助类( DatabaseObject
),使它成为一个单身,这将是适用于您的过程,而生命周期。
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.
这篇关于这是正常使用静态成员的Android窗口小部件类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!