2

I have an app in Google play already and has no problem at all until I upgrade my Android Studio. The build.gradle has to be modified so that the project can be compiled Here is what I changed:

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile 'com.android.support:appcompat-v7:21.0.0'
    compile 'com.google.android.gms:play-services:6+'
    compile 'com.android.support:support-v4:+'
}

The only change is com.android.support:appcompat-v7:+ which is changed to com.android.support:appcompat-v7:21.0.0.

My problem is the .findViewById(R.id.tabhost) always return null so that the application crashes. Here is my layout file:

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

My java code:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;

public class MenuLeftFragment extends Fragment {
    private FragmentTabHost mFragmentTabHost;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mView = getView();
        if (mView != null) {
            mFragmentTabHost = (FragmentTabHost) mView
                    .findViewById(R.id.tabhost);

Any idea? Thanks.

Bagusflyer
  • 12,675
  • 21
  • 96
  • 179

1 Answers1

5

You should do this in onCreateView() where you should define as follows :

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.your_layout, container, false);
    mFragmentTabHost = (FragmentTabHost) v.findViewById(R.id.tabhost);
    return v;
}

If you want to keep this code, the getView() on the onActivityCreated() is wrong, if you have a view on your onCreate() you can do something like :

mView = v; 

Then in your onActivityCreated() instead of call getView() use mView

Then it should work.

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148