Problems when calling a Fragment from an Activity

0

My problem is this: I have a MyLocationActivity.java that gives me the location in google maps, the example that I have to send to call that file is to call a fragment that I have declared in my MainActivity.java and what I want is to send my second activity MyLocationFragment.java (to that file I call it fragment because with the start tests to show the fragment, but change its internal code to FragmentActivity (for all content code))

  

Error: incompatible types: MyLocationFragment can not be converted to   Fragment

MainActivity.java (drawable layout)

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_mylocation) {
        MyLocationFragment myLocationFragment = new MyLocationFragment();
        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.map, myLocationFragment).commit();

    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
    
asked by Luis Hernandez 16.10.2018 в 20:58
source

2 answers

0

Hello, the problem is that you are mixing pears with apples, MyLocationFragment is a FragmentActivity, therefore, it inherits from Activity not from Fragment.

Then you try to use replace() which is used to replace Fragments but you are actually sending an Activity to it and that's why it fails.

if (id == R.id.nav_mylocation) {
   Intent intent = new Intent(context, MyLocationFragment.class);
   startActivity(intent); 
}    

I also recommend that you do a refactor / rename and put the correct name to your class, it can be complicated when the app grows and you no longer remember that your Activity is called Fragment.

    
answered by 17.10.2018 / 23:58
source
0

Apparently the problem is in the import when calling getFragmentManager() .

When you use getFragmentManager (), make sure that all the classes of your fragments (in this case your MyLocationFragment ) extend from the class android.app.Fragment .

Although if by chance you are using android.support.v4.app.Fragment , then use getSupportFragmentManager() instead.

    
answered by 17.10.2018 в 00:46