jobin
jobin

Reputation: 1517

Android studio Fragment TabHost

I want to display a fragmentTabHost in activity_main when a button is clicked.When I click it, it shows "unfortunately FragTabHost has stopped".Below is the code. Please help me!!

MainActivity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TestFragment fragment=new TestFragment();
                FragmentManager fragmentManager=fragment.getFragmentManager();
                FragmentTransaction transaction=fragmentManager.beginTransaction();
                transaction.replace(R.id.relative,fragment);
                transaction.commit();


            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/relative"
    tools:context=".MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="TabHost"/>

</RelativeLayout>

test_fragment

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0" />

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" />

</LinearLayout>

TestFragment

package com.example.sabudaniel61.fragtabhost;

/**
 * Created by Sabudaniel61 on 2015-09-30.
 */

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

public class TestFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        FragmentTabHost tabHost = new FragmentTabHost(getActivity());
        inflater.inflate(R.layout.test_fragment, tabHost);
        tabHost.setup(getActivity(),
                getChildFragmentManager(), R.id.realtabcontent);

        tabHost.addTab(tabHost.newTabSpec("simple")
                .setIndicator("Simple"), DummySectionFragment.class, null);
        tabHost.addTab(tabHost.newTabSpec("contacts")
                .setIndicator("Contacts"), DummySectionFragment.class, null);
        return tabHost;
    }

    /**
     * A dummy fragment representing a section of the app,
     * but that simply displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        private static int count = 0;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_section_dummy,
                    container, false);
            ((TextView) rootView.findViewById(android.R.id.text1))
                    .setText("Dummy Section " + count++);
            return rootView;
        }
    }
}

fragment_section_dummy

 <TextView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="24sp"
        android:padding="32dp"
        />

LogCat:

09-30 00:43:18.676  28335-28335/com.example.sabudaniel61.fragtabhost E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.sabudaniel61.fragtabhost, PID: 28335
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference
            at com.example.sabudaniel61.fragtabhost.MainActivity$1.onClick(MainActivity.java:24)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
09-30 00:48:19.063  28335-28335/com.example.sabudaniel61.fragtabhost I/Process﹕ Sending signal. PID: 28335 SIG: 9

Upvotes: 2

Views: 815

Answers (2)

jobin
jobin

Reputation: 1517

I have come up with a solution myself.

activity_main.xml:

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="TabHost"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

test_fragment.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<TabHost android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:background="#E91E63"
    android:layout_weight="1">
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="0" >

        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:layout_gravity="center" />
    </FrameLayout>

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:orientation="horizontal" />


</TabHost>
</LinearLayout>

fragment_section_dummy.xml:

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >
           <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@android:id/text1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:textSize="24sp"
            android:padding="32dp"

            />
        </RelativeLayout>

MainActivity:

    package com.example.sabudaniel61.fragtabhost;

    import android.os.Bundle;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v7.app.AppCompatActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.RelativeLayout;

    public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button button=(Button) findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    RelativeLayout relativeLayout=(RelativeLayout) findViewById(R.id.relative);
                    relativeLayout.removeAllViews();
                    TestFragment fragment=new TestFragment();
                    FragmentManager fragmentManager=getSupportFragmentManager();
                    FragmentTransaction transaction=fragmentManager.beginTransaction();
                    transaction.replace(R.id.relative, fragment);
                    transaction.commit();


                }
            });

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

TestFragment:

    package com.example.sabudaniel61.fragtabhost;

    /**
     * Created by Sabudaniel61 on 2015-09-30.
     */

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

    public class TestFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {

           FragmentTabHost tabHost=new FragmentTabHost(getActivity());
           View v= inflater.inflate(R.layout.test_fragment, tabHost);

            tabHost.setup(getActivity(),
                    getChildFragmentManager(), R.id.realtabcontent);

            tabHost.addTab(tabHost.newTabSpec("simple")
                    .setIndicator("Simple"), DummySectionFragment.class, null);
            tabHost.addTab(tabHost.newTabSpec("contacts")
                    .setIndicator("Contacts"), DummySectionFragment.class, null);
            return tabHost;
        }


        public static class DummySectionFragment extends Fragment {
            private static int count = 0;
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_section_dummy,
                        container, false);
                ((TextView) rootView.findViewById(android.R.id.text1))
                        .setText("Dummy Section " );
                return rootView;
            }
        }
    }

Upvotes: 0

Shahzeb
Shahzeb

Reputation: 3734

You are getting NullPointerException at Line# 24 in MainActivity.

Replace

FragmentManager fragmentManager=fragment.getFragmentManager();

with

FragmentManager fragmentManager=this.getSupportFragmentManager();

in MainActivity.

Upvotes: 1

Related Questions