0

I have activity with fragments:

for (String tab_name : tabs) {
    getActionBar().addTab(mActionBar.newTab().setText(tab_name)
                          .setTabListener(this));
}

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().add(new FirstFragment(), "TEST").commit();
fm.beginTransaction().add(new SecondFragment(), "TEST").commit();
fm.beginTransaction().add(new ThirdFragment(), "TEST").commit();

When I want to call new Activity from my SecondFragment:

Intent intent =  new Intent(App.context, SomeActivity.class);
startActivity(intent);

It crashes with this error:

03-22 00:22:19.439: E/AndroidRuntime(17438): java.lang.IllegalStateException: Fragment ... not attached to Activity

App.context is from MainActivity:

App.context = getApplicationContext();

What I can know that to attach fragment to activity, can be done by adding the fragment to fragmentManager, but it still crash. What I am wrong here?

Rendy
  • 5,572
  • 15
  • 52
  • 95

2 Answers2

1

Instead of

Intent intent =  new Intent(App.context, SomeActivity.class);
startActivity(intent);

use

Intent intent =  new Intent(getActivity(), SomeActivity.class);
startActivity(intent);

instead of using App.context use getActivty()

Fahim
  • 12,198
  • 5
  • 39
  • 57
0

As holding a context is very bad. Just use this

Intent intent =  new Intent(getActivity(), SomeActivity.class);
startActivity(intent);
Setu Kumar Basak
  • 11,460
  • 9
  • 53
  • 85
  • It returns null, although I create variable and get activity from onAttach and use that variable in my method.. – Rendy Mar 21 '15 at 18:13