使用recyclerview和Asynctask安装Viewpager



我有一个ViewPager和3个Fragment,根据Android文档,ViewPager.setOffscreenPageLimit(1);至少为1。当我在ViewPager中有多个Fragments,并且每个Fragment都必须从Server加载一些数据时,我面临着一个问题,因此我在每个Fragment中调用AsyncTask来首先获取数据,然后加载到Fragment中。

我可以在Log中看到我正在从Server获取数据,但一旦我调用第二个Fragment,我就可以看到它也在调用下一个FragmentonCreateView,这就是为什么我在设置RecyclerView时遇到困难的原因。我试着用adapter3.notifyDataSetChanged();在不同的场景下调用Adapter,但没有任何帮助。

ViewPager的父Fragment

public class ViewUserProfile extends Fragment{
ViewPager ViewPager;
UserProfile_TabAdapter tabAdapter;
TabLayout tabLayout;
View view;

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.view_userprofile, container, false);
ViewPager = view.findViewById(R.id.up_Viewpager_ViewPager);
ViewPager.setOffscreenPageLimit(1);
ViewPager.setPageMargin(10);
tabAdapter=new TabAdapter(getFragmentManager(),getActivity(),Uda.getFN());
tabLayout= view.findViewById(R.id.up_Viewpager_Tab);
tabLayout.setupWithViewPager(userInfo_ViewPager);
return view;
}
}

Fragment未加载其数据:

public class UseConnectfragment extends Fragment {
RecyclerView FriendsRecycler,FollowingRecylcer,FollowerRecycler;
ArrayList<viewUserProfile_Wrapper> followersList;
ArrayList<viewUserProfile_Wrapper> friendsList;
ArrayList<viewUserProfile_Wrapper> followingList;
UserConnections_Adapter adapter1;
UserConnections_Adapter adapter2;
UserConnections_Adapter adapter3;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.userprofile_connections,container,false);
setRetainInstance(true);
FriendsRecycler=view.findViewById(R.id.userConnections_recyclerFriends);
FollowingRecylcer=view.findViewById(R.id.userConnections_recyclerFollowing);
FollowerRecycler=view.findViewById(R.id.userConnections_recyclerFollower);
FriendsRecycler.setHasFixedSize(true);
FollowingRecylcer.setHasFixedSize(true);
FollowerRecycler.setHasFixedSize(true);
FriendsRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 3));
FollowingRecylcer.setLayoutManager(new GridLayoutManager(getActivity(), 3));
FollowerRecycler.setLayoutManager(new GridLayoutManager(getActivity(), 3));
adapter1=new UserConnections_Adapter(friendsList);
adapter2=new UserConnections_Adapter(followingList);
adapter3=new UserConnections_Adapter(followersList);

