为什么On Click Listener会破坏我的Android应用程序?

时间:2014-03-14 18:47:35

标签: java android xml crash onclicklistener

所以,作为一些背景知识,我目前是一名iOS开发人员,我也希望为Android分支和开发,我终于有时间这样做了。

我一直在观看一些有关Android开发的视频教程,在课程中我们制作了一个简单的应用程序,当您单击一个按钮时,它会添加1,当您点击另一个按钮时,它会减去。

还有一个小文本视图,当点击按钮时总数的数值也会发生变化,所有这些都可以在代码中轻松识别。

但是,当我构建并运行应用程序时,它会在屏幕上显示错误,说“#34;不幸(应用程序名称)已停止。"

添加调试后,应用程序仅停止工作,并在添加第一个On Click Listener方法后显示此消息。

以下是主要的XML:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Your total is 0" 
        android:textSize="45dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:id="@+id/tvDisplay"
/>
    <Button 
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:text="Add One"
    android:layout_gravity="center"
    android:textSize="20dp"
    android:id="@+id/bAdd"
/>     

    <Button 
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    android:text="Subtract One"
    android:layout_gravity="center"
    android:textSize="20dp"
    android:id="@+id/bSub"
/>   


</LinearLayout>

以下是Manifest XML:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorial.thenewboston"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.tutorial.thenewboston.StartingPoint"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是Java:

public class StartingPoint extends ActionBarActivity {

int counter;
Button add, sub;
TextView display;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starting_point);
    counter = 0;
    add = (Button) findViewById(R.id.bAdd);
    sub = (Button) findViewById(R.id.bSub);
    display = (TextView) findViewById(R.id.tvDisplay);
    add.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            counter++;
            display.setText("Your total is " + counter);


        }
    });
    sub.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            counter--;
            display.setText("Your total is " + counter);


        }
    });

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

这是LogCat:

03-14 14:53:41.111: D/AndroidRuntime(17884): Shutting down VM
03-14 14:53:41.111: W/dalvikvm(17884): threadid=1: thread exiting with uncaught exception (group=0x41ce4ba8)
03-14 14:53:41.111: E/AndroidRuntime(17884): FATAL EXCEPTION: main
03-14 14:53:41.111: E/AndroidRuntime(17884): Process: com.tutorial.thenewboston, PID: 17884
03-14 14:53:41.111: E/AndroidRuntime(17884): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tutorial.thenewboston/com.tutorial.thenewboston.StartingPoint}: java.lang.NullPointerException
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.os.Looper.loop(Looper.java:136)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at java.lang.reflect.Method.invokeNative(Native Method)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at java.lang.reflect.Method.invoke(Method.java:515)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at dalvik.system.NativeStart.main(Native Method)
03-14 14:53:41.111: E/AndroidRuntime(17884): Caused by: java.lang.NullPointerException
03-14 14:53:41.111: E/AndroidRuntime(17884):    at com.tutorial.thenewboston.StartingPoint.onCreate(StartingPoint.java:31)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.Activity.performCreate(Activity.java:5231)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-14 14:53:41.111: E/AndroidRuntime(17884):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-14 14:53:41.111: E/AndroidRuntime(17884):    ... 11 more

控制台日志:

[2014-03-14 15:09:31 - TheNewBoston] ------------------------------
[2014-03-14 15:09:31 - TheNewBoston] Android Launch!
[2014-03-14 15:09:31 - TheNewBoston] adb is running normally.
[2014-03-14 15:09:31 - TheNewBoston] Performing com.tutorial.thenewboston.StartingPoint activity launch
[2014-03-14 15:09:31 - TheNewBoston] Automatic Target Mode: using device '015d483bce140216'
[2014-03-14 15:09:31 - TheNewBoston] Application already deployed. No need to reinstall.
[2014-03-14 15:09:31 - TheNewBoston] Starting activity com.tutorial.thenewboston.StartingPoint on device 015d483bce140216
[2014-03-14 15:09:32 - TheNewBoston] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.tutorial.thenewboston/.StartingPoint }

以下是一些更有希望的相关信息: 我在我的个人Android平板电脑而不是模拟器上测试我的应用程序,因为SIM卡很慢。 我的平板电脑是华硕Nexus 7,配备NVIDIA Tegra 3 1.20GHz 1GB RAM,32GB闪存 并正在运行Kit Kat,4.4.2

修改

我以前的java包含一个错误,它将它链接到我的主XML视图。 它应该在调用fragment_starting_point时调用activity_starting_point。

这是新代码

public class StartingPoint extends ActionBarActivity {

    int counter;
    Button add, sub;
    TextView display;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_starting_point);
        add = (Button) findViewById(R.id.bAdd);
        sub = (Button) findViewById(R.id.bSub);
        display = (TextView) findViewById(R.id.tvDisplay);
        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                counter++;
                display.setText("Your total is " + counter);


            }
        });
        sub.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter--;
                display.setText("Your total is " + counter);


            }
        });

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

然而我的问题完全相同,应用程序崩溃时使用与以前相同的消息,但它确实包含新的logcat信息:

03-14 15:25:44.621: E/FragmentManager(20269): No view found for id 0x7f05003c (com.tutorial.thenewboston:id/container) for fragment PlaceholderFragment{4247a988 #0 id=0x7f05003c}
03-14 15:25:44.621: E/FragmentManager(20269): Activity state:
03-14 15:25:44.621: D/FragmentManager(20269):   Local FragmentActivity 4245cf60 State:
03-14 15:25:44.621: D/FragmentManager(20269):     mCreated=truemResumed=false mStopped=false mReallyStopped=false
03-14 15:25:44.621: D/FragmentManager(20269):     mLoadersStarted=false
03-14 15:25:44.621: D/FragmentManager(20269):   Active Fragments in 4245e0b8:
03-14 15:25:44.621: D/FragmentManager(20269):     #0: PlaceholderFragment{4247a988 #0 id=0x7f05003c}
03-14 15:25:44.621: D/FragmentManager(20269):       mFragmentId=#7f05003c mContainerId=#7f05003c mTag=null
03-14 15:25:44.621: D/FragmentManager(20269):       mState=0 mIndex=0 mWho=android:fragment:0 mBackStackNesting=0
03-14 15:25:44.621: D/FragmentManager(20269):       mAdded=true mRemoving=false mResumed=false mFromLayout=false mInLayout=false
03-14 15:25:44.621: D/FragmentManager(20269):       mHidden=false mDetached=false mMenuVisible=true mHasMenu=false
03-14 15:25:44.621: D/FragmentManager(20269):       mRetainInstance=false mRetaining=false mUserVisibleHint=true
03-14 15:25:44.621: D/FragmentManager(20269):       mFragmentManager=FragmentManager{4245e0b8 in StartingPoint{4245cf60}}
03-14 15:25:44.621: D/FragmentManager(20269):       mActivity=com.tutorial.thenewboston.StartingPoint@4245cf60
03-14 15:25:44.621: D/FragmentManager(20269):   Added Fragments:
03-14 15:25:44.621: D/FragmentManager(20269):     #0: PlaceholderFragment{4247a988 #0 id=0x7f05003c}
03-14 15:25:44.621: D/FragmentManager(20269):   FragmentManager misc state:
03-14 15:25:44.621: D/FragmentManager(20269):     mActivity=com.tutorial.thenewboston.StartingPoint@4245cf60
03-14 15:25:44.621: D/FragmentManager(20269):     mContainer=android.support.v4.app.FragmentActivity$2@4245ea30
03-14 15:25:44.621: D/FragmentManager(20269):     mCurState=2 mStateSaved=false mDestroyed=false
03-14 15:25:44.621: D/FragmentManager(20269):   View Hierarchy:
03-14 15:25:44.621: D/FragmentManager(20269):     com.android.internal.policy.impl.PhoneWindow$DecorView{424636b0 V.E..... ... 0,0-0,0}
03-14 15:25:44.621: D/FragmentManager(20269):       com.android.internal.widget.ActionBarOverlayLayout{424646a0 V.ED.... ... 0,0-0,0 #1020313 android:id/action_bar_overlay_layout}
03-14 15:25:44.621: D/FragmentManager(20269):         android.widget.FrameLayout{42465448 V.E..... ... 0,0-0,0 #1020002 android:id/content}
03-14 15:25:44.631: D/FragmentManager(20269):           android.widget.LinearLayout{42472528 V.E..... ... 0,0-0,0}
03-14 15:25:44.631: D/FragmentManager(20269):             android.widget.TextView{42472840 V.ED.... ... 0,0-0,0 #7f05003d app:id/tvDisplay}
03-14 15:25:44.631: D/FragmentManager(20269):             android.widget.Button{42472e30 VFED..C. ... 0,0-0,0 #7f05003e app:id/bAdd}
03-14 15:25:44.631: D/FragmentManager(20269):             android.widget.Button{42473838 VFED..C. ... 0,0-0,0 #7f05003f app:id/bSub}
03-14 15:25:44.631: D/FragmentManager(20269):         com.android.internal.widget.ActionBarContainer{42465960 V.ED.... ... 0,0-0,0 #1020314 android:id/action_bar_container}
03-14 15:25:44.631: D/FragmentManager(20269):           com.android.internal.widget.ActionBarView{42465fb8 V.E..... ... 0,0-0,0 #1020315 android:id/action_bar}
03-14 15:25:44.631: D/FragmentManager(20269):             android.widget.LinearLayout{42466718 V.....C. ... 0,0-0,0}
03-14 15:25:44.631: D/FragmentManager(20269):               com.android.internal.widget.ActionBarView$HomeView{42467a90 V.E..... ... 0,0-0,0}
03-14 15:25:44.631: D/FragmentManager(20269):                 android.widget.ImageView{42467f58 G.ED.... ... 0,0-0,0 #102025a android:id/up}
03-14 15:25:44.631: D/FragmentManager(20269):                 android.widget.ImageView{42469038 V.ED.... ... 0,0-0,0 #102002c android:id/home}
03-14 15:25:44.631: D/FragmentManager(20269):               android.widget.LinearLayout{4246a3f0 G.E..... ... 0,0-0,0}
03-14 15:25:44.631: D/FragmentManager(20269):                 android.widget.TextView{4246a890 V.ED.... ... 0,0-0,0 #1020265 android:id/action_bar_title}
03-14 15:25:44.631: D/FragmentManager(20269):                 android.widget.TextView{4246b578 G.ED.... ... 0,0-0,0 #1020266 android:id/action_bar_subtitle}
03-14 15:25:44.631: D/FragmentManager(20269):           com.android.internal.widget.ActionBarContextView{4246bc60 G.E..... ... 0,0-0,0 #1020316 android:id/action_context_bar}
03-14 15:25:44.631: D/FragmentManager(20269):         com.android.internal.widget.ActionBarContainer{4246c248 G.ED.... ... 0,0-0,0 #1020317 android:id/split_action_bar}
03-14 15:25:44.631: D/AndroidRuntime(20269): Shutting down VM
03-14 15:25:44.631: W/dalvikvm(20269): threadid=1: thread exiting with uncaught exception (group=0x41ce4ba8)
03-14 15:25:44.631: E/AndroidRuntime(20269): FATAL EXCEPTION: main
03-14 15:25:44.631: E/AndroidRuntime(20269): Process: com.tutorial.thenewboston, PID: 20269
03-14 15:25:44.631: E/AndroidRuntime(20269): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tutorial.thenewboston/com.tutorial.thenewboston.StartingPoint}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.tutorial.thenewboston:id/container) for fragment PlaceholderFragment{4247a988 #0 id=0x7f05003c}
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.os.Looper.loop(Looper.java:136)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at java.lang.reflect.Method.invokeNative(Native Method)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at java.lang.reflect.Method.invoke(Method.java:515)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at dalvik.system.NativeStart.main(Native Method)
03-14 15:25:44.631: E/AndroidRuntime(20269): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.tutorial.thenewboston:id/container) for fragment PlaceholderFragment{4247a988 #0 id=0x7f05003c}
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.Activity.performStart(Activity.java:5241)
03-14 15:25:44.631: E/AndroidRuntime(20269):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
03-14 15:25:44.631: E/AndroidRuntime(20269):    ... 11 more

2 个答案:

答案 0 :(得分:4)

编辑:

我刚刚观看了tutoiral:

您正在设置错误的布局文件:

setContentView(R.layout.activity_starting_point);

你应该设置:

setContentView(R.layout.main);

假设您在问题中所说的内容是正确的,并且您发布的XML代码确实属于&#34; main.xml&#34;。这就是你获得NullPointerException的原因。您尝试引用的视图(TextView,按钮,...)不在您设置为内容视图的布局文件中。

答案 1 :(得分:0)

试试这个:

add = (Button) findViewById(R.id.bAdd);
        sub = (Button) findViewById(R.id.bSub);
        display = (TextView) findViewById(R.id.tvDisplay);
        add.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                counter++;
                display.setText("Your total is " + counter);


            }
        });
        sub.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter--;
                display.setText("Your total is " + counter);


            }
        });

的问候。 何