Search code examples
androidandroid-fragmentsillegalstateexception

java.lang.IllegalStateException: (Activity has been destroyed) in fragments


In my app I have 2 fragments: fragmentDiary and fragmentCal . I'm trying to call fragmentDiary from fragmentCal . I've made a function callFragmentDiary() for this purpose in MainActivity . So, from fragmentCal, this function,present in MainActivity is called. Then this function calls fragmentDiary from MainActivity. However I'm getting the java.lang.IllegalStateException on the following line in this function.

 ft.replace(R.id.container , fragDiary).commit();

Following is the relevant code:

In fragmentCal.java

( new MainActivity()).callFragmentDiary(date);

MainActivity

package com.example.nirvan.finaldiary;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

  FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  fragmentDiary fragDiary = new fragmentDiary();
  fragmentCal fragCal = new fragmentCal();

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

    ft.add(R.id.container,fragCal).commit();
  }

  public void callFragmentDiary(int []date){
    Bundle bundle=new Bundle();
    bundle.putInt("day",date[0]);
    bundle.putInt("month",date[1]);

    fragDiary.setArguments(bundle);
    ft.replace(R.id.container , fragDiary).commit();
  }
}

Solution

  • You instantiating a (new MainActivity). callFragmentDiary in the cast, while it should be something like ((MainActivity)getActivity()).callFragmentdiary.

    Also, it might be a good idea to get the FragmentManager inside the onCreate method, as the fragment manager might not be setup when the class is loaded/instantiated. And create the FragmentTransaction only when you are going to use it.