App force close on viewPager.setAdapter(adapter)
Asked Answered
L

2

5

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!!

Legitimacy answered 23/12, 2014 at 11:8 Comment(2)
you using view pager with tab.Supercargo
yes I am using tab with viewpagerLegitimacy
L
18

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

Legitimacy answered 23/12, 2014 at 12:11 Comment(2)
Thanks for this. For the same error I had the same problem!Ministrant
what do you return in place of null.Malvin
S
1

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>
Supercargo answered 23/12, 2014 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.