Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot cast from fragment

I've a two fragments defined in the layout of my MainActivity and set by setContentView. I'd like to call some methods from these fragments, but I don't know how to acces them. Eclipse says: "Cannot cast form Fragment to ListFileFrgament".

public class MainActivity extends FragmentActivity {

    @Override
     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    FileListFragment listFragment = (FileListFragment) getFragmentManager().findFragmentById(R.id.list_fragment);  
     // cannot casr here
    PlayerFragment playerFragment = (PlayerFragment) getFragmentManager().findFragmentById(R.id.player_fragment); 
     // cannot cast here
    }


}
like image 899
XorOrNor Avatar asked Mar 08 '13 19:03

XorOrNor


2 Answers

use getSupportFragmentManager() instead of getFragmentManager()

like image 179
JafarKhQ Avatar answered Sep 27 '22 20:09

JafarKhQ


Make sure your imports match - it may be that FileListFragment / PlayerListFragment extend android.support.v4.app.Fragment while getFragmentManager().findFragmentById returns android.app.Fragment.

Use getSupportFragmentManager() to return android.support.v4.app.Fragment instances.

like image 34
ianhanniballake Avatar answered Sep 27 '22 19:09

ianhanniballake