在 Fragment 中调用 AsyncTask(FragmentStatePagerAdapter 问题)
Call AsyncTask in a Fragment (FragmentStatePagerAdapter issue)
我知道这个问题已经有人问过,但我找不到任何解决办法。
事情是这样的:
- 我有一个 Activity
,其中包含三个选项卡。
- 每个选项卡都是一个 Fragment
。
- 整个事情是使用 FragmentSatePagerAdapter
管理的
当我滑到最后一个选项卡时,我想向服务器发送一个请求,并用收到的 Json
填充一个 ListView
。听起来很容易。
我有一个扩展 AsyncTask 的 class,我用它来处理对服务器的请求
public class HttpAsyncNotif extends AsyncTask<String, Void, JSONArray>{
private TabOperations tabOperationsCaller; // This is my fragment
public HttpAsyncNotif(TabOperations caller){
this.tabOperationsCaller = caller;
}
// Others methods of Asynctask
}
这是我的片段的代码(最后一个标签)
public class TabOperations extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab_operations, container, false);
return rootView;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
new HttpAsyncNotif(this).execute(user.getUsername()); // Got the NullPointerException
}
}
}
详细查看了Fragment的生命周期,但仍然没有解决方案。
我该怎么做?
非常感谢!
改变
new HttpAsyncNotif(this).execute(user.getUsername());
到
new HttpAsyncNotif(getActivity()).execute(user.getUsername());
通过使用 getActivity()
在 Fragment
中获得 Context
还要在 user.getUsername()
之前检查 user!=null
问题出在 Context
您已经通过了。将代码更改为
new HttpAsyncNotif(getActivity()).execute(user.getUsername());
我知道这个问题已经有人问过,但我找不到任何解决办法。
事情是这样的:
- 我有一个 Activity
,其中包含三个选项卡。
- 每个选项卡都是一个 Fragment
。
- 整个事情是使用 FragmentSatePagerAdapter
管理的
当我滑到最后一个选项卡时,我想向服务器发送一个请求,并用收到的 Json
填充一个 ListView
。听起来很容易。
我有一个扩展 AsyncTask 的 class,我用它来处理对服务器的请求
public class HttpAsyncNotif extends AsyncTask<String, Void, JSONArray>{
private TabOperations tabOperationsCaller; // This is my fragment
public HttpAsyncNotif(TabOperations caller){
this.tabOperationsCaller = caller;
}
// Others methods of Asynctask
}
这是我的片段的代码(最后一个标签)
public class TabOperations extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tab_operations, container, false);
return rootView;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
new HttpAsyncNotif(this).execute(user.getUsername()); // Got the NullPointerException
}
}
}
详细查看了Fragment的生命周期,但仍然没有解决方案。
我该怎么做?
非常感谢!
改变
new HttpAsyncNotif(this).execute(user.getUsername());
到
new HttpAsyncNotif(getActivity()).execute(user.getUsername());
通过使用 getActivity()
Fragment
中获得 Context
还要在 user.getUsername()
user!=null
问题出在 Context
您已经通过了。将代码更改为
new HttpAsyncNotif(getActivity()).execute(user.getUsername());