为什么自定义控件会抛出NullPointerException?

时间:2013-04-24 16:15:18

标签: android nullpointerexception

这是activity_main.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layoutRoot"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/L1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" >

        <Button
            android:id="@+id/addButton"
            android:layout_width="74dp"
            android:layout_height="wrap_content"
            android:text="Add" />

        <EditText
            android:id="@+id/newEditText"
            android:layout_width="174dp"
            android:layout_height="wrap_content"
            android:layout_weight="3.24"
            android:ems="10"
            android:inputType="text" />
    </LinearLayout>

    <ListView
        android:id="@+id/List"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    </ListView>    
</LinearLayout>

这是名为second.xml的自定义复合控件的xml文件:

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/expandButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="0.44" 
                android:text = "One Click"/>

            <TextView
                android:id="@+id/txtView"
                android:layout_width="253dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.56"
                android:ems="10" 
                android:text = "LOL This is a sample code"/>    
        </LinearLayout>

        <RadioGroup
            android:id="@+id/ratingRadioGroup"
            android:layout_width="321dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/likeButton"
                android:layout_width="145dp"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Like" />

            <RadioButton
                android:id="@+id/dislikeButton"
                android:layout_width="147dp"
                android:layout_height="wrap_content"
                android:text="Dislike" />
        </RadioGroup>
</LinearLayout>

这是膨胀second.xml的java文件:

public class Second extends View
{
    private Button mExpandButton;
    private RadioButton mLikeButton;
    private RadioButton mDislikeButton;
    private TextView mText;
    private RadioGroup mLikeGroup;
    private ViewGroup vGroup;

    OnClickListener myClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            String s= mExpandButton.getText().toString();

            if (s.equals("One Click"))
                mExpandButton.setText("Other Click");
            else
                mExpandButton.setText("One Click");
        }
    };

    OnCheckedChangeListener myCkeckListener = new OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
            if (mLikeButton.isChecked())
                mText.setText("I Like it");

            if (mDislikeButton.isChecked())
                mText.setText("I Don't Like it");
        }
    };

    public Second(Context context) 
    {
        super(context);
        mExpandButton = (Button) this.findViewById(R.id.expandButton);
         mText = (TextView)this.findViewById(R.id.txtView);
        mLikeGroup = (RadioGroup)this.findViewById(R.id.ratingRadioGroup);
        mExpandButton.setOnClickListener(myClickListener);
        mLikeGroup.setOnCheckedChangeListener(myCkeckListener);
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.second, null);
     }
  }

最后,这是activity_main.xml的java代码:

public class MainActivity extends Activity 
{
    protected ListView mLayout;
    protected EditText mEditText;   
    protected Button mButton;   

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

        mLayout = (ListView)findViewById(R.id.List);
        mEditText = (EditText)findViewById(R.id.newEditText);
        mButton = (Button)findViewById(R.id.addButton); 

        for (int i =0; i< 4; i++)
        {
            Second sec = new Second(this);
            mLayout.addView(sec);
                setContentView(sec);
        }   
    }

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

这是生成的logcat(更新。我的包的名称是nullextry):

04-24 16:33:30.072: E/AndroidRuntime(1759): FATAL EXCEPTION: main
04-24 16:33:30.072: E/AndroidRuntime(1759): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nullextry/com.example.nullextry.MainActivity}: java.lang.NullPointerException
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.os.Looper.loop(Looper.java:137)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at java.lang.reflect.Method.invokeNative(Native Method)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at java.lang.reflect.Method.invoke(Method.java:511)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at dalvik.system.NativeStart.main(Native Method)
04-24 16:33:30.072: E/AndroidRuntime(1759): Caused by: java.lang.NullPointerException
04-24 16:33:30.072: E/AndroidRuntime(1759):     at com.example.nullextry.Second.<init>(Second.java:58)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at com.example.nullextry.MainActivity.onCreate(MainActivity.java:31)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.Activity.performCreate(Activity.java:5104)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-24 16:33:30.072: E/AndroidRuntime(1759):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-24 16:33:30.072: E/AndroidRuntime(1759):     ... 11 more
04-24 16:33:30.192: D/dalvikvm(1759): GC_CONCURRENT freed 110K, 9% free 2858K/3112K, paused 79ms+5ms, total 232ms
04-24 16:33:32.793: I/Process(1759): Sending signal. PID: 1759 SIG: 9

调试时,我发现在second.java构造函数中对second.xml进行了膨胀后抛出了这个异常,其中侦听器被分配给它们各自的控件。 我错过了什么吗? 我没有宣布什么?

愚蠢的错误:我没有宣布mExpandButton和mLikeGroup。我修复了second.java代码,(谢谢ZouZou!)。但我还得到了同样的例外(logcat已经更新)。

1 个答案:

答案 0 :(得分:1)

你忘了初始化         mExpandButton在你的构造函数中。

所以当你在做的时候:

mLikeGroup

它会抛出mExpandButton.setOnClickListener(myClickListener); mLikeGroup.setOnCheckedChangeListener(myCkeckListener);

另外不要忘记初始化

NPE

否则

mLikeButton;
mDislikeButton;
mText;

也会抛出 if (mLikeButton.isChecked()) mText.setText("I Like it"); if (mDislikeButton.isChecked()) mText.setText("I Don't Like it");

编辑:

您试图在给布局充气之前分配按钮。请尝试改为:

NullPointerExceptions