Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager data lost when coming back from next screen

Tags:

I am using a ViewPager in my application and I have three tabs in it; I am using ViewPager inside a fragment. Now my problem here is, I am getting data correctly while loading the application, but when I go next page and then back to ViewPager, the data is lost and tabs are not working. Please assist me. Below is my code:

import com.devpoint.rprtjobs.R;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.design.widget.TabLayout;


public class MainActivity extends Fragment {

   // Declaring Your View and Variables

   Toolbar toolbar;
   ViewPager pager;
   SwipeViewPagerAdapter adapter;
   SlidingTabLayout tabs;
   CharSequence Titles[]={"OnGoing","UpComing","Expired"};
   int Numboftabs =3;
private View rootView;

   @SuppressWarnings("deprecation")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        try {
            rootView = inflater.inflate(R.layout.activity_main,
                    container, false);


       adapter =  new SwipeViewPagerAdapter(getActivity().getSupportFragmentManager(),Titles,Numboftabs);

       // Assigning ViewPager View and setting the adapter
       pager = (ViewPager) rootView.findViewById(R.id.pager);
       pager.setAdapter(adapter);

       // Assiging the Sliding Tab Layout View
       tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
       tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

       // Setting Custom Color for the Scroll bar indicator of the Tab View
       tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
           @Override
           public int getIndicatorColor(int position) {
               return getResources().getColor(R.color.tabsScrollColor);
           }
       });

       // Setting the ViewPager For the SlidingTabsLayout
       tabs.setViewPager(pager);

       pager.setOffscreenPageLimit(3);

       pager.setOnPageChangeListener(new OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {}
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            public void onPageSelected(int position) {

                if(position ==0)
                {
                    SwipeViewPagerAdapter.Pagename = "ListOnGoing";
                }
                else if(position ==1)
                {
                    SwipeViewPagerAdapter.Pagename = "ListUpComing"; 
                }
                else if(position ==2)
                {
                    SwipeViewPagerAdapter.Pagename = "ListExpired";
                }

                }
        });


   }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return rootView;

   }

}

Here is my adapter:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
 * Created by Edwin on 15/02/2015.
 */
public class SwipeViewPagerAdapter extends FragmentPagerAdapter {

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
    public static String Pagename="ListOnGoing";


    // Build a Constructor and assign the passed Values to appropriate values in the class
    public SwipeViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
        super(fm);

        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;

    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {

        switch (position) {
        case 0:
            //Pagename = "ListOnGoing";
            ListOnGoing mListOnGoing = new ListOnGoing();  
            return mListOnGoing;
        case 1:
            //Pagename = "ListUpComing";
            ListUpComing mListUpComing = new ListUpComing(); 
            return mListUpComing;
        case 2:
            //Pagename = "ListExpired";
            ListExpaire mListExpaire = new ListExpaire();
            return mListExpaire;
        default:
            return null;
    }

    }

    // This method return the titles for the Tabs in the Tab Strip

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}

