我在处理活动中的onCreate()时遇到了一个主要问题。就像thread说的,我只能执行main活动的onCreate()方法中的一部分代码一次。因此,我按照该线程中的步骤执行了以下操作:
/*I've updated the code to SharePreferences version*/
public class MyApp extends Activity {
private static RMEFaceAppActivity instance;
private boolean wascalled = false;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//initiate some buttons here
sharedPreferences = this.getSharedPreferences("test",0);
editor = sharedPreferences.edit();
if(sharedPreferences.getString("wascalled", "false").equalsIgnoreCase("false"))
{
//work can only be done once
editor.putString("wascalled", "true");
editor.commit();
}
//set buttons to listener methods
}
void onClick(View arg0)
{
if(arg0.getId() == R.id.button1)
{
Intent intent = new Intent(this, MyChildApp.class);
startActivity(intent);
}
}
}在MyChildApp类中,当工作完成时,我调用了finish()。但是,字段wascalled始终为false。我认为当第二次执行从MyChildApp返回的onCreate()时,wascalled应该已经设置为true。每次从MyChildApp返回时,onCreate()方法中的if语句中的代码都会执行。
有人对此有什么建议吗?在此之前非常感谢。
发布于 2012-08-16 23:52:09
定义SharedPreferences并最初存储一个值0/false,以表明从未调用过。
现在,当第一次调用wasCalled时,将此SharedPreference变量的值更新为1/true。
下次运行onCreate()时,检查SharedPreference中该变量的值,如果该值为1/true,则不要再执行该变量。
实现SharedPreferences的代码:
final String PREF_SETTINGS_FILE_NAME = "PrefSettingsFile";
int wasCalledValue;
onCreate() {
....
SharedPreferences preferences = getSharedPreferences(PREF_SETTINGS_FILE_NAME, MODE_PRIVATE);
wasCalledValue= preferences.getInt("value", 0);
if(wasCalledValue == 0)
{
// execute the code
//now update the variable in the SharedPreferences
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("value", 1);
editor.commit();
}
else if(wasCalledValue == 1)
{
//skip the code
}
} // end of onCreate()发布于 2012-08-16 23:46:22
当你从MyChildApp返回时,myApp正在重新创建,所以onCreate被再次调用,变量被再次初始化(这就是为什么why总是false的原因)。
一种可能的解决方案是将the称为状态存储在SharePreferences中
发布于 2012-08-16 23:47:58
wascalled将始终为false,因为它是活动实例的一部分。它是在你的活动中声明的:
private boolean wascalled = false;当重新创建活动时,所有实例变量都初始化为它们的默认值,这就是为什么您得到always false的原因。
如果您注意到该thread中的代码,您会注意到该wascalled是另一个类的一部分,而不是Activity的类。
if (!YourApplicationInstance.wasCalled) {
}在这个具体的示例中,YourApplicationInstance是一个单独的类,它保持wascalled的状态为变量。
https://stackoverflow.com/questions/11990827
复制相似问题