java - 为什么我在 .setOnTouchListener() 上遇到 nullpointerException?

标签 java android nullpointerexception imageview

我正在尝试将 onTouchListener 添加到 ImageView,以便我可以获得用户从他们拍摄的图像中选择的像素值。因此,我在主 Activity 中实现了 onTouchListener,并将其用作 ImageView imageview 的 onTouchListener。

我的代码如下:

package com.andrew.omnidropper;

import java.io.File;
import java.net.URI;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class OmniDropperActivity extends Activity implements OnTouchListener {
protected static final int TAKE_PICTURE_INTENT = 0;
protected static final int SELECT_PREVIOUS_PHOTO_INTENT = 1;
/** Called when the activity is first created. */

public Button cameraButton;

public ImageView imageview;
public ImageView colordisplay;

private Bitmap bitmap;

private Uri imageUri;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    cameraButton = (Button) findViewById(R.id.camerabutton);
    imageview = (ImageView) findViewById(R.id.imageview);
    colordisplay = (ImageView) findViewById(R.id.colordisplay);

    cameraButton.setOnClickListener(clickListener);
    imageview.setOnTouchListener(this);
}
OnClickListener clickListener = new OnClickListener() {
    public void onClick(View v) {
        if(v.getId() == R.id.camerabutton){
            Intent intent = new    Intent("android.media.action.IMAGE_CAPTURE");
            File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photo));
            imageUri = Uri.fromFile(photo);
            startActivityForResult(intent, 0);
            setContentView(R.layout.selectcolorspot);
        }
        /*if(v.getId() == R.id.imagebutton){
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                    SELECT_PREVIOUS_PHOTO_INTENT);
            setContentView(R.layout.selectcolorspot);
        }(*/
        /*if(v.getId() == R.id.scratchbutton){
            setContentView(R.layout.makenewcolor);
        }*/
    }
};
private int colorPicked;

public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 0:
            if (resultCode == Activity.RESULT_OK) {
                Uri selectedImage = imageUri;
                getContentResolver().notifyChange(selectedImage, null);
                imageview = (ImageView) findViewById(R.id.imageview);
                ContentResolver cr = getContentResolver();
                try {
                    bitmap = android.provider.MediaStore.Images.Media
                        .getBitmap(cr, selectedImage);

                    imageview.setImageBitmap(bitmap);
                    imageview.setScaleType(ImageView.ScaleType.FIT_XY);
                    Toast.makeText(this, "Select an point on the image and press OK",
                                   Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                        .show();
                    Log.e("Camera", e.toString());
                }
            }
    }
}

public boolean onTouch(View v, MotionEvent e) {
    if(v.getId() == R.id.imageview){
        if(e.getAction() == MotionEvent.ACTION_DOWN && bitmap != null){
            colorPicked = bitmap.getPixel((int) e.getX(),(int) e.getY());
            setContentView(R.layout.iscolorok);
            colordisplay.setBackgroundColor(colorPicked);
        }
    }
    return false;
}
}

但是当我尝试运行它时,它崩溃了。

这是 logcat 输出:

03-28 20:43:54.613: D/AndroidRuntime(4761): Shutting down VM
03-28 20:43:54.613: W/dalvikvm(4761): threadid=1: thread exiting with uncaught exception (group=0x40018560)
03-28 20:43:54.621: E/AndroidRuntime(4761): FATAL EXCEPTION: main
03-28 20:43:54.621: E/AndroidRuntime(4761): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.andrew.omnidropper/com.andrew.omnidropper.OmniDropperActivity}: java.lang.NullPointerException
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1696)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1716)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.app.ActivityThread.access$1500(ActivityThread.java:124)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:968)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.os.Looper.loop(Looper.java:123)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.app.ActivityThread.main(ActivityThread.java:3806)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at java.lang.reflect.Method.invokeNative(Native Method)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at java.lang.reflect.Method.invoke(Method.java:507)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at dalvik.system.NativeStart.main(Native Method)
03-28 20:43:54.621: E/AndroidRuntime(4761): Caused by: java.lang.NullPointerException
03-28 20:43:54.621: E/AndroidRuntime(4761):     at com.andrew.omnidropper.OmniDropperActivity.onCreate(OmniDropperActivity.java:47)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at     android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-28 20:43:54.621: E/AndroidRuntime(4761):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1660)
03-28 20:43:54.621: E/AndroidRuntime(4761):     ... 11 more
03-28 20:43:59.519: I/Process(4761): Sending signal. PID: 4761 SIG: 9

我不认为 imageview 为 null,因为我声明了它,那么为什么它会抛出 nullPointerException?

最佳答案

您的 ImageView 可能为空。如果找不到 View ,findViewById 方法将返回 null。您确定您尝试获取的 ImageView 已在您的 main 布局中定义吗?我将使用调试器单步执行它并查看 imageview 是否为 null。

关于java - 为什么我在 .setOnTouchListener() 上遇到 nullpointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918146/

相关文章:

java - 数组索引越界错误

android - 更新 SDK 后,Pixel 启动器一直停止

java - 是否存在扩展不允许空元素的 List 的 native JAVA 集合类?

java - 如何使用ListVersionsRequest、JAVA从S3获取确切文件的信息?

java - 在 HTTP header 中发送 UTF-8 值会导致 Mojibake

Android 库项目和单元测试

android - 房间查询不起作用

java - 尝试冒泡排序时出现空指针异常

java - 什么是 NullPointerException,我该如何解决?

java - 如何在java中选择正确的变量?