Problems with Fragments: Activity has been destroyed

Asked

Viewed 54 times

0

Man navigation drawer is correct, but when you click on a Drawer item, and it will replace the Fragments, the application stops, and the logcat error message says that

Activity has been destroyed

Code:

class DrawerItemClickListener extends FragmentActivity implements         ListView.OnItemClickListener {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    selectItem(position);
}

private void selectItem(int position) {

    Fragment fragment = null; 

    switch(position)
    {
    case 0:
        fragment = new DadosCadastraisDilmaFragment();
        break;
    case 1:
        fragment = new DadosCadastraisAecioFragment();
        break;
    ...
            default:
            break;
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.content_frame, fragment).commit();
}
}

public class MainActivity extends ActionBarActivity{

private String [] listaCandidatos;
private DrawerLayout drawerLayout; 
private ListView drawerList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // inicializar a lista do drawer
    listaCandidatos = getResources().getStringArray(R.array.lista_candidatos);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerList = (ListView) findViewById(R.id.left_drawer);

    // Set the adapter for the list view
    drawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item,R.id.drawerListItemTextView, listaCandidatos));
    // Set the list's click listener 
    drawerList.setOnItemClickListener(new DrawerItemClickListener());
} 

1 answer

0


The problem is that the DrawerItemClickListener inherits from FragmentActivity. And he’s doing replacements Fragment in a Activity (DrawerItemClickListener) using the FragmentManager, which was not created by ActivityManager (part of the Android framework).

The message:

Activity has been destroyed

It’s caused because that Activity was not started. So for it is destroyed.

Remove this inheritance and make the DrawerItemClickListener is declared non-static within the MainActivity.

Sort of like this:

public class MainActivity extends ActionBarActivity {

    // Restante do codigo

    public class DrawerItemClickListener implements ListView.OnItemClickListener {

        // Restante do seu código

    }
}
  • Thank you very much, It worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.