当我尝试打开片段时应用崩溃

时间:2019-05-08 10:58:50

标签: android android-fragments

由于遇到了Gradle问题,我尝试与删除的其他应用程序使用相同的代码。因此,我做了一个新项目,并遵循了从Github保存的相同代码。

现在的问题是,当我从导航抽屉中单击“销售”菜单(将向您显示“销售片段”)时,应用程序崩溃了。我尝试创建一个示例活动并使用了意图,但从来没有问题,仅使用片段。

谢谢您的帮助!

我已经尝试清理并重建项目,卸载了该应用程序并再次运行,但是没有运气。

DashboardActivity.java

package com.example.devcash;

import android.content.Intent;
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.FragmentTransaction;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.widget.Toast;

public class DashboardActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    DrawerLayout drawer;
    NavigationView navigationView;
    Toolbar toolbar;

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

        ///
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = 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();
            }
        });

        drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        drawer = 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.dashboard, 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);
    }

    //switch for nav drawer menu
    private void displaySelectedScreen(int id){
        Fragment fragment = null;

        switch (id){
            case R.id.nav_dashboard:
                Toast.makeText(this, "Dashboard", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_sales:
                fragment = new SalesFragment();
                break;
            case R.id.nav_inventory:
                Toast.makeText(this, "Inventory", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_employee:
                Toast.makeText(this, "Employee", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_reports:
                Toast.makeText(this, "Reports", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_help:
                Toast.makeText(this, "Help Center", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_settings:
                Intent sample = new Intent(DashboardActivity.this, SampleActivity.class);
                startActivity(sample);
                break;
        }

        if (fragment != null){
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.flcontent, fragment);
            ft.commit();
        }

        drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

    }

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

        displaySelectedScreen(id);

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

fragment_sales.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    tools:context=".SalesFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Sales Fragment"
        android:textSize="50sp"/>


</FrameLayout>

SalesFragment.java

package com.example.devcash;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SalesFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SalesFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SalesFragment 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 SalesFragment() {
        // 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 SalesFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SalesFragment newInstance(String param1, String param2) {
        SalesFragment fragment = new SalesFragment();
        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_sales, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //
        getActivity().setTitle("Sales");
    }

    // 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);
    }
}

这是我的logcat

2019-05-08 19:07:03.348 20884-20884/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
2019-05-08 19:07:03.348 20884-20884/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
2019-05-08 19:07:03.349 20884-20884/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
2019-05-08 19:07:03.349 20884-20884/? D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
2019-05-08 19:07:03.538 20884-20884/? D/ActivityThread: add activity client record, r= ActivityRecord{de5bc93 token=android.os.BinderProxy@ecaf2fe {com.example.devcash/com.example.devcash.OwnerLoginActivity}} token= android.os.BinderProxy@ecaf2fe
2019-05-08 19:07:03.560 20884-20884/? I/HwSecImmHelper: mSecurityInputMethodService is null
2019-05-08 19:07:03.580 20884-20884/? D/OpenGLRenderer:   HWUI Binary is  enabled
2019-05-08 19:07:03.587 20884-20908/? D/OpenGLRenderer: HWUI GL Pipeline
2019-05-08 19:07:03.628 20884-20884/? I/PressGestureDetector: HiTouch restricted: AboardArea.
2019-05-08 19:07:03.645 20884-20889/? I/zygote64: Do partial code cache collection, code=28KB, data=29KB
2019-05-08 19:07:03.646 20884-20889/? I/zygote64: After code cache collection, code=28KB, data=29KB
2019-05-08 19:07:03.646 20884-20889/? I/zygote64: Increasing code cache capacity to 128KB
2019-05-08 19:07:03.722 20884-20908/? I/OpenGLRenderer: Initialized EGL, version 1.4
2019-05-08 19:07:03.723 20884-20908/? D/OpenGLRenderer: Swap behavior 2
2019-05-08 19:07:03.735 20884-20908/? D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
2019-05-08 19:07:03.751 20884-20908/? D/OpenGLRenderer:   HWUI Binary is  enabled
2019-05-08 19:07:03.884 20884-20884/? W/InputMethodManager: startInputReason = 1
2019-05-08 19:07:03.962 20884-20884/com.example.devcash W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
2019-05-08 19:07:03.968 20884-20884/com.example.devcash I/AssistStructure: Flattened final assist data: 3444 bytes, containing 1 windows, 14 views
2019-05-08 19:07:04.003 20884-20884/com.example.devcash W/InputMethodManager: startInputReason = 5
2019-05-08 19:07:04.107 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:04.107 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:04.115 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:04.115 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:04.124 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:04.156 20884-20889/com.example.devcash I/zygote64: Do partial code cache collection, code=61KB, data=57KB
2019-05-08 19:07:04.157 20884-20889/com.example.devcash I/zygote64: After code cache collection, code=61KB, data=57KB
2019-05-08 19:07:04.157 20884-20889/com.example.devcash I/zygote64: Increasing code cache capacity to 256KB
2019-05-08 19:07:04.272 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:04.272 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:07.928 20884-20884/com.example.devcash D/KeyEvent: obtain, mHwFlags=30
2019-05-08 19:07:07.990 20884-20884/com.example.devcash D/KeyEvent: obtain, mHwFlags=30
2019-05-08 19:07:09.123 20884-20884/com.example.devcash I/hwaps: JNI_OnLoad
2019-05-08 19:07:09.128 20884-20884/com.example.devcash W/Settings: mValues not put! needsGenerationTracker: true currentGeneration: -1 name: enable_navbar value: null
2019-05-08 19:07:09.183 20884-20884/com.example.devcash V/AudioManager: playSoundEffect   effectType: 0
2019-05-08 19:07:09.252 20884-20889/com.example.devcash I/zygote64: Do full code cache collection, code=119KB, data=104KB
2019-05-08 19:07:09.253 20884-20889/com.example.devcash I/zygote64: After code cache collection, code=101KB, data=63KB
2019-05-08 19:07:09.829 20884-20884/com.example.devcash V/AudioManager: playSoundEffect   effectType: 0
2019-05-08 19:07:09.906 20884-20884/com.example.devcash D/HwCust: Create obj success use class android.app.HwCustActivityImpl
2019-05-08 19:07:09.909 20884-20884/com.example.devcash D/HwCust: Create obj success use class android.app.HwCustHwWallpaperManagerImpl
2019-05-08 19:07:09.912 20884-20884/com.example.devcash V/ActivityThread: ActivityThread,callActivityOnCreate
2019-05-08 19:07:09.930 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
2019-05-08 19:07:09.931 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
2019-05-08 19:07:09.931 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
2019-05-08 19:07:09.931 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
2019-05-08 19:07:09.943 20884-20884/com.example.devcash D/HwRTBlurUtils: check blur style for HwPhoneWindow, themeResId : 0x7f100006, context : com.example.devcash.ForgotPasswordActivity@54f76ec, Nhwext : 0, get Blur : disable with , null
2019-05-08 19:07:09.944 20884-20884/com.example.devcash D/HwRTBlurUtils: check blur style for HwPhoneWindow, themeResId : 0x7f100006, context : com.example.devcash.ForgotPasswordActivity@54f76ec, Nhwext : 0, get Blur : disable with , null
2019-05-08 19:07:09.954 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
2019-05-08 19:07:09.954 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
2019-05-08 19:07:09.955 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.23, mControlPoint1y = 0.06, mControlPoint2x = 0.09, mControlPoint2y = 0.97
2019-05-08 19:07:09.955 20884-20884/com.example.devcash D/CubicBezierInterpolator: CubicBezierInterpolator  mControlPoint1x = 0.6, mControlPoint1y = 0.9, mControlPoint2x = 0.8, mControlPoint2y = 1.0
2019-05-08 19:07:09.996 20884-20884/com.example.devcash D/ActivityThread: add activity client record, r= ActivityRecord{2b209b4 token=android.os.BinderProxy@854c33e {com.example.devcash/com.example.devcash.ForgotPasswordActivity}} token= android.os.BinderProxy@854c33e
2019-05-08 19:07:10.009 20884-20908/com.example.devcash D/OpenGLRenderer:   HWUI Binary is  enabled
2019-05-08 19:07:10.042 20884-20884/com.example.devcash I/PressGestureDetector: HiTouch restricted: AboardArea.
2019-05-08 19:07:10.102 20884-20908/com.example.devcash D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000
2019-05-08 19:07:10.116 20884-20908/com.example.devcash D/OpenGLRenderer:   HWUI Binary is  enabled
2019-05-08 19:07:10.163 20884-20884/com.example.devcash W/InputMethodManager: startInputReason = 1
2019-05-08 19:07:10.207 20884-20884/com.example.devcash W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
2019-05-08 19:07:10.211 20884-20884/com.example.devcash I/AssistStructure: Flattened final assist data: 2840 bytes, containing 1 windows, 11 views
2019-05-08 19:07:10.220 20884-20908/com.example.devcash W/libEGL: EGLNativeWindowType 0x7cd9ac6010 disconnect failed
2019-05-08 19:07:10.242 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:10.242 20884-20884/com.example.devcash E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
2019-05-08 19:07:10.292 20884-20889/com.example.devcash I/zygote64: Do partial code cache collection, code=122KB, data=99KB
2019-05-08 19:07:10.292 20884-20889/com.example.devcash I/zygote64: After code cache collection, code=122KB, data=99KB
2019-05-08 19:07:10.292 20884-20889/com.example.devcash I/zygote64: Increasing code cache capacity to 512KB
2019-05-08 19:07:20.871 20884-20889/com.example.devcash I/zygote64: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()

2 个答案:

答案 0 :(得分:1)

一个显而易见的错误与您的FragmentInteractionListener有关。在您的SalesFragment中,指定以下内容:

@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");
    }
}

但是您的Activity没有实现OnFragmentInteractionListener,因此您至少会在日志中看到一个异常,其中显示“ DashboardActivity必须实现OnFragmentInteractionListener”

答案 1 :(得分:0)

您正在呼叫:

 drawer = findViewById(R.id.drawer_layout);
 drawer.closeDrawer(GravityCompat.START);

两次,一次在onNavigationItemSelected()中,一次在displaySelectedScreen()

通常,在调用抽屉之前,最好先检查抽屉的状态,如下所示:

if (drawer_layout.isDrawerOpen(Gravity.START)) {
       drawer_layout.closeDrawer(Gravity.START)
}

更新

如上所述,您的片段交互侦听器存在问题。我看到这将崩溃,因为如上所述,DashboardActivity没有实现OnFragmentInteractionListener。将DashboardActivity的类标头更新为此:

public class DashboardActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, SalesFragment.OnFragmentInteractionListener {

并按如下所示重写接口方法onFragmentInteraction(Uri uri)(在dashboardActivity中)

@Override
public void onFragmentInteraction(Uri uri) {

}