我一直在网上搜索,但没有得到我所需要的正确答案。我是Android的新手,所以请提供一个详细的答案。
我有一个片段,它从用户那里获取一些数据,例如:名称、职业等等。每次我得到这些数据时,我都想用GSON存储到sharedPreferences。在搜索的基础上,我需要构造一个常规的Java类并传递对象(Android -将对象保存到SharedPreferences中,并在应用程序中的任何位置获取它。)。
我只是提供了一个用户作为一个例子,但一般地我想知道1和2的答案。
谢谢
发布于 2016-01-21 06:19:43
发布于 2016-01-21 07:29:37
下面是您的问题的解决方案和澄清。首先,我想澄清这个片段是一个具有生命周期方法的类。我所说的生命周期方法是指根据应用程序或活动生命周期调用方法,就像在前台、可见和背景中一样。下面是你的问题的答案。
- If you are not aware, Creating an object by calling new MyClass() takes up resources and also the object creation process is time consuming. So if you call them inside onResume() or onStart() method those objects will be created when the fragment move from visible state to focused(foreground - onResume() is called) and from background to visible(onStart() is called) state .
- This happens often when another application comes into focus(which causes the fragment to call onResume() or onStart() when your application comes into foreground) or when our application moves from background to visible state(onStart() is called). So object is created everytime this happens.
- But on the other hand if you create it inside onCreate() or lifecycle methods above it the objects will be created only when the fragment is destroyed and recreated.
- Also if you want to call methods from the class you have instantiated by above method you can call it from any lifecycle method below the onCreate() like in onStart() (if you wanted to show results before the user uses your fragment) or in onResume() (if you wanted to show results after the user sees it) it is upto you to do this.
- Also in my example above i have called retrieveData() method from onStart() and i have wrote that method from outside the lifecycle methods. it is just for an example. You can do like that. But you have to call those methods inside the lifecycle methods according to your needs.
- Finally here is a link to learn more about the lifecycle methods of the Fragment. [Learn About Fragment LifeCycle](https://developer.xamarin.com/guides/android/platform_features/fragments/part_1_-_creating_a_fragment/)
我希望这能帮你找到解决办法。谢谢。
https://stackoverflow.com/questions/34916460
复制相似问题