gpt4 book ai didi

java - 我应该在哪里调用 fragment 中的 Rest API

转载 作者:行者123 更新时间:2023-12-04 23:48:50 25 4
gpt4 key购买 nike

我正在使用带有 3 个 fragment 的底部导航。在 Home-fragment 我请求 API 来获取数据并在回收器 View 中显示我的问题是每当我切换 fragment 并再次回到 Home-fragment 它正在重新创建布局并再次从 API 获取数据我只想加载一次应用启动时

This is where I call API in the fragment


  @Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.home_fragment, container, false);
// return inflater.inflate(R.layout.home_fragment, container, false);
sharedPrefManager = new SharedPrefManager(getActivity());
locationTrack = new LocationTrack(getActivity());

buildGoogleApiClient();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
getUserLatLng();
setUp(view);
netWorkCall();
return view;
}

HomeActivity to load home-fragment by default


if (savedInstanceState == null) {
Fragment fragment = null;
fragment = new HomeFragment();

if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.content_frame, fragment, "home").addToBackStack("Home");
ft.commit();
}
}

bottom-navigation click listener


private void displaySelectedScreen(int itemId) {

Fragment fragment = null;

switch (itemId) {

case R.id.action_home:
fragment = new HomeFragment();
break;
case R.id.action_profile:
if (sharedPrefManager.getAuthority()) {
fragment = new ProfileFragment();
} else {
SDConstant.switchActivity(this, LoginScreen.class);

}
break;
case R.id.action_calculator:
if (sharedPrefManager.getAuthority()) {
fragment = new CalculatorFragment();
} else {
SDConstant.switchActivity(this, LoginScreen.class);
}
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment, "home").addToBackStack("Home");
ft.commitAllowingStateLoss();
//ft.commitNow();
}
}
}

Please guide me solution How to solve this re-creation API call

最佳答案

首先,在 onViewCreated 内执行此调用而不是 onCreateView :

sharedPrefManager = new SharedPrefManager(getActivity());
locationTrack = new LocationTrack(getActivity());

buildGoogleApiClient();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
getUserLatLng();
setUp(view);
netWorkCall(); //this call has to be removed as explained later

为什么?因为 onCreateView 应该只返回 fragment UI。之后直接调用 OnViewCreated,这是做一些事情的地方。

不解决你的问题。解决此问题的最佳方法是将架构组件中的 ViewModel 与 LiveData 结合使用。

您可以阅读有关此主题的更多信息 here .

您的实现可能如下所示(改编自链接中的示例):
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<List<User>>();
loadUsers();
}
return users;
}

private void loadUsers() {
// Do an asynchronous operation to fetch users.
}
}

在您的 onViewCreated 中,您可以执行以下操作:
MyViewModel model = new ViewModelProvider(getViewLifecycleOwner()).get(MyViewModel.class);
model.getUsers().observe(getViewLifecycleOwner(), users -> {
// update UI
});

不要为此感到不知所措。它在现实中的作用相对简单。 ViewModel 在配置更改后仍然存在。这意味着如果您旋转手机,将不会再次调用 loadUsers 请求 - 与在底部导航选项卡之间切换相同。当然,如果 fragment 被销毁,ViewModel 也会被销毁(然后调用 onCleared 函数)。

LiveData 用户只是一个简单观察者的花哨名称。可变意味着你可以设置一个值,getUsers() 返回一个不可变的 LiveData,这意味着你只能读取它的值。当您为 LiveData 对象设置值时,将通知其订阅者。你可以把它想象成 LiveData 是一个由你的 Fragment 实现的接口(interface),它使用 ViewModel。一旦您获取数据,就会调用此接口(interface)函数。更多关于处理 LiveData 的信息 is explained here你一定要检查一下。

因此,如果尚未加载用户,则一旦您开始观察 getUsers,ViewModel 将调用 loadUsers。如果它们已被加载,则返回当前值。

哦,添加 LiveData 和 ViewModel -> it's explained here :)

希望这会有所帮助。我知道这很多,但相信我,值得投入时间!

关于java - 我应该在哪里调用 fragment 中的 Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62171730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com