когда я изменяю фрагмент и возвращаюсь к предыдущему фрагменту, меняя его не показывая ничего - PullRequest
0 голосов
/ 30 марта 2020

У меня есть 4 фрагмента, и у каждого фрагмента есть обзор переработчика. фрагменты прикреплены к вкладкам. когда я перемещаюсь от одного фрагмента к другому и возвращаюсь к предыдущему фрагменту, не отображаются никакие данные.

Это мои файлы двух фрагментов.

недавний фрагмент. java

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
//        return inflater.inflate(R.layout.fragment_recent, container, false);



        listItems = new ArrayList<>();

        loadRecyclerViewData();


        // Inflate the layout for this fragment
        v = inflater.inflate(R.layout.fragment_recent, container, false);
        rvRecent = (RecyclerView) v.findViewById(R.id.rvRecent);

        progressBar =(ProgressBar) v.findViewById(R.id.porgress);
        rvRecent.setHasFixedSize(true);

        JobAdapter jobAdapter = new JobAdapter(listItems,getContext());

        manager = new LinearLayoutManager(getActivity());
        rvRecent.setLayoutManager(manager);


        rvRecent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
                    isScrolling = true;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                currentItems = manager.getChildCount();
                totalItems = manager.getItemCount();
                scrollOutItems = manager.findFirstVisibleItemPosition();

                if(isScrolling && (currentItems + scrollOutItems == totalItems)){
                    //fetch data
                    isScrolling = false;
                    loadMoreData();
                }

            }
        });



        return v;


    }



    //test


    private void loadRecyclerViewData() {

        final ProgressDialog progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Loading data...");
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.GET
                , URL_DATA, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                try {



                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONArray("employees");

                    if(jsonArray.length()<counter_2){

                        counter_2 = jsonArray.length();
                        //set flag for data completion
                    }
                    for(int i = counter_1; i<counter_2; i++){
                        JSONObject obj = jsonArray.getJSONObject(i);
                        ListItem item = new ListItem(
                                obj.getString("name"),
                                obj.getString("firstappearance"),
                                obj.getString("imageurl")


                        );
                        listItems.add(item);
                        counter_1 = counter_1 + 1;
                    }

                    adapter = new JobAdapter(listItems,getContext());       //check
                    rvRecent.setAdapter(adapter);


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }

    private void loadMoreData() {
        progressBar.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                StringRequest stringRequest = new StringRequest(Request.Method.GET
                        , URL_DATA, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {



                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray jsonArray = jsonObject.getJSONArray("employees");

                            if(jsonArray.length()>counter_2 * 2){
                                counter_2 = counter_2 * 2;
                            }else{
                                counter_2 = jsonArray.length();
                                //set flag for data completion
                            }

                            for(int i = counter_1; i<counter_2; i++){
                                JSONObject obj = jsonArray.getJSONObject(i);
                                ListItem item = new ListItem(
                                        obj.getString("name"),
                                        obj.getString("firstappearance"),
                                        obj.getString("imageurl")


                                );
                                listItems.add(item);
                                counter_1 = counter_1 + 1;
                            }

//                            adapter = new JobAdapter(listItems,getApplicationContext());
//                            rvJob.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            progressBar.setVisibility(View.GONE);


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

                RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
                requestQueue.add(stringRequest);


            }
        },2000);
    }

NotificationFragment. java

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



    listItems = new ArrayList<>();

    loadRecyclerViewData();


    // Inflate the layout for this fragment
    v = inflater.inflate(R.layout.fragment_notifications, container, false);
    rvNotifications = (RecyclerView) v.findViewById(R.id.rvNotifications);

    progressBar =(ProgressBar) v.findViewById(R.id.porgress);
    rvNotifications.setHasFixedSize(true);

    JobAdapter jobAdapter = new JobAdapter(listItems,getContext());

    manager = new LinearLayoutManager(getActivity());
    rvNotifications.setLayoutManager(manager);


    rvNotifications.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL){
                isScrolling = true;
            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            currentItems = manager.getChildCount();
            totalItems = manager.getItemCount();
            scrollOutItems = manager.findFirstVisibleItemPosition();

            if(isScrolling && (currentItems + scrollOutItems == totalItems)){
                //fetch data
                isScrolling = false;
                loadMoreData();
            }

        }
    });



    return v;


}

private void loadRecyclerViewData() {

    final ProgressDialog progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Loading data...");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET
            , URL_DATA, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            progressDialog.dismiss();
            try {



                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("employees");

                if(jsonArray.length()<counter_2){

                    counter_2 = jsonArray.length();
                    //set flag for data completion
                }
                for(int i = counter_1; i<counter_2; i++){
                    JSONObject obj = jsonArray.getJSONObject(i);
                    ListItem item = new ListItem(
                            obj.getString("name"),
                            obj.getString("firstappearance"),
                            obj.getString("imageurl")


                    );
                    listItems.add(item);
                    counter_1 = counter_1 + 1;
                }

                adapter = new JobAdapter(listItems,getContext());       //check
                rvNotifications.setAdapter(adapter);


            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
}

private void loadMoreData() {
    progressBar.setVisibility(View.VISIBLE);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            StringRequest stringRequest = new StringRequest(Request.Method.GET
                    , URL_DATA, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {



                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray jsonArray = jsonObject.getJSONArray("employees");

                        if(jsonArray.length()>counter_2 * 2){
                            counter_2 = counter_2 * 2;
                        }else{
                            counter_2 = jsonArray.length();
                            //set flag for data completion
                        }

                        for(int i = counter_1; i<counter_2; i++){
                            JSONObject obj = jsonArray.getJSONObject(i);
                            ListItem item = new ListItem(
                                    obj.getString("name"),
                                    obj.getString("firstappearance"),
                                    obj.getString("imageurl")


                            );
                            listItems.add(item);
                            counter_1 = counter_1 + 1;
                        }

JobAdapter (listItems, getApplicationContext ());

                        adapter.notifyDataSetChanged();
                        progressBar.setVisibility(View.GONE);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

            RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
            requestQueue.add(stringRequest);


        }
    },2000);
}

Main2Activity. java

public class Main2Activity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        tabLayout = findViewById(R.id.tabLayout_id);
        viewPager = findViewById(R.id.viewPager_id);

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        //adding fragments
        adapter.AddFragment(new RecentFragment(),"Recent");
        adapter.AddFragment(new JobsFragment(),"Jobs");
        adapter.AddFragment(new NotificationsFragment(),"Notifications");
        adapter.AddFragment(new RecentFragment(),"Results");

        //adapter setup
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.getTabAt(0).setIcon(R.drawable.ic_recent_24dp);
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_jobs_24dp);
        tabLayout.getTabAt(2).setIcon(R.drawable.ic_notifications_black_24dp);
        tabLayout.getTabAt(3).setIcon(R.drawable.ic_results_24dp);



    }
}

1 Ответ

1 голос
/ 30 марта 2020

Добавить

viewPager.setOffscreenPageLimit(3)

После

viewPager = findViewById(R.id.viewPager_id); 
...