And here is one of my fragments:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@SuppressLint("ShowToast")
public class ListOnGoing extends Fragment implements OnItemClickListener { 
    Boolean isInternetPresent = false;
    ConnectionDetector connectdetector;
    public static ListView swipelisview;
    Activity activity;
    public static ProductListAdapter productListAdapter; 
    SharedPreference sharedPreference;
    String LoggedIn;
    boolean fragmentAlreadyLoaded = false;


    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.listener = (FragmentActivity) activity;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }



    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        try {
            super.onViewCreated(view, savedInstanceState);

            swipelisview = (ListView) rootView.findViewById(R.id.list);

            View emptyView = rootView.findViewById(R.id.emptyView);
            swipelisview.setEmptyView(emptyView);

            if (savedInstanceState == null && !fragmentAlreadyLoaded) {
                fragmentAlreadyLoaded = true;
                repoObject = SplashScreen.getRepo();
                session = new SessionManager(getActivity());
                HashMap<String, String> Radious = session.getRadiousName();
                Radiosname = Radious.get(SessionManager.KEY_RadiousName);
                //LoadActivity.Status="";
                GPlaces = new GetAllGooglePlaces();
                GPlaces.GetOpportunityList("", Radiosname, getActivity());
                DisPlayOppList();
            }

            productListAdapter = new ProductListAdapter(getActivity(),
                    GetAllGooglePlaces.ArrayListOngoing);
            swipelisview.setAdapter(productListAdapter);
            productListAdapter.notifyDataSetChanged();


            session = new SessionManager(getActivity());
            HashMap<String, String> Radious = session.getRadiousName();
            Radiosname = Radious.get(SessionManager.KEY_RadiousName);


            searchedit = (EditText) rootView.findViewById(R.id.searchbox);

            Button searchbtn = (Button) rootView.findViewById(R.id.searchbtn);


            searchedit = (EditText) rootView.findViewById(R.id.searchbox);

            clearbtn = (Button) rootView.findViewById(R.id.clearbtn);

            searchedit.addTextChangedListener(watch);
            clearbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            LoadActivity.Status="";
            searchedit.setText("");
            GPlaces.GetOpportunityList("", Radiosname, getActivity());

            DisPlayOppList();
            }
            });




            searchbtn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    getActivity().runOnUiThread(new Runnable() {

                        public void run() {
                            multipleCat = "";
                            GetAllGooglePlaces.ArrayListOngoing = new CopyOnWriteArrayList<>();
                            SearchText = searchedit.getText()
                                    .toString();

                            LoadActivity.Status = "Search";

                            if (LoadActivity.isOnline) {
                                GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());

                                DisPlayOppList();
                            }

                            else {
                                List<OpportunityTable> alloffers = repoObject.roffertable
                                        .getAlloffersbySearchKeyword(SearchText);

                                if (alloffers != null) {

                                    GPlaces.FillArrayListOffline(alloffers,"OnGoing");
                                }

                            }

                        }
                    });

                }
            });



            HashMap<String, String> user = session.getLogin();
            LoggedIn = user.get(SessionManager.KEY_Login);

            if (LoggedIn == null) {
                LoggedIn = "";
            }

            connectdetector = new ConnectionDetector(getActivity());



            try {
                // Check if Internet present
                isInternetPresent = connectdetector.isConnectingToInternet();

            } catch (Exception e) {
                e.printStackTrace();            
                PostLogcatErrors ple = new PostLogcatErrors();
                ple.PostLogcatErorrs(e);
            }






            footerlayout = (LinearLayout) rootView.findViewById(R.id.footerlayout);

            footerlayout.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    swipelisview.requestDisallowInterceptTouchEvent(true);
                    return true;
                }
            });





            swipelisview.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View v,
                        final int position, long id) {

                    InputMethodManager imm = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);

                    try {
                        final DetailsViewpagerFragment mDetailsViewpagerFragment = new DetailsViewpagerFragment();
                        String url;
                        if (LoadActivity.isOnline) {

                            progresdialog = new ProgressDialog(getActivity());
                            progresdialog.setMessage(Html
                                    .fromHtml("<b>Search</b><br/>Loading Details..."));
                            progresdialog.setIndeterminate(false);
                            progresdialog.setCancelable(false);
                            progresdialog.show();

                            ListDetails product = GetAllGooglePlaces.ArrayListOngoing
                                    .get(position);
                            OpportunityID = product.getOfferID();


                            url = LoadActivity.BaseUri + "SaveUserViewedOpportunities";

                            JsonObjectRequest jsObjRequest;
                            jsObjRequest = new JsonObjectRequest(
                                    Request.Method.POST, url,
                                    getSaveViewUserParams(),
                                    new Response.Listener<JSONObject>() {

                                        @Override
                                        public void onResponse(JSONObject response) {

                                            pagename = "Userplaceslist";

                                            mDetailsViewpagerFragment
                                                    .setClickList(position);
                                            FragmentManager fragment = getFragmentManager();

                                            fragment.beginTransaction()
                                                    .replace(R.id.frame_container,
                                                            mDetailsViewpagerFragment)
                                                    .commit();

                                            LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;



                                            ModuleFragmentBackStackingClass
                                                    .AddtoStack(
                                                            mDetailsViewpagerFragment,
                                                            EnumModuleTags.SinglePlaceActivity,
                                                            getString(R.string.mainfrgment_rprt));
                                            LoadActivity.updateActionbarMenu();

                                            progresdialog.dismiss();


                                        }

                                    }, new Response.ErrorListener() {

                                        @Override
                                        public void onErrorResponse(
                                                VolleyError error) {
                                            Toast.makeText(getActivity(), "False",
                                                    Toast.LENGTH_LONG).show();  
                                            progresdialog.dismiss();
                                        }
                                    });

                            AppController.getInstance().addToRequestQueue(
                                    jsObjRequest);
                        } else { 

                            mDetailsViewpagerFragment.setClickList(position);
                            FragmentManager fragment = getFragmentManager();

                            fragment.beginTransaction()
                                    .replace(R.id.frame_container,
                                            mDetailsViewpagerFragment).commit();

                            LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
                            ModuleFragmentBackStackingClass.AddtoStack(
                                    mDetailsViewpagerFragment,
                                    EnumModuleTags.SinglePlaceActivity,
                                    getString(R.string.mainfrgment_rprt));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();            
                        PostLogcatErrors ple = new PostLogcatErrors();
                        ple.PostLogcatErorrs(e);
                    } 

                }

                private JSONObject getSaveViewUserParams() {

                    JSONObject params = new JSONObject();

                    HashMap<String, String> UserId = session.getUserID(); 
                    String UserIdVal = UserId.get(SessionManager.KEY_UserID);



                    if (!(UserIdVal == null)) {
                        UserIdVal = UserId.get(SessionManager.KEY_UserID);
                    } else {
                        UserIdVal = "0";
                    }

                    try {
                        params.put("UserId", UserIdVal);
                        params.put("OpportunityID", OpportunityID);
                        params.put("UserViewedID", 0);
                        params.put("Shortlisted", true);
                        params.put("KeyValue",  null); 
                    } catch (JSONException e) {
                        e.printStackTrace();            
                        PostLogcatErrors ple = new PostLogcatErrors();
                        ple.PostLogcatErorrs(e);
                    }

                    return params;
                }

            });

            // Click The FavoritesItem on LongPress
            swipelisview.setOnItemLongClickListener(new OnItemLongClickListener() {

                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    InputMethodManager imm;
                    imm = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);

                    try {
                        ImageView button;
                        button = (ImageView) view
                                .findViewById(R.id.fav_checkbox);

                        String tag = button.getTag().toString();
                        if (tag.equals(getString(R.string.grey_favcolor))) {
                            sharedPreference.addFavorite(activity,
                                    GetAllGooglePlaces.ArrayListOngoing.get(position));
                            button.setTag(getString(R.string.red_favcolor));
                            button.setImageResource(R.drawable.checked);
                        } else if (tag.equals(getString(R.string.red_favcolor))){
                            sharedPreference.removeFavorite(activity,
                                    GetAllGooglePlaces.ArrayListOngoing.get(position));
                            button.setTag(getString(R.string.grey_favcolor));
                            button.setImageResource(R.drawable.unchecked);
                        }

                        return true;
                    } catch (NotFoundException e) {
                        e.printStackTrace();            
                        PostLogcatErrors ple = new PostLogcatErrors();
                        ple.PostLogcatErorrs(e);
                        Toast.makeText(getActivity(), e.getMessage(),
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                    return true;
                }

            });




            // Code placed here will be executed even when the fragment comes from
            // backstack
        } catch (Exception e) {
            e.printStackTrace();            
            PostLogcatErrors ple = new PostLogcatErrors();
            ple.PostLogcatErorrs(e);
        }
    }

    // String APIkey ="AIzaSyCAekTB0o1MuSYvUb-8HTZxhlJHE8yBUfI";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            activity = getActivity();
            sharedPreference = new SharedPreference();
            //setRetainInstance(true);
        } catch (Exception e) {
            e.printStackTrace();            
            PostLogcatErrors ple = new PostLogcatErrors();
            ple.PostLogcatErorrs(e);
        }
    }

    @SuppressWarnings("static-access")
    @SuppressLint({ "CutPasteId", "ClickableViewAccessibility" })
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        try {
            //setRetainInstance(true);

            try
            {
                 Tracker t = ((Analytics) getActivity().getApplication()).getTracker(
                            TrackerName.APP_TRACKER);

            t.setScreenName("UserPlaces Listview");

            t.send(new HitBuilders.AppViewBuilder().build());
            }
            catch(Exception e)
            {
            Toast.makeText(getActivity().getApplication(), "Error"+e.getMessage(), 1).show();  
            }


             rootView = inflater.inflate(R.layout.user_places_listview, container,
                    false);

             swipelisview = (ListView) rootView.findViewById(R.id.list);

                View emptyView = rootView.findViewById(R.id.emptyView);
                swipelisview.setEmptyView(emptyView);


            return rootView;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rootView;
    }


    TextWatcher watch = new TextWatcher(){

        @Override
        public void afterTextChanged(Editable arg0) {

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
        int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence s, int a, int b, int c) {

        if(c == 0){
        clearbtn.setVisibility(View.GONE);
        }
        else {
        clearbtn.setVisibility(View.VISIBLE);
        }
        }};


    protected void LoadSearchPlaces(String searchparam) {
        try {
            if (LoadActivity.isOnline) {

                JsonArrayRequest movieReq = new JsonArrayRequest("http://192.168.2.10/RPRT.WebApi/api/RPRT/" + "SearchPlaces/"+searchparam,
                        new Response.Listener<JSONArray>() {
                                @Override
                                public void onResponse(JSONArray response) { 
                                    List<HashMap<String, String>> aList = new ArrayList<>();
                                    for (int i = 0; i < response.length(); i++) {
                                        JSONObject json_data;
                                        try {
                                            json_data = response.getJSONObject(i);
                                            HashMap<String, String> hm = new HashMap<>();
                                            hm.put("Address", json_data.getString("Address"));
                                            hm.put("City", json_data.getString("City"));
                                            hm.put("Latitude", json_data.getString("Latitude"));
                                            hm.put("Longitude", json_data.getString("Longitude"));
                                            aList.add(hm);
                                        } catch (JSONException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace(); 
                                        }

                                    }
                                    String[] from = { "Address"} ;
                                    int[] to = { R.id.tv };
                                    SimpleAdapter adapterId = new SimpleAdapter(getActivity(), aList,
                                            R.layout.user_places_dropdown_listitem, from, to);

                                    //final AutoCompleteTextView autoCompView = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView);

                                    autoCompView.setAdapter(adapterId);

                                    autoCompView.setThreshold(1);

                                    // Pname.setThreshold(1);

                                    autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                        @SuppressWarnings("unchecked")
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
                                            HashMap<String, String> hm = (HashMap<String, String>) parent
                                                    .getAdapter().getItem(position);

                                            autoCompView.setText(hm.get("Address"));
                                            SplashScreen.nwLocation.setLatitude(Double.parseDouble(hm.get("Latitude")));
                                            SplashScreen.nwLocation.setLongitude(Double.parseDouble(hm.get("Longitude")));

                                             HashMap<String, String> Radious = session.getRadiousName();
                                                final String Radiosname;
                                                Radiosname = Radious.get(SessionManager.KEY_RadiousName);

                                                multipleCat="";
                                            ProgressDialog progresdialog = new ProgressDialog(getActivity());
                                            progresdialog.setMessage(Html
                                                    .fromHtml("<b>Search</b><br/>Loading Details..."));
                                            progresdialog.setIndeterminate(false);
                                            progresdialog.setCancelable(false);
                                            //progresdialog.show();
                                            LoadActivity.Status="";
                                            GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());

                                            DisPlayOppList();

                                            searchdialog.cancel();


                                        }

                                    }); 


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

                            }

                        });

                AppController.getInstance().addToRequestQueue(movieReq);


            } 

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




    private void DisPlayOppList() {
        try {

            pdialog = new ProgressDialog(getActivity());
            pdialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Details..."));
            pdialog.setIndeterminate(false);
            pdialog.setCancelable(false);


                if(LoadActivity.Status.equals("Slidemenulist"))  
                {
                    int CategoryId = 0;
                    switch (CopyOfListOnGoing.multipleCat) {
                        case "Books":
                            CategoryId = 1;
                            break;
                        case "BeautyandFashion":
                            CategoryId = 2; 
                            break;
                        case "Electronic":
                            CategoryId = 3;
                            break;
                        case "Food":
                            CategoryId = 4;  
                            break;
                        case "HomeService":
                            CategoryId = 5;
                            break;
                        case "Jobs":
                            CategoryId = 6;
                            break;
                        case "RealEstate":
                            CategoryId = 7;
                            break;
                        case "Vehicles":
                            CategoryId = 8;
                            break;
                    }

                    List<OpportunityTable> alloffers = repoObject.roffertable
                            .getAllCatOpp(CategoryId , Radiosname); 

                    if (alloffers != null) {

                        GPlaces.FillArrayListOffline(alloffers,"OnGoing");
                    }

                } else {
                    List<OpportunityTable> alloffers = repoObject.roffertable
                            .getAlloffers(Integer.parseInt(Radiosname));

                    if (alloffers != null) {

                        GPlaces.FillArrayListOffline(alloffers,"OnGoing");
                    }
                }
        }

        catch (Exception e) {
            e.printStackTrace();            
            PostLogcatErrors ple = new PostLogcatErrors();  
            ple.PostLogcatErorrs(e);
        }
    }


    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

        multipleCat = "";
        DisPlayOppList(); 

    }


    /* @Override
      public void onResume() {
         Log.e("DEBUG", "onResume of Userplace ListView");
         super.onResume();
      }*/

      @Override
      public void onPause() {
        Log.e("DEBUG", "OnPause of Userplace ListView");
        super.onPause();
      }




}

And the remaining fragments look the same. Please help me.

like image 308
Hari krishna Avatar asked Sep 14 '15 08:09

Hari krishna


People also ask

Is ViewPager deprecated?

This function is deprecated.

When should I use ViewPager?

ViewPager in Android is a class that allows the user to flip left and right through pages of data. This class provides the functionality to flip pages in app. It is a widget found in the support library. To use it you'll have to put the element inside your XML layout file that'll contain multiple child views.

Which method returns the number of available views in ViewPager?

getAdapter(). getCount() The getAdapter() method returns the object that supplies the pages for the ViewPager.

How do I use TabLayout with ViewPager?

Tab layout are visible below toolbar with View pager, used to create swipeable views . Tabs are designed to work with fragments. Use them to swipe fragments in view pager.


2 Answers

After a little research, I found the solution to my problem.

I was originally calling getactivity().getSupportFragmentmanager(). However, the correct code is getChildFragmentManager()

like image 194
Hari krishna Avatar answered Oct 26 '22 23:10

Hari krishna


In you adapter extend FragmentStatePagerAdapter instead of FragmentPagerAdapter it will solve your problem. Let me know if you have any problem.

Reason (quoting from javadoc)

  /**
   The [android.support.v4.view.PagerAdapter] that will provide
   fragments for each of the sections. We use a
   {@link FragmentPagerAdapter} derivative, which will keep every
   loaded fragment in memory. If this becomes too memory intensive, it
   may be best to switch to a
   [android.support.v4.app.FragmentStatePagerAdapter].
  */
like image 29
Biswajit Avatar answered Oct 27 '22 00:10

Biswajit