return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.d(TAG,"Set User Visible Running");
if (isVisibleToUser){
Log.d(TAG,"User Connection Tab Is Visible So Call Server Now");
new GetConncetions().execute();
}
}
public class UserConnections_Adapter extends RecyclerView.Adapter<UseConnections_fragment.UserConnections_Adapter.ViewHolder> {
ArrayList<viewUserProfile_Wrapper> connectionList;
public UserConnections_Adapter(ArrayList<viewUserProfile_Wrapper> connectionList) {
this.connectionList = connectionList;
}
@Override
public UserConnections_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.userprofile_connections_singleitem,viewGroup,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(UserConnections_Adapter.ViewHolder holder, int i) {
final viewUserProfile_Wrapper wrapper=connectionList.get(i);
Log.d(TAG,"Wrapper on bind "+wrapper.getUserName()+" "+connectionList.size());
holder.userName.setText(wrapper.getUserName());
Glide.with(getActivity()).load(wrapper.getUserImage()).into(holder.userImage);
holder.userImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "User Name "+wrapper.getUserName()+" User ID "+wrapper.getID(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return connectionList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView userName;
ImageView userImage;
public ViewHolder(View itemView) {
super(itemView);
userName=itemView.findViewById(R.id.userConnection_Name);
userImage=itemView.findViewById(R.id.userConnection_friends);
}
}
}
public class GetConncetions extends AsyncTask<Void,Void,String> {
private static final String All_Connections="http://localhost/test/Android/getallon.php";
BufferedReader reader;
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
progressDialog.setTitle("Loading...");
progressDialog.show();
}
@Override
protected String doInBackground(Void... voids) {
Log.d(TAG,"Starting Do in background");
// addedInterest=new ArrayList<>();
try {

URL url=new URL(All_Connections);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
connection.setConnectTimeout(5000);
OutputStream outputStream=connection.getOutputStream();
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
writer.write(data);
writer.flush();
writer.close();
outputStream.close();
//GET INTEREST JSON FROM SERVER
Log.d(TAG,"Response Code "+connection.getResponseCode());
if (connection.getResponseCode()==200) {
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer stringBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
Log.d(TAG, "Appending JSON into String Buffer");
}
Log.d(TAG,"JSON Received "+stringBuffer);
JSONObject jsonObject=new JSONObject(stringBuffer.toString());
String callResult=jsonObject.getString("status");
Log.d(TAG,"Server Call Result "+callResult);
//Make These String out of the scope so we can access this outside if statement
String ID,Name,Image;
if (callResult.equals("SUCCESS")){
Log.d(TAG,"Server Call Is Success");
followersList=new ArrayList<>();
followingList=new ArrayList<>();
friendsList  =new ArrayList<>();
JSONArray followerDataArray=jsonObject.getJSONArray("data1");
for (int i = 0; i <followerDataArray.length() ; i++) {
String image=followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData=new viewUserProfile_Wrapper(image);
followersList.add(followerData);
}
JSONArray followingDataArray=jsonObject.getJSONArray("data2");
for (int i = 0; i <followingDataArray.length() ; i++) {
String image=followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData=new viewUserProfile_Wrapper(image);
followingList.add(followerData);
}
JSONArray friendDataArray=jsonObject.getJSONArray("data3");
for (int i = 0; i <friendDataArray.length() ; i++) {
String image=followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData=new viewUserProfile_Wrapper(image);
friendsList.add(followerData);
}
return null;
}

}
return "Success";

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String v) {
super.onPostExecute(v);
Log.d(TAG,"On Post running");
progressDialog.dismiss();
if (v!=null){
if (v.equals("Success")){
FriendsRecycler.setAdapter(adapter1);
FollowingRecylcer.setAdapter(adapter2);
FollowerRecycler.setAdapter(adapter3);
}else {
Toast.makeText(getActivity(), "Server Error.Try Again", Toast.LENGTH_SHORT).show();
}
}

}
}

}

当片段可见时调用异步任务将其添加到片段中

编辑

更改以下代码

JSONArray followingDataArray = jsonObject.getJSONArray("data2");
for (int i = 0; i < followingDataArray.length(); i++) {
String image = followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
followingList.add(followerData);
}
JSONArray friendDataArray = jsonObject.getJSONArray("data3");
for (int i = 0; i < friendDataArray.length(); i++) {
String image = followerDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
friendsList.add(followerData);
}

到这个

JSONArray followingDataArray = jsonObject.getJSONArray("data2");
for (int i = 0; i < followingDataArray.length(); i++) {
String image = followingDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
followingList.add(followerData);
}
JSONArray friendDataArray = jsonObject.getJSONArray("data3");
for (int i = 0; i < friendDataArray.length(); i++) {
String image = friendDataArray.getJSONObject(i).getString("getmyUserImage");
viewUserProfile_Wrapper followerData = new viewUserProfile_Wrapper(image);
friendsList.add(followerData);
}

如I_A_Mok所述,从中删除返回null

if (callResult.equals("SUCCESS")){......}

相关内容

  • 没有找到相关文章

最新更新