简体   繁体   English

通过意图调用其他活动后保存活动状态

[英]Saving activity state after calling another activity through intent

I have two activities: 我有两个活动:

Activity A-->the onCreate() method interacts with a database and shows data in the Activity. 活动A-> onCreate()方法与数据库交互并在活动中显示数据。

Activity B (generic) 活动B(通用)

Now,in my Activity A,I have a button that,through a Intent,brings me to Activity B;the same Intent is found in the Activity B to go back from B to A. 现在,在我的活动A中,我有一个按钮,该按钮通过一个意图将我带到活动B;在活动B中发现了相同的意图,可以从B转到A。

Here's the problem:when i go back from B to A,the onCreate method is called again,and the data is taken from the database again. 这是问题所在:当我从B返回到A时,再次调用onCreate方法,并且再次从数据库中获取数据。 Is there a way I can go from Activity B to A without having to take data again from the database,maybe 'saving' the state of the Activity A? 有没有一种方法可以使我从活动B转到A,而不必再次从数据库中获取数据,也许可以“保存”活动A的状态?

Thank you. 谢谢。

If you do a new Intent its impossible to save data because u are creating a new object every time u save the method. 如果执行新的Intent,则不可能保存数据,因为每次您保存方法时都会创建一个新对象。

You have some options to solve it, try to override the onSavedInstanceState method in the activity. 您有一些解决方案,请尝试在活动中覆盖onSavedInstanceState方法。

You can also send the data u have do save from one activity to another. 您还可以将自己保存的数据从一个活动发送到另一个活动。

I can help u more if u give us some code example :) 如果您给我们一些代码示例,我可以为您提供更多帮助:)

When you come back to Activity A it should be in the Resume state, so if you don't have it you should create an onResume method where that can re-handle database stuff or not. 返回到活动A时,它应该处于Resume状态,因此,如果没有它,则应该创建一个onResume方法,该方法可以重新处理数据库内容。 Depending on what you want when you come back to Activity A 回到活动A时,取决于您想要的内容

@Override
public void onResume() {
   super.onResume();
   //saved data base stuff can be here
   System.out.println("Resuming...");   //just a sanity check if you want to watch the logs do this
}

Don't know what you're doing but you may need to separate some code where onCreate just initializes stuff then have your database interactions called elsewhere. 不知道您在做什么,但是您可能需要分离一些代码,其中onCreate只是初始化东西,然后在其他地方调用数据库交互。

I found a solution: When Activity A calls Activity B through Intent,it passes to the Activity B the values I need to keep using putExtra. 我找到了一个解决方案:当活动A通过Intent调用活动B时,它将需要使用putExtra保持的值传递给活动B。

Then the Activity B receives these values through getIntent() ,and when the Activity B calls again the Activity A through Intent,it passes back the values it received at the start. 然后,活动B通过getIntent()接收这些值,并且当活动B通过Intent再次调用活动A时,它将回传它在开始时收到的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM