Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

v4 getFragmentManager with Activity - Incompatible types

Tags:

I have a simple activity which runs as expected.

import android.app.Activity; import android.app.FragmentManager; // import android.support.v4.app.FragmentManager; import android.os.Bundle;  public class MainActivity extends Activity {      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         // FragmentManager fm = getSupportFragmentManager(); // ActionBarActivity         FragmentManager fm = getFragmentManager(); // Activity     } } 

I then replaced

import android.app.FragmentManager; 

with

import android.support.v4.app.FragmentManager; 

so I could support my older devices.. However, this reports an error:

Incompatible types.      Required: android.support.v4.app.FragmentManager      Found: android.app.FragmentManager 

What am I doing wrong here?

The popular solution I found is to use getSupportFragmentManager() instead, but this only works for ActionBarActivites [edit - see answers] and FragmentActivities.

cannot convert from android.app.FragmentManager to android.support.v4.app.FragmentManager

The other relevant solution points to using a FragmentActivity instead, but this appears to have the same legacy problems.

The method getFragmentManager() is undefined for the type MyActivity

import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.support.v4.app.FragmentActivity;      public class MainActivity extends FragmentActivity {     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         //setContentView(R.layout.activity_main);         // FragmentManager fm = getSupportFragmentManager(); // ActionBarActivity         FragmentManager fm = getFragmentManager();     } } 

I'm pretty sure the solution to this will be on SE already, but it isn't easy (for me) to find. The minimal example should help other people with understanding it, too.

  • I'm fairly new to Android.
like image 755
David Avatar asked Aug 15 '14 04:08

David


1 Answers

In your first case if you use getSupportFragmentManager() you need to extend FragmentActivity or extend ActionBarActivity (extends FragmentActivity) as FragmentActivity is the base class for support based fragments.

In your second case you need to use getSupportFragmentManager() instead of getFragmentManager().

Fragments were introduced in honeycomb. To support fragments below honeycomb you need to use fragments from the support library in which case you need to extend FragmentActivity and use getSupportFragmentManager().

like image 111
Raghunandan Avatar answered Sep 25 '22 21:09

Raghunandan