片段中的函数使模拟器崩溃

时间:2015-10-28 22:07:35

标签: java android android-fragments crash fragment

HTML中的函数放入onCreateView时出现错误。提前抱歉,因为我也会将我的日志放入,所以它可能会使我的帖子有点大,所以我会告诉你布局。对于大量问题,我感到很抱歉。

如果我不将函数menu1_Fragment.java放入我的片段中,代码就能完美运行。快速注意该功能基本上使我的图像在setClick()中成为一个3向按钮又名开始停止重置,当你重置时,它会弹出你准确时间的吐司

1)menu1_layout.xml

menu1_Fragment.java

2)LOGS

public class menu1_Fragment extends Fragment {
    Chronometer mChronometer;
    int loop = 0;
    double startTime;
    double millis;

    View rootview;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.menu1_layout, container, false);
        setClick();
        return rootview;
    }



    Button button;
    public void setClick() {


        mChronometer = (Chronometer) getActivity().findViewById(R.id.aChronometer);

        button = (Button) getActivity().findViewById(R.id.stopWatch);
        button.setOnClickListener(mStartListener);

        button = (Button) getActivity().findViewById(R.id.stopWatch);
        button.setOnClickListener(mStartListener);

        button = (Button) getActivity().findViewById(R.id.stopWatch);
        button.setOnClickListener(mStartListener);
    }

    View.OnClickListener mStartListener = new View.OnClickListener() {
        public void onClick(View v) {
            if (loop == 0) {
                mChronometer.setBase(SystemClock.elapsedRealtime());
                mChronometer.start();
                startTime = System.currentTimeMillis();
                loop++;
            } else if (loop == 1) {
                mChronometer.stop();
                millis = System.currentTimeMillis()-startTime;
                loop++;
            } else if (loop == 2) {
                mChronometer.setBase(SystemClock.elapsedRealtime());
                Context context = getActivity().getApplicationContext();
                CharSequence text = "Your Time is: " + (millis/1000);
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                loop = 0;
            }
        }
    };
}

3)10-28 16:52:26.552 2912-2912/app.z0nen.menu D/AndroidRuntime: Shutting down VM 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: FATAL EXCEPTION: main 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Process: app.z0nen.menu, PID: 2912 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{app.z0nen.menu/app.z0nen.slidemenu.MyActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.setClick(menu1_Fragment.java:39) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at app.z0nen.slidemenu.menu1_Fragment.onCreateView(menu1_Fragment.java:26) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Fragment.performCreateView(Fragment.java:2220) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.BackStackRecord.run(BackStackRecord.java:793) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.FragmentController.execPendingActions(FragmentController.java:325) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.Activity.performStart(Activity.java:6252) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) 10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  10-28 16:52:26.552 2912-2912/app.z0nen.menu E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  10-28 16:52:28.662 2912-2912/? I/Process: Sending signal. PID: 2912 SIG: 9

MyActivity.Java

4)public class MyActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks { /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { Fragment objFragment = null; switch (position) { case 0: objFragment = new menu1_Fragment(); break; case 1: objFragment = new menu2_Fragment(); break; } // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, objFragment) .commit(); } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_section1); break; case 2: mTitle = getString(R.string.title_section2); break; } } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.my, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @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); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_my, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MyActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } } }

Menu1_layout.xml

2 个答案:

答案 0 :(得分:2)

更改

button = (Button) getActivity().findViewById(R.id.stopWatch);

到此:

button = (Button) findViewById(R.id.stopWatch);

您的按钮位于片段的布局中,而不是活动。

修改

button设为成员变量,以便您可以从onCreateView& setClick方法:

private Button mButton;

我们需要在button方法中保存onCreateView的引用:( rootview是您片段的夸大布局)

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootview = inflater.inflate(R.layout.menu1_layout, container, false);
        mButton = rootview.findViewById(R.id.stopWatch);
        setClick();
        return rootview;
    }

并在 setClick 方法中改为:

mButton.setOnClickListener(mStartListener);

答案 1 :(得分:2)

您无法使用getActivity()中的onCreateView(),因为片段的活动尚未创建。您应该在调用getActivity()之前使用onActivityCreated(),或者更好的是,使用您膨胀的rootview进行findViewByID()来电。

此外,您正在初始化按钮三次。你应该摆脱其中两个:)