Lior Lior - 4 months ago 82
Java Question

incompatible types: HomeFragment cannot be converted to Fragment in Android

I've tried to find answer in similar questions yet it didn't work. I'm working with android studio.
I'm getting an error in this part of code:

private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment =new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;

default:
break;
}

if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();

// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}


I get
error: incompatible types: HomeFragment cannot be converted to Fragment


this is the imports:

package liorsiag.lgbt;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;


and this is the class title:

public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;


No matter what I've tried I still get this error, any help?
And another thing, I've tried a lot of navigation drawer tutorials, but none of them seem to work. Can anyne link me to a good one?

Answer

This seems to be an import problem.

Make sure that your Fragment classes extend Fragment class.

If by any chance you are using import android.support.v4.app.Fragment, then you need to use getSupportFragmentManager() instead of getFragmentManager().

Hope it helps

Comments