user3782260
user3782260

Reputation: 111

getSupportFragmentManager cant be assigned to FragmentManager

I am writing my first app that uses fragments using a tutorial in Android Programming: Big Nerd Ranch Guide.

I created a fragment and a corresponding layout and now i want to add a fragment manager to the parent that will use it.

I wrote this:

FragmentManager fm = getSupportFragmentManager();

But android studio is giving me this error:

Error:(19, 51) error: incompatible types
required: android.app.FragmentManager
found:    android.support.v4.app.FragmentManager

I dont understand... I was under the impression that the FragmentManager can be from the support library or not depending on if you want to support pre-API 11 builds.

Was something changed?

These are my imports:

import android.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

When i change:

import android.app.FragmentManager;

to

import android.support.v4.app.FragmentManager;

I am getting an error recognizing a fragment class;

This is the relevant code:

FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);

if (fragment == null){
   fragment = new CrimeFragment();
   fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}

And the error is highlighting the line if (fragment == null){

and saying:

unknown class: 'fragment'

as well as a couple of

unexpected token

on each parenthesis of the if statement and a

unexpected identifier

on the double equals.

What is going on?

Upvotes: 3

Views: 4677

Answers (1)

Marius
Marius

Reputation: 820

Simply change import android.app.FragmentManager; to import android.support.v4.app.FragmentManager;

For you edited question: Check where you put your code and double check those multiple parentheses. I was able to reproduce your problem by putting the code out of any methods:

FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);

if (fragment == null){
    fragment = new CrimeFragment();
    fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_profile_holder, container, false);
}

Upvotes: 6

Related Questions