66781

Android : ViewPager inside DialogFragment : Fragment does not have a view

I am trying to create an alertDialog with a pageView inside with a cancel and ok button.

The problem is when I set the adapter in the method onCreateDialog, I got:

"java.lang.IllegalStateException : Fragment does not have a view".

If I comment out this line, I don't have an exception.

I have tried also by override the method onCreateView() in the class MyDialog, the problem is the same.

Someone have an idea?

<strong>MainActivity.java</strong>

public class MainActivity extends FragmentActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); // Capture button clicks button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { MyDialog alertdFragment = new MyDialog(); alertdFragment.show(getSupportFragmentManager(), "Alert Dialog Fragment"); } }); } }

<strong>MyDialog.java</strong>

public class MyDialog extends DialogFragment implements OnTabChangeListener, OnPageChangeListener { private ViewPager viewPager; private View view; private TabHost tabHost; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private List<Fragment> getFragments(){ List<Fragment> fList = new ArrayList<Fragment>(); // TODO Put here your Fragments fList.add(DetailsFragment.newInstance(1,"S1")); fList.add(DetailsFragment.newInstance(2,"S2")); fList.add(DetailsFragment.newInstance(3,"S3")); return fList; } // Method to add a TabHost private static void AddTab(FragmentActivity fragmentActivity, TabHost tabHost, TabHost.TabSpec tabSpec) { tabSpec.setContent(new MyTabFactory(fragmentActivity)); tabHost.addTab(tabSpec); } // Manages the Tab changes, synchronizing it with Pages public void onTabChanged(String tag) { int pos = this.tabHost.getCurrentTab(); this.viewPager.setCurrentItem(pos); } // Manages the Page changes, synchronizing it with Tabs @Override public void onPageScrolled(int arg0, float arg1, int arg2) { int pos = this.viewPager.getCurrentItem(); this.tabHost.setCurrentTab(pos); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Builder builder = new Builder(getActivity()); view = getActivity().getLayoutInflater().inflate(R.layout.dialog, null); viewPager = (ViewPager) view.findViewById(R.id.viewpager); tabHost = (TabHost) view.findViewById(android.R.id.tabhost); tabHost.setup(); // TODO Put here your Tabs AddTab(getActivity(), this.tabHost, this.tabHost.newTabSpec("Tab1").setIndicator("Tab1")); AddTab(getActivity(), this.tabHost, this.tabHost.newTabSpec("Tab2").setIndicator("Tab2")); AddTab(getActivity(), this.tabHost, this.tabHost.newTabSpec("Tab3").setIndicator("Tab3")); tabHost.setOnTabChangedListener(this); // Fragments and ViewPager Initialization List<Fragment> fragments = getFragments(); viewPager.setAdapter(new FragmentAdapter(getChildFragmentManager(), fragments)); viewPager.setOnPageChangeListener(this); // Positive button builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Do something else } }); // Negative Button builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Do something else } }); builder.setView(view); return builder.create(); } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub } }

<strong>FragmentAdapter.java</strong>

public class FragmentAdapter extends FragmentPagerAdapter { private List<Fragment> fragments; public FragmentAdapter(FragmentManager fm) { super(fm); } public FragmentAdapter(FragmentManager fm, List<Fragment> fragments) { super(fm); this.fragments = fragments; } @Override public Fragment getItem(int position) { return this.fragments.get(position); } @Override public int getCount() { return this.fragments.size(); } @Override public CharSequence getPageTitle(int position) { return "Page " + position; } public int getItemPosition(Object object) { return POSITION_NONE; } }

<strong>DetailsFragment.java</strong>

public class DetailsFragment extends Fragment { // Store instance variables private String title; private int page; // newInstance constructor for creating fragment with arguments public static DetailsFragment newInstance(int page, String title) { DetailsFragment fragmentFirst = new DetailsFragment(); Bundle args = new Bundle(); args.putInt("someInt", page); args.putString("someTitle", title); fragmentFirst.setArguments(args); return fragmentFirst; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); page = getArguments().getInt("someInt", 0); title = getArguments().getString("someTitle"); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.details, container,false); TextView textView = (TextView) view.findViewById(R.id.detailsText); textView.setText(page + " -- " + title); return view; } }

<strong>activity_main.xml</strong>

<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" tools:context=".Main" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="dialog" /> </RelativeLayout>

<strong>dialog.xml</strong>

<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=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0" /> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" /> </LinearLayout> </TabHost> </RelativeLayout>

<strong>details.xml</strong>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/detailsText" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="center_horizontal|center_vertical" android:layout_marginTop="20dip" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" android:textSize="30dip" /> </LinearLayout>

<strong>Edit : Track list error</strong>

11-21 20:12:56.224: E/AndroidRuntime(2864): FATAL EXCEPTION: main 11-21 20:12:56.224: E/AndroidRuntime(2864): java.lang.IllegalStateException: Fragment does not have a view 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.Fragment$1.findViewById(Fragment.java:1443) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.view.ViewPager.populate(ViewPager.java:914) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.view.View.measure(View.java:15848) 11-21 20:12:56.224: E/AndroidRuntime(2864): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)

Answer1:

I haven't tried this, but based on the error my guess would be that you are trying to configure your pager adapter too soon. Since your code is in onCreateDialog, you haven't yet told Android about the view that will go into your dialog, and maybe it needs your view hierarchy to be in place before you work with the child fragment manager.

Try moving all the code having to do with the view pager and tab host into onResume:

@Override public void onResume() { super.onResume(); if (viewPager != null) { return; } viewPager = (ViewPager) findViewById(R.id.viewpager); tabHost = (TabHost) findViewById(android.R.id.tabhost); tabHost.setup(); // TODO Put here your Tabs AddTab(getActivity(), this.tabHost, this.tabHost.newTabSpec("Tab1").setIndicator("Tab1")); AddTab(getActivity(), this.tabHost, this.tabHost.newTabSpec("Tab2").setIndicator("Tab2")); AddTab(getActivity(), this.tabHost, this.tabHost.newTabSpec("Tab3").setIndicator("Tab3")); tabHost.setOnTabChangedListener(this); // Fragments and ViewPager Initialization List<Fragment> fragments = getFragments(); viewPager.setAdapter(new FragmentAdapter(getChildFragmentManager(), fragments)); viewPager.setOnPageChangeListener(this); }

EDIT: Hmmm. Maybe the issue is that you need to let the fragments get built earlier in the life cycle, and then call setAdapter later. Try moving all the code except the actual call to setAdapter back where you had it in onCreateDialog, including saving the FragmentAdapter in a field, and then JUST call setAdapter in your onResume:

@Override public void onResume() { super.onResume(); viewPager.setAdapter(fragmentAdapter); }

Recommend

  • how to save ViewPager Current image to sd card on button click
  • How to validate input data in a Tab on Tab Change?
  • Fragments not updating in viewpager
  • setCurrentItem of nested viewpager
  • Updating ListView show old data even after updatting with new data in ArrayAdaptor
  • Close tab programmatically TabHost
  • problems with With Fragments and ViewPager
  • getItem() calling multiple time in FragmentPagerAdapter
  • Non stop auto scroll of viewpager in android
  • Synchronizing and combining webviews together to reduce loading for files over 500kb
  • DB transaction or Java DAO's method synchronization?
  • Error 402: App packaging failed: 'Failed synchronizing resource pool'
  • how to change the image automatically in view pager when it reaches the last image it should come to
  • Subclipse- update working copy
  • Yii: how to show a field from a related table's related table?
  • Give wx.StaticBitmap a transparent background? wxpython
  • C++ how to get substring after get position of its index
  • WordPress > setting permalink option via script buggy?
  • Subclassing QGraphicsItem prevents me from being able to use itemAt() on a QGraphicsScene/View
  • Do I need to seed any random number generator before using EVP_PKEY_keygen of OpenSSL?
  • JqueryMobile Popup menu is not working
  • Ajax Loaded meta Tags
  • Get one-time binding to work for ng-if
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Counter field in MS Access, how to generate?
  • Volley JsonObjectRequest send headers in GET Request
  • Possible to stop flickering java tooltip in heavyweight mode?
  • sending/ receiving email in Java
  • How to set my toolbar fixed while scrolling android
  • Importing jscolor library in angular 2
  • Rearranging Cells in UITableView Bug & Saving Changes
  • align graphs with different xlab
  • AT Commands to Send SMS not working in Windows 8.1
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • How get height of the a view with gone visibility and height defined as wrap_content in xml?
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • apache spark aggregate function using min value
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • Sorting a 2D array using the second column C++
  • java string with new operator and a literal