片段中的功能使模拟器崩溃 [英] Function in fragment makes emulator crash

查看:22
本文介绍了片段中的功能使模拟器崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 menu1_Fragment.javaonCreateView 中放置一个函数时发生错误.提前抱歉,因为我也会把我的日志放进去,所以这可能会使我的帖子有点大,所以我会告诉你布局.我很抱歉有很多问题.

Error occurs when I place a function inside onCreateView in menu1_Fragment.java. Sorry in advance as I will be placing my logs in as well so it might make my post a bit big so I will tell you the layout. I am new sorry for the loads of questions.

如果我不将函数 setClick() 放在我的片段中,则代码可以完美运行.快速注意该功能基本上使我在 menu1_layout.xml 中的图像成为一个 3 向按钮,即开始停止重置,当您重置时,它会弹出一个准确时间的祝酒词

The code works perfectly if I just don't put the function setClick() inside my fragment. quick note the function basically makes my image in menu1_layout.xml a 3 way button aka start stop reset where when you reset, it pops up a toast of exact time you got

1) menu1_Fragment.java

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

2) 日志

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

3) MyActivity.Java

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

}

4) Menu1_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:gravity="center_horizontal">

    <Chronometer
        android:id="@+id/aChronometer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:textColor="#111111"
        android:layout_marginTop="27dp"
        android:layout_below="@+id/stopWatch"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/stopWatch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/stopwatch2"
        android:layout_marginTop="38dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

推荐答案

你不能使用 onCreateView() 中的 getActivity() 因为片段的活动还没有被尚未创建.在调用 onActivityCreated() 之前,您不应该使用 getActivity(),或者更好的是,使用您膨胀的 rootview 来执行您的 findViewByID() 调用.

You can't use getActivity() from onCreateView() as the fragment's activity has not been created yet. You should use not use getActivity() until onActivityCreated() is called, or better yet, use the rootview you inflated to do your findViewByID() calls.

另外,您正在初始化按钮 3 次.你应该摆脱其中两个:)

Also, you are initializing your button three times. You should get rid on two of them :)

这篇关于片段中的功能使模拟器崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