在导航抽屉中打开另一个活动时,应用程序崩溃

时间:2016-07-05 18:30:41

标签: android android-studio android-intent android-activity navigation-drawer

我有一个导航抽屉,其中的项目正在打开碎片,但当我尝试使用导航抽屉上的项目打开另一个活动时,它会崩溃并打开所述活动。这是我的代码:

MainActivity.java

package application.cedie.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.NotificationCompat;
import android.text.InputType;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import layout.BlankFragment;
import layout.DrugList;
import layout.HerbalMedicineList;
import layout.Home;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, Home.OnFragmentInteractionListener, BlankFragment.OnFragmentInteractionListener, DrugList.OnFragmentInteractionListener
, HerbalMedicineList.OnFragmentInteractionListener{


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        Fragment fragment = null;
        Class fragmentClass = null;
        fragmentClass = BlankFragment.class;
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.Fragment_container, fragment).commit();

        NavigationView nw = (NavigationView)
                findViewById(R.id.nav_view);
                nw.setItemIconTintList(null);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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

        return super.onOptionsItemSelected(item);
    }



    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
            Fragment fragment = null;
        Class fragmentClass = null;

        if (id == R.id.nav_home) {
            fragmentClass = Home.class;
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment).commit();
        } else if (id == R.id.nav_reminder) {
            fragmentClass = BlankFragment.class;
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment).commit();
        } else if (id == R.id.nav_druglist) {
            fragmentClass = DrugList.class;
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment).commit();
        } else if (id == R.id.nav_herbdrug) {
            fragmentClass = HerbalMedicineList.class;
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment).commit();
        } else if (id == R.id.nav_settings) {

        } else if (id == R.id.nav_help) {

        } else if (id == R.id.nav_about) {
            Intent newAct = new Intent(getApplicationContext(), About.class);
            startActivity(newAct);

    }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

About.java

package application.cedie.myapplication;

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

public class About extends AppCompatActivity {

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

logcat的

07-06 03:28:23.426 1760-1760/application.cedie.myapplication I/Process: Sending signal. PID: 1760 SIG: 9
07-06 03:28:30.049 3855-3876/application.cedie.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
07-06 03:28:30.049 3855-3876/application.cedie.myapplication W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-06 03:28:30.059 3855-3876/application.cedie.myapplication D/OpenGLRenderer: Enabling debug mode 0
07-06 03:28:33.043 3855-3855/application.cedie.myapplication V/Monotype: SetAppTypeFace- try to flip, app = application.cedie.myapplication
07-06 03:28:33.044 3855-3855/application.cedie.myapplication V/Monotype:     Typeface getFontPathFlipFont - systemFont = /data/data/flipfont/app_fonts/Felbridge#Felbridge
07-06 03:28:33.256 3855-3855/application.cedie.myapplication W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-06 03:28:34.020 3855-3871/application.cedie.myapplication W/art: Suspending all threads took: 6.224ms
07-06 03:28:38.532 3855-3855/application.cedie.myapplication D/AndroidRuntime: Shutting down VM
07-06 03:28:38.533 3855-3855/application.cedie.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: application.cedie.myapplication, PID: 3855
                                                                               java.lang.NullPointerException: Attempt to write to field 'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager' on a null object reference
                                                                                   at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:418)
                                                                                   at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:453)
                                                                                   at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:445)
                                                                                   at application.cedie.myapplication.MainActivity.onNavigationItemSelected(MainActivity.java:128)
                                                                                   at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:151)
                                                                                   at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
                                                                                   at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                                                                                   at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
                                                                                   at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:318)
                                                                                   at android.view.View.performClick(View.java:4756)
                                                                                   at android.view.View$PerformClick.run(View.java:19761)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5253)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:949)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:744)

片段类: Home.java

package layout;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import application.cedie.myapplication.R;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link Home.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Home#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Home extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    private OnFragmentInteractionListener mListener;

    public Home() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Home.
     */
    // TODO: Rename and change types and number of parameters
    public static Home newInstance(String param1, String param2) {
        Home fragment = new Home();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

2 个答案:

答案 0 :(得分:1)

试试这个

 Fragment fragment = null;
  if (id == R.id.nav_home) {
               fragment = Home.class;
     FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment ).comit();

 } else if (id == R.id.nav_reminder) {
    fragment = BlankFragment.class;
    FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment ).comit();
} else if (id == R.id.nav_druglist) {
    fragment = DrugList.class;
    FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment ).comit();
} else if (id == R.id.nav_herbdrug) {
    fragment = HerbalMedicineList.class;
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.Fragment_container,fragment ).commit();
} else if (id == R.id.nav_settings) {

} else if (id == R.id.nav_help) {

} else if (id == R.id.nav_about) {
    Intent newAct = new Intent(getApplicationContext(), About.class);
    startActivity(newAct);

}

答案 1 :(得分:1)

这解决了我的问题:

DATE

每当我打开一个片段时,我都会把它放进去。