Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App force close on viewPager.setAdapter(adapter)

I have an application page with viewpager containing two fragments. When my activity pops up , a server request is made for loading current data and then adapter is set. But the app crashes with the following error.

Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference

While debugging, viewPager.setAdapter(adapter) showed null pointer exception. Neither my viewPager is null nor my Adapter.

I am not able to figure out why this is happening.

Please help!! Thanks in advance!!

like image 673
user2781627 Avatar asked Dec 23 '14 11:12

user2781627


People also ask

What is viewpager in Android?

Android ViewPager Tutorial and Examples. ViewPager is a Layout Manager that allows user to swipe through pages either left or right.In ViewPager each child view is a separate page (a separate tab) in the layout. ViewPager is one of the most important navigation features of android as it powers most of those swiping you see in apps.

How do I convert a viewpager adapter class for use with viewpager2?

If you currently use getPageWidth () with ViewPager to enable peeking on adjacent pages, you must instead use the clipToPadding attribute of RecyclerView as demonstrated in the sample app. In summary, to convert a ViewPager adapter class for use with ViewPager2 , you must make the following changes:

When to use fragmentstatepageradapter with viewpager2?

When ViewPager used FragmentStatePagerAdapter to page through a large or unknown number of fragment, use FragmentStateAdapter with ViewPager2. Fragment-based adapter classes inheriting from FragmentPagerAdapter or FragmentStatePagerAdapter always accept a single FragmentManager object as a constructor parameter.

What is a pager adapter?

Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page. This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs.


Video Answer


2 Answers

Found the problem.. In my fragmentPagerAdapter, getItem() was returning null for a fragment.

like image 75
user2781627 Avatar answered Oct 27 '22 01:10

user2781627


Try this code

create a class file TabOne.java

package com.example.tabfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TabOne extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_one, null);

    return rootView;
}
}

create a class file TabTwo.java

package com.example.tabfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TabTwo extends Fragment {

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

    View rootView = inflater.inflate(R.layout.tab_two, null);
    return rootView;
}

}

**create xml file tab_one.xml and tab_two.xml **

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center"
    android:text="@string/tab_2" />

</RelativeLayout>

Create a class TabFragmentPageAdapter.java

package com.example.tabfragment;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;

public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
        Bundle args) {
    super(fm);
    this.fragments = fragments;
    this.args = args;
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = fragments.get(position);
    fragment.setArguments(args);
    return fragment;
}

@Override
public int getCount() {
    return fragments.size();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}
}

Create a classs file TabFragments.java

public class TabFragments extends Fragment implements OnPageChangeListener,
    OnTabChangeListener {

public static final int TAB_LOGIN = 0;
public static final int TAB_REG = 1;

private TabHost tabHost;
private int currentTab = TAB_LOGIN;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, null);
    tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
    viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
    viewPager.setOnPageChangeListener(this);
    fragments = new ArrayList<Fragment>();
    fragments.add(new TabOne());
    fragments.add(new TabTwo());


    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
    pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
            fragments, getArguments());
    pageAdapter.notifyDataSetChanged();
    viewPager.setAdapter(pageAdapter);
    setupTabs();

}

private void setupTabs() {
    tabHost.setup();
    tabHost.addTab(newTab(R.string.tab_1));
    tabHost.addTab(newTab(R.string.tab_2));


    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {

        tabHost.getTabWidget().getChildAt(i)
                .setBackgroundColor(Color.parseColor("#304c58"));

        // tabHost.setBackgroundResource(R.drawable.tab_selector);
        final View view = tabHost.getTabWidget().getChildTabViewAt(i);
        final View textView = view.findViewById(android.R.id.title);
        ((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));

        ((TextView) textView).setSingleLine(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            tabHost.getTabWidget().getChildAt(i)
                    .findViewById(android.R.id.icon);
            tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;

        } else {

            if (view != null) {
                // reduce height of the tab
                view.getLayoutParams().height *= 0.77;

                if (textView instanceof TextView) {
                    ((TextView) textView).setGravity(Gravity.CENTER);
                    textView.getLayoutParams().height =  ViewGroup.LayoutParams.MATCH_PARENT;
                    textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
            }
        }

    }
    tabHost.setOnTabChangedListener(TabFragments.this);
    tabHost.setCurrentTab(currentTab);
}

private TabSpec newTab(int titleId) {
    TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
    tabSpec.setIndicator(getString(titleId));
    tabSpec.setContent(new TabFactory(getActivity()));
    return tabSpec;
}

@Override
public void onPageScrollStateChanged(int position) {

}

@Override
public void onPageScrolled(int position, float arg1, int arg2) {

}

@Override
public void onPageSelected(int position) {
    tabHost.setCurrentTab(position);
}

@Override
public void onTabChanged(String tabId) {
    currentTab = tabHost.getCurrentTab();
    viewPager.setCurrentItem(currentTab);
    updateTab();
}

@SuppressWarnings("unused")
private void updateTab() {
    switch (currentTab) {
    case TAB_LOGIN:
        TabOne login = (TabOne) fragments.get(currentTab);
        break;
    case TAB_REG:
        TabTwo register = (TabTwo) fragments
                .get(currentTab);
        break;
    }
}

class TabFactory implements TabContentFactory {

    private final Context context;

    public TabFactory(Context context) {
        this.context = context;
    }

    @Override
    public View createTabContent(String tag) {
        View v = new View(context);
        v.setMinimumHeight(0);
        v.setMinimumWidth(0);
        return v;
    }

}
}

Create you activity class

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

public class MainActivity extends ActionBarActivity {

Fragment fragment = null;

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

    fragment = new TabFragments();

    Log.i("fragment", "" + fragment.getId());

    if (fragment != null) {
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.frame_container, fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                .commit();
    }
}

}

Create mainactivity.xml file

 <?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.DrawerLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >  

      <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />
 </android.support.v4.widget.DrawerLayout>

create tab fragment_home.xml file

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fadingEdge="none"
        android:background="#394c58"
        android:tabStripEnabled="false" />

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</LinearLayout>

</TabHost>
like image 35
Jai Rajesh Avatar answered Oct 27 '22 00:10

Jai Rajesh