空指针异常与视图中的基本按钮

时间:2011-07-16 09:35:53

标签: java android button nullpointerexception

我只做最简单的事情。我有一个带有2个按钮和ImageView的布局,当我通过id找到它时,我得到NullPointerException

<?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"
android:weightSum="1">
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content"    android:layout_height="wrap_content"></Button>
<Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<ImageView android:layout_height="wrap_content" android:id="@+id/imageView1" android:layout_width="76dp" android:layout_weight="0.12"></ImageView>
</LinearLayout>

OnCreate中:

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        one = (Button) findViewById(R.id.button1);
        two = (Button) findViewById(R.id.button2);
        image = (ImageView)findViewById(R.id.imageView1);

        one.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
            }
        });

        two.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, 2);  
            }
        });

    } 

1 个答案:

答案 0 :(得分:-1)

检查你的代码,我没有看到会抛出NPE的明显逻辑。也许它是在未发布的代码中。 我们可以通过以下命令检查日志以查看抛出异常的行: adb logcat