使用 recyclerview 和 Asynctask 设置 Viewpager

Posted

技术标签:

【中文标题】使用 recyclerview 和 Asynctask 设置 Viewpager【英文标题】:Setup Viewpager with recyclerview and Asynctask 【发布时间】:2018-12-18 21:06:39 【问题描述】:

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

我可以在Log 中看到我正在从Server 获取数据,但是当我调用第二个Fragment 时,我可以看到它也在调用下一个Fragment onCreateView 这就是为什么我我很难设置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();
                

            



        
    



【问题讨论】:

doInBackground里面,在3个for-loop之后,有return null。我认为它不应该在那里。希望有帮助! @I_A_Mok 感谢您的评论,但即使删除 null 后它也不起作用。 @I_A_Mok 我只注意到如果我初始化适配器onPostExecute 然后它工作。 adapter=new fetchPhoto_Adapter(); 【参考方案1】:

当片段可见时调用您的 asynctask 将其添加到您的片段中

编辑

更改以下代码

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 评论的那样,删除 return null from

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

【讨论】:

如果我设置 TAG= friends 那么 asynctask 将只设置 FriendsRecycler.setAdapter(adapter1); 这个适配器而不是其他适配器。如果我理解错了,请纠正我 对不起,我错过了阅读您的问题。你能填充所有三个 recyclerviews 吗?或者你只有'adapter3'有问题 在您的 setUserVisibleHint 中添加 'getView!=null' 检查,因为它在 onCreateView 之前被调用 在viewpager下一个片段的onCreate call before setUserVisibleHint`

以上是关于使用 recyclerview 和 Asynctask 设置 Viewpager的主要内容,如果未能解决你的问题,请参考以下文章

BaseQuickAdapter和BaseViewHolder使用 RecyclerView点击事件 RecyclerView添加子view点击事件 RecyclerView添加子view点击事

recyclerview和listview的区别

怎么导入recyclerview包

RecyclerView小结

RecyclerView详解

Android RecyclerView使用简述