Context in ViewPager Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Context in ViewPager without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I store information if user is logged in SharedPreferences. In my ViewPager adapter I want to check if userIsLoggedIn. Depending on that I will display different fragments. My question is: in order to get data from sharedPreferences I need a context. How do I get it from my ViewPager adapter class? Thank you.

public class ViewPageAdapter extends FragmentPagerAdapter {

private static int NUM_ITEMS = 3;
private FragmentManager mFragmentManager;

public ViewPageAdapter(@NonNull FragmentManager fm) {
    mFragmentManager = fm;

public Fragment getItem(int position) {
    switch (position){
        case 0: return new FragmentInsta();
        case 1: return new FragmentList();
        case 2: return new FragmentHostUnlogged();
            return new FragmentList();

public int getCount() {
    return NUM_ITEMS;

public int getItemPosition(@NonNull Object object) {
    if (object instanceof FragmentHostUnlogged)
        return POSITION_NONE;



You should use FragmentStatePagerAdapter . FragmentPagerAdapter is deprecated.

class ViewPageAdapter extends FragmentStatePagerAdapter {

         Context context; 

         ViewPagerAdapter(FragmentManager manager,Context c) {

Read Context from official guideline.

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system.

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), getApplicationContext());
We are here to answer your question about Context in ViewPager - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji