使用setOnClickListener时出错

时间:2014-09-21 17:10:18

标签: java android eclipse

使用下面的简单代码时程序崩溃,因为它在安装后自动关闭

package com.zaki.thenewboston;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    int         counter;
    Button      add,sub;        //used to reference to xml view ids
    TextView    display;        //used to reference to xml view ids


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

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

            //zaki: this is to wait the R.layout.activity_main to load first other wise the program may crash
            counter =0;
            add = (Button) findViewById(R.id.bAdd);   
           // sub = (Button) findViewById(R.id.bSub); 
            display = (TextView) findViewById(R.id.tvDisplay);     
            add.setOnClickListener(new OnClickListener() {              
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter ++;
                    display.setText("Your total is" + counter);

                }
            });

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



    }


    @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();
        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 {

        public PlaceholderFragment() {
        }

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

}

这是logcat: 我觉得有一个null返回,但为什么呢?我不知道原因。 我确定onCreateView中的问题

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

文件Activity_main.xml在

之下
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zaki.thenewboston.MainActivity"
    tools:ignore="MergeRootFrame" />

,文件fragment_main.xml在

之下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.zaki.thenewboston.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/tvDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/your_total_is" />

    <Button
     android:layout_width="240dp"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="@string/add_one"
     android:textSize="20sp"
     android:id="@+id/bAdd"
     />

    <Button
     android:layout_width="240dp"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="@string/subtract_one"
     android:textSize="20sp"
     android:id="@+id/bSub"
     />

</LinearLayout>

另请注意我改变了行

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

并且问题仍然存在

2 个答案:

答案 0 :(得分:0)

将其移至片段类

  counter =0;
            add = (Button) rootView.findViewById(R.id.bAdd);   

            display = (TextView) rootView.findViewById(R.id.tvDisplay);     
            add.setOnClickListener(new OnClickListener() {              
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter ++;
                    display.setText("Your total is" + counter);

                }
            });

答案 1 :(得分:0)

我发现问题不仅仅在于将代码移动到PlaceholderFragment,因为我得到了一个新的 我发布的编译错误

还有以下代码

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

应转换为如下

            add = (Button) rootView.findViewById (R.id.bAdd);
            sub = (Button) rootView.findViewById(R.id.bSub);
            display = (TextView) rootView.findViewById(R.id.tvDisplay);

我很欣赏对我所做的解释的评论