简体   繁体   中英

IllegalStateException Activity has been destroyed error android

I am working on a project which has two slider menus on left and right of the mainactivity.When the left slider opens it shows a list of four items.On clicking an item in the list i want the framelayout in the main activity to be replaced by a fragment.So i passed the integer postion of the listview to the mainactivity.The code is shown below:

The mainactivity

package com.navdrawer.demo.simple;

import com.navdrawer.SimpleSideDrawer;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    private SimpleSideDrawer mNav;
    Button btn1;
    RightFragment rf;
    ListView lv_countries;
    String[] values;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        values = new String[] { 
             "Android List View", 
                "Adapter implementation",
                "Simple List View In Android",
                "Create List View Android", 
                "Android Example", 
                "List View Source Code", 
                "List View Array Adapter", 
                "Android Example List View" 
               };
        mNav = new SimpleSideDrawer(this);

        mNav.setLeftBehindContentView(R.layout.activity_behind_left_simple);
           findViewById(R.id.leftBtn).setOnClickListener(new OnClickListener() {
            @Override 
            public void onClick(View v) {

                mNav.toggleLeftDrawer();
            }
        });


        mNav.setRightBehindContentView(R.layout.activity_behind_right_simple);
        final LayoutInflater factory = getLayoutInflater();

        final View textEntryView = factory.inflate(R.layout.activity_behind_right_simple, null);

        lv_countries =  (ListView) textEntryView.findViewById(R.id.lv_countries);
        ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,values);
        lv_countries.setAdapter(adapter);

        findViewById(R.id.rightBtn).setOnClickListener(new OnClickListener() {
            @Override 
            public void onClick(View v) { 
                //rf=new RightFragment();
                mNav.toggleRightDrawer();
            }
        });


    }
}

The leftfragment:

package com.example.facebook.slideoutmenu;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//Left Menu 

public class LeftMenuFragment extends Fragment {

    ListView lv_settings;
    String[] values;
    ArrayAdapter<String> adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.leftmenu, container, false);
        lv_settings=(ListView) view.findViewById(R.id.lv_settings);
        values=new String[]{"Dashboard","View Jobs","Support","About"};
        adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,values);
        lv_settings.setAdapter(adapter);

        lv_settings.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {


                new MainActivity().displayfragment(arg2);







            }


        });
        return view;
    }


}

I am calling the displayfragment method of the mainactivity from the leftfragment as follows: new MainActivity().displayfragment(arg2); .

But i get the following error in LOGCAT:

09-23 09:50:07.078: E/AndroidRuntime(10839): FATAL EXCEPTION: main
09-23 09:50:07.078: E/AndroidRuntime(10839): java.lang.IllegalStateException: Activity has been destroyed
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1342)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at com.example.facebook.slideoutmenu.MainActivity.displayfragment(MainActivity.java:258)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at com.example.facebook.slideoutmenu.LeftMenuFragment$1.onItemClick(LeftMenuFragment.java:43)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.widget.AdapterView.performItemClick(AdapterView.java:284)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.widget.ListView.performItemClick(ListView.java:3701)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:1970)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.os.Handler.handleCallback(Handler.java:587)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.os.Looper.loop(Looper.java:130)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at android.app.ActivityThread.main(ActivityThread.java:3689)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at java.lang.reflect.Method.invokeNative(Native Method)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at java.lang.reflect.Method.invoke(Method.java:507)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
09-23 09:50:07.078: E/AndroidRuntime(10839):    at dalvik.system.NativeStart.main(Native Method)

The error is shown at this line:

fragmentTransaction.commit();

I have seen several questions asked on the same error ,but i havent found a satsifactory answer yet.Please help.

displayfragment method:

public  void displayfragment(int position)
    {
        switch(position)
        {
        case 0:
        {

            Fragment fragment=new DashboardFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.menuPanel,fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
        }
            //MainActivity activity=new MainActivity();


            if(isExpanded)
            {
                isExpanded = false;
                // Collapse


                new CollapseAnimation(slidingPanel, panelWidth1,
                        TranslateAnimation.RELATIVE_TO_SELF, 0.75f,
                        TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f,
                        0, 0.0f);
            } 


        }
        }

Your LeftMenuFragment is creating a new MainActivity in your onItemClick. This won't work.

Android creates activities on your behalf, and it should already be running and attached to your fragment. So instead, you should use the getActivity() method provided by Fragment to retrieve your MainActivity.

I assume you've got a "displayfragment" method defined in your MainActivity? If you need to call any custom methods like that, just cast the result of getActivity() to MainActivity first like this:

MainActivity mainActivity = (MainActivity)getActivity();

if (mainActivity != null) // Make sure we are attached 
{
    mainActivity.displayFragment(arg2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM