Search code examples
androidandroid-viewpagerandroid-tabhostandroid-tabs

Android TabHost Error


i am using Android Studio and i am trying to make an TabHost with ViewPager based on this tutorial

https://www.youtube.com/watch?v=GxEi_I3tv2k

but i am having a problem and i cannot determine it.

the main_activity.xml code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.subhi.navtabs.MainActivity">


    <TabHost
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tabHost"
       >



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

            <HorizontalScrollView
                android:layout_width="match_parent"
                android:id="@+id/h_Scroll_View"
                android:layout_height="wrap_content">


                <TabWidget
                    android:id="@android:id/tabs"
                    android:fillViewport="true"
                    android:scrollbars="none"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"></TabWidget>

            </HorizontalScrollView>



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

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

and this is mainactivity class :

package com.subhi.navtabs;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TabHost;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener {

    ViewPager viewPager;
    TabHost tabHost;


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


        initViewPager();
        initTabHost();



    }

    private void initTabHost() {

        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();

        String[] tabanames = {"Tab1", "Tab2", "Tab3", "Tab4", "Tab5", "Tab6"};

        for (int i = 0; i < tabanames.length; i++) {
            TabHost.TabSpec tabSpec;
            tabSpec = tabHost.newTabSpec(tabanames[i]);
            tabSpec.setIndicator(tabanames[i]);
            tabSpec.setContent(new FakeContent(getApplicationContext()));
            tabHost.addTab(tabSpec);
        }

        tabHost.setOnTabChangedListener(this);


    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

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

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onTabChanged(String tabId) {

        int selecteditem = tabHost.getCurrentTab();
        viewPager.setCurrentItem(selecteditem);

        HorizontalScrollView horizontalScrollView = (HorizontalScrollView) findViewById(R.id.h_Scroll_View);
        View tabView = tabHost.getCurrentTabView();

        int scrollpos = tabView.getLeft()
                - (horizontalScrollView.getWidth() - tabView.getWidth()) / 2;
        horizontalScrollView.smoothScrollBy(scrollpos, 0);


    }



    public class FakeContent implements TabHost.TabContentFactory {

        Context context;

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

        @Override
        public View createTabContent(String tag) {

            View fakeview = new View(context);
            fakeview.setMinimumHeight(0);
            fakeview.setMinimumHeight(0);

            return fakeview;
        }
    }

    private void initViewPager() {

        viewPager = (ViewPager) findViewById(R.id.viewpager);

        List<Fragment> listfragment = new ArrayList<Fragment>();
        listfragment.add(new Fragment1());
        listfragment.add(new Fragment2());
        listfragment.add(new Fragment3());
        listfragment.add(new Fragment1());
        listfragment.add(new Fragment2());
        listfragment.add(new Fragment3());

        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), listfragment);
        viewPager.setAdapter(myFragmentPagerAdapter);
        viewPager.setOnPageChangeListener(this);

    }
}

and this is a code of one the fragments:

package com.subhi.navtabs;

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

/**
 * Created by subhi on 2/9/2016.
 */
public class Fragment1 extends Fragment {


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

        View v=inflater.inflate(R.layout.fragment1_layout,container,false);
        return v;
    }
}

And this is the log cat :

    02-09 08:35:36.925 2501-2501/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.subhi.navtabs, PID: 2501
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.subhi.navtabs/com.subhi.navtabs.MainActivity}: java.lang.NullPointerException
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
         at android.app.ActivityThread.access$800(ActivityThread.java:135)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:136)
         at android.app.ActivityThread.main(ActivityThread.java:5017)
         at java.lang.reflect.Method.invokeNative(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:515)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
         at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
         at com.subhi.navtabs.MainActivity.initTabHost(MainActivity.java:37)
         at com.subhi.navtabs.MainActivity.onCreate(MainActivity.java:28)
         at android.app.Activity.performCreate(Activity.java:5231)
         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
         at android.app.ActivityThread.access$800(ActivityThread.java:135) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:136) 
         at android.app.ActivityThread.main(ActivityThread.java:5017) 
         at java.lang.reflect.Method.invokeNative(Native Method) 
         at java.lang.reflect.Method.invoke(Method.java:515) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
         at dalvik.system.NativeStart.main(Native Method) 
    02-09 08:35:36.925 1268-1438/? W/ActivityManager:   Force finishing activity com.subhi.navtabs/.MainActivity
    02-09 08:35:37.145 1268-1438/? D/dalvikvm: GC_FOR_ALLOC freed 1812K, 26% free 12136K/16264K, paused 10ms, total 10ms
    02-09 08:35:37.665 1268-1283/? W/ActivityManager: Activity pause timeout for ActivityRecord{b1549268 u0 com.subhi.navtabs/.MainActivity t6 f}
    02-09 08:35:37.735 1402-1402/? W/EGL_emulation: eglSurfaceAttrib not implemented

i don't know where is the problem, if anyone can help me?!


Solution

  • tabHost (with uppercase "H") is different than tabhost.

    Your TabHost id is "@+id/tabHost" and you're using android.R.id.tabhost in findViewById() method.

    This is why findViewById() return a null object.


    To solve this, just change:

    From java code,

    tabHost = (TabHost) findViewById(android.R.id.tabhost);

    to tabHost = (TabHost) findViewById(R.id.tabhost);

    OR

    From xml, android:id="@+id/tabHost" to android:id="@android:id/tabhost"