首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何避免在onCreate()中执行某些代码

如何避免在onCreate()中执行某些代码
EN

Stack Overflow用户
提问于 2012-08-16 23:41:12
回答 3查看 335关注 0票数 2

我在处理活动中的onCreate()时遇到了一个主要问题。就像thread说的,我只能执行main活动的onCreate()方法中的一部分代码一次。因此,我按照该线程中的步骤执行了以下操作:

代码语言:javascript
复制
/*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语句中的代码都会执行。

有人对此有什么建议吗?在此之前非常感谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-08-16 23:52:09

定义SharedPreferences并最初存储一个值0/false,以表明从未调用过

现在,当第一次调用wasCalled时,将此SharedPreference变量的值更新为1/true

下次运行onCreate()时,检查SharedPreference中该变量的值,如果该值为1/true,则不要再执行该变量。

实现SharedPreferences的代码:

代码语言:javascript
复制
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()
票数 1
EN

Stack Overflow用户

发布于 2012-08-16 23:46:22

当你从MyChildApp返回时,myApp正在重新创建,所以onCreate被再次调用,变量被再次初始化(这就是为什么why总是false的原因)。

一种可能的解决方案是将the称为状态存储在SharePreferences中

票数 0
EN

Stack Overflow用户

发布于 2012-08-16 23:47:58

wascalled将始终为false,因为它是活动实例的一部分。它是在你的活动中声明的:

代码语言:javascript
复制
private boolean wascalled = false;

当重新创建活动时,所有实例变量都初始化为它们的默认值,这就是为什么您得到always false的原因。

如果您注意到该thread中的代码,您会注意到该wascalled是另一个类的一部分,而不是Activity的类。

代码语言:javascript
复制
if (!YourApplicationInstance.wasCalled) {
}

在这个具体的示例中,YourApplicationInstance是一个单独的类,它保持wascalled的状态为变量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11990827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档