在Android教程的开始步骤中获取NullPointerException

时间:2014-04-01 00:06:55

标签: android eclipse nullpointerexception

我是初学者尝试使用Android。我已经掌握了几个教程,但无法完成所有这些教程的第一步。一旦我尝试向按钮添加监听器,我就会在第一步中获得NullPointerExceptions。

例如在Lynda android初学者教程中,前两个编码步骤如下:

1在主要活动中添加一个按钮。

Button b = (Button) findViewById(R.id.button1);

运行良好

2为按钮添加一个监听器

b.setOnClickListener(new OnClickListener() {

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

        }
    });

我收到NullPointerException错误

所有代码和错误都在下面。在上面的代码之外,我创建Android应用程序项目时默认创建了所有其他代码。

Main.java:

package com.example.lyndatutlearnactivites;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
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.os.Build;

public class Main extends ActionBarActivity {

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

        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

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

            }
        });

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

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

}

R.java包含按钮引用:

  public static final class id {
    ....
        public static final int button1=0x7f05003d;
    ....
    }

错误:

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

第24行是:

b.setOnClickListener(new OnClickListener() {

activity_mail.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.example.lyndatutlearnactivites.Main"
    tools:ignore="MergeRootFrame" />

还有一个名为fragment_main.xml的文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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.example.lyndatutlearnactivites.Main$PlaceholderFragment" >

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Button" />

</RelativeLayout>

这些教程建立在API级别10上,而我的ADT eclipse建立在第19级,所以我不知道这是否有所作为。在级别19添加的所有额外代码都令人困惑。 导致错误的原因是什么?

2 个答案:

答案 0 :(得分:2)

您的activity_main布局中不包含Button,其ID为R.id.button1,表示该行

    Button b = (Button) findViewById(R.id.button1);

将返回null,因此下一行将产生NullPointerException。

如果您尝试访问片段中的Button,请先从PlaceholderFragment访问,或在附加片段后致电findViewById(R.id.button1);

答案 1 :(得分:2)

调用onCreate活动时,PlaceholderFragment未附加到活动。这就是Button b为空的原因。

  1. 您可以初始化PlaceholderFragment中的按钮,也可以设置setOnClickListener。
  2. 您可以在activity_main.xml中添加button1并初始化活动内部的按钮&lt;创建