IllegalStateException in Fragment

时间:2015-11-11 11:40:25

标签: android android-fragments fragment illegalstateexception

I am doing an activity, which contains one fragments. When one of the button on the fragment1 is press, the fragment 1 change to fragment2 but it say IllegalStateException Activity has been destroyed

This is the code from Activity container.

public class SeleccionEjercito extends FragmentActivity implements FragmentEjercito.listener {

Context contexto;
Fragment firsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_seleccionejercito);
    // Crea una instancia de FragmentEjercito
    firsFragment = new FragmentEjercito();
    // Añadimos el fragmento al FrameLayout contenedor
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.fragment_container,firsFragment);
    ft.commit();
}

//metodo que hace la consulta a la base de datos y cambia el fragment
public void cambiarFragment()
{
    Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
            Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_menu_principal, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public void swap()
{
    FragmentSectorial secondFragement = new FragmentSectorial();
    //SeleccionEjercito s = new SeleccionEjercito();
    FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
    //ft.remove(firsFragment);
    ft.replace(R.id.fragment_container, secondFragement);
    ft.addToBackStack(null);
    ft.commit();
}

public void backSwap()
{
    swap();
}

}

This is the code from first Fragment.

public class FragmentEjercito extends Fragment {

Button test;
private static String LOGCAT = "LogsAndroid";
listener mCallBack;
Activity mActivity;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflamos la interfaz de usuario para este fragmento

    final View InputFragmentView = inflater.inflate(R.layout.fragment_ejercito, container, false);
    test = (Button) InputFragmentView.findViewById(R.id.bnTest);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallBack.backSwap();
        }
    });
    return InputFragmentView;
}

@Override
public void onAttach(Activity activity)
{
    mActivity = activity;
    super.onAttach(activity);
    mCallBack = (listener) activity;
}


@Override
public void onDetach() {
    super.onDetach();

    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

public interface listener
{
    public void backSwap();
}

}

This is second Fragment

public class FragmentSectorial extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_sectorial, container, false);
}

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);
}

i put the logcat here

11-12 03:01:36.301    3117-3117/armymovil E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Activity has been destroyed
        at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1399)
        at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
        at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
        at albertorollan.armymovil.SeleccionEjercito.swap(SeleccionEjercito.java:75)
        at albertorollan.armymovil.SeleccionEjercito.backSwap(SeleccionEjercito.java:80)
        at albertorollan.armymovil.FragmentEjercito$1.onClick(FragmentEjercito.java:38)
        at android.view.View.performClick(View.java:4240)
        at android.view.View$PerformClick.run(View.java:17721)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5103)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:0)

您很可能尝试将片段1替换为片段1本身的片段2。 请尝试将swap()方法移动到主活动中,并为片段交互添加侦听器。

答案 1 :(得分:0)

通常,您不能将片段替换为片段中的其他片段。正如多布里所说,使用听众。您需要从Activity实现的片段中获得一个接口。

在片段中创建以下字段:

listener mCallback;
activity mActivity;

在片段中创建以下方法:

@Override
        public void onAttach(Activity activity) {
            mActivity=activity;
            super.onAttach(activity);
        mCallback = (listener) activity;
        }

在片段中创建以下界面:

public interface listener {
        public void backSwap();
    }

从片段中的onCLick中删除swap()并替换为

mCallback.backSwap();

将交换方法从片段移动到seleccionEjercito。

修改活动声明以实施界面

public class SeleccionEjercito extends FragmentActivity implements fragmentEjercito.listener{  etc

最后在seleccionEjercito

中创建以下方法
public void backSwap(){  swap();}

如果不让我知道,我希望这有效。

答案 2 :(得分:0)

1)首先,您需要使用片段容器作为布局(帧,线性等)

2)而不是使用FragmentManager.replace而不是FragmentManager.add(在你的MainActivity中)

就是这样!