尝试在空对象引用上调用虚拟方法'void android.widget.ImageView.setImageURI(android.net.Uri)'



这是我的活动。此活动的主要目标是

  1. 开放式摄像头
  2. 拍摄照片并保存到外部存储器
  3. 使用setImageUri将该图像加载到mImageView中

此活动包含2个按钮(mCamera、mGallery(和1个imageView(mImageView(。如果单击mCamera,则首先询问打开相机的权限。如果用户允许权限,则调用dispatchTakePictureIntent((。

package com.example.foodforpoor;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.dynamic.IFragmentWrapper;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Upload extends AppCompatActivity {
    private static final String TAG = "Upload Activity";
    public static final int CAMERA_PERMISSION_CODE = 101; //It is used to identify the particular permission
    public static final int CAMERA_REQUEST_CODE = 102;
    String currentPhotoPath;
    private Button mCamera, mGallery;
    private ImageView mImageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        mCamera = (Button) findViewById(R.id.cameraBtn);
        mGallery = (Button) findViewById(R.id.galleryBtn);
        mCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //showToast("Camera button clicked");
                askCameraPermission();
            }
        });
        mGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showToast("Gallery button clicked");
            }
        });
    }
    private void askCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
        } else{
           // openCamera();
            dispatchTakePictureIntent();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CAMERA_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //if both of these condition are true that means the user has given the permission
                // and now we should open the camera
                dispatchTakePictureIntent();
            } else{
                showToast("We need camera to use this feature");
            }
        }
    }
    private void openCamera() {
       showToast("Camera Open Request");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// a specific request to OS in order to open the default camera app
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                //File f = new File(currentPhotoPath);
                Log.d(TAG, "onActivityResult : resultcode == result ok and currentPhotoPath  = " + currentPhotoPath);
                Uri uri = Uri.parse(currentPhotoPath);
                Log.d(TAG, "onActivityResult : uri.getPath() : "+uri.getPath());
                mImageView.setImageURI(uri);
            }
        }
    }

    private File createImageFile() throws IOException{
        //Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /*prefix*/
                ".jpg",    /*suffix*/
                storageDir      /*directory*/
        );
        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        Log.d(TAG, "onCreateImageFile() : currentPhotoPath : " + currentPhotoPath);
        return image;
    }

    private void dispatchTakePictureIntent(){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Ensure that there is a camera activity to handle the intent
        Log.d(TAG, "onDispatchTakePictureIntent");
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            //Create the file where photo should go
            File photoFile = null;
            try{
                photoFile = createImageFile();
            } catch (IOException ex){
            }
            //continue only if the file was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                Log.d(TAG,"on photoFile!= null"+ photoURI.toString());
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }
    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
}
mImageView = findViewById(R.id.whatever_image_id) is missing?

相关内容

  • 没有找到相关文章

最新更新