Java 在android中拍照后,如何修复应用程序崩溃

Java 在android中拍照后,如何修复应用程序崩溃,java,android,Java,Android,在android上拍照后,我如何修复我的应用程序崩溃?我目前正在制作一个应用程序,通过照片向街道报告,但当用户通过摄像头拍照时,我遇到了一个问题,当我按下应用程序按钮崩溃时,以下报告发生了崩溃 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activit

在android上拍照后,我如何修复我的应用程序崩溃?我目前正在制作一个应用程序,通过照片向街道报告,但当用户通过摄像头拍照时,我遇到了一个问题,当我按下应用程序按钮崩溃时,以下报告发生了崩溃

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.dbothxrpsc119.soppeng/com.dbothxrpsc119.soppeng.LaporanActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4332)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4376)
    at android.app.ActivityThread.-wrap19(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:6635)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
    at com.dbothxrpsc119.soppeng.LaporanActivity.setPic(LaporanActivity.java:262)
    at com.dbothxrpsc119.soppeng.LaporanActivity.onCaptureImageResult(LaporanActivity.java:271)
    at com.dbothxrpsc119.soppeng.LaporanActivity.onActivityResult(LaporanActivity.java:206)
    at android.app.Activity.dispatchActivityResult(Activity.java:7351)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4328)
    ... 9 more
对于reportactivity代码段,如下所示

public class LaporanActivity extends AppCompatActivity {

    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btnSelect;
    private EditText edPesanKirim;
    private Button btnUpload;
    private ImageView ivImage;
    private String userChoosenTask;
    String mCurrentPhotoPath;
    Uri photoURI;

    public static final String UPLOAD_KEY = "image";
    public static final String TAG = "Laporan";

    private Bitmap bitmap;

    private SQLiteDatabase db;
    private Cursor c;

    String pesan,nama,ktpsim,alamat,hp;
    Boolean sudahUpload = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_laporan);
        db=openOrCreateDatabase("User", Context.MODE_PRIVATE, null);

        ivImage = (ImageView) findViewById(R.id.ivImage);
        btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
        btnSelect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

        edPesanKirim = (EditText) findViewById(R.id.edPesanKirim);
        btnUpload = (Button) findViewById(R.id.btnUpload);
        btnUpload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //check jika data belum lengkap
                c = db.rawQuery("SELECT * FROM users",null);
                boolean exists = (c.getCount() > 0);
                if(exists) {
                    c.moveToFirst();
                    pesan = edPesanKirim.getText().toString();
                    nama = c.getString(1);
                    ktpsim = c.getString(2);
                    alamat = c.getString(3);
                    hp = c.getString(4);

                    if (!c.getString(0).equals("") || !c.getString(1).equals("") || c.getString(2).equals("")
                            || c.getString(3).equals("") || c.getString(4).equals("")) {
                        if (!pesan.equals("")) {
                            if (sudahUpload.equals(true)) {
                                uploadImage("gambar");
                            } else {
                                uploadImage("pesan");
                            }
                        } else {
                            Toast.makeText(LaporanActivity.this,"Silahkan isi gambar dan pesan terlebih dahulu",Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
                        startActivity(intent);
                    }
                } else {
                    Toast.makeText(LaporanActivity.this,"Silahkan Lengkapi Profil user anda terlebih dahulu",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(LaporanActivity.this, ProfileDataActivity.class);
                    startActivity(intent);
                }
                c.close();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(userChoosenTask.equals("Ambil Photo"))
                        cameraIntent();
                    else if(userChoosenTask.equals("Pilih dari Galery"))
                        galleryIntent();
                } else {
                    //code for deny
                }
                break;
        }
    }

    private void selectImage() {
        final CharSequence[] items = { "Ambil Photo", "Pilih dari Galery", "Cancel" };

        AlertDialog.Builder builder = new AlertDialog.Builder(LaporanActivity.this);
        builder.setTitle("Tambah Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result=Utility.checkPermission(LaporanActivity.this);

                if (items[item].equals("Ambil Photo")) {
                    userChoosenTask ="Ambil Photo";
                    if(result)
                        cameraIntent();

                } else if (items[item].equals("Pilih dari Galery")) {
                    userChoosenTask ="Pilih dari Galery";
                    if(result)
                        galleryIntent();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void galleryIntent()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Pilih File"),SELECT_FILE);
    }

    private void cameraIntent()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
                photoFile.delete();
            } catch (IOException ex) {
                // Error occurred while creating the File
                Log.d("Photo",ex.toString());
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.dbothxrpsc119.soppeng.fileprovider",
                        photoFile);
            startActivityForResult(intent, REQUEST_CAMERA);

            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
            else if (requestCode == REQUEST_CAMERA) {
                onCaptureImageResult();
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "DebotHaxor_" + 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
        //mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        mCurrentPhotoPath = image.getAbsolutePath();
        //mCurrentPhotoPath = image;
        return image;
    }
    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = photoURI;
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }
    private void setPic() {
        // Get the dimensions of the View
        int targetW = ivImage.getWidth();
        int targetH = ivImage.getHeight();
        //Log.d("Photo","Set Pic "+mCurrentPhotoPath);

        Bitmap real_bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap_view = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        ivImage.setImageBitmap(bitmap_view);
        Log.d("Photo","Tampilkan Foto "+ mCurrentPhotoPath);

        //resize
        Bitmap resized;
        resized = Bitmap.createScaledBitmap(bitmap_view,(int)(real_bitmap.getWidth()*0.4), (int)(real_bitmap.getHeight()*0.4), true);

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        resized.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
        bitmap = resized;
    }

    private void onCaptureImageResult() {
        galleryAddPic();
        setPic();
        sudahUpload = true;
    }

    @SuppressWarnings("deprecation")
    private void onSelectFromGalleryResult(Intent data) {

        Bitmap bm=null;
        if (data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ivImage.setImageBitmap(bm);

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
        bitmap = bm;
        sudahUpload = true;
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage(String mode){
        class UploadImage extends AsyncTask<Bitmap,Void,String> {

            ProgressDialog loading;
            RequestHandler rh = new RequestHandler();

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(LaporanActivity.this, "Kirim Pesan", "Mohon tunggu...",true,true);
                loading.setCanceledOnTouchOutside(false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();

                String msg = "";
                if (s.equals("ok")) {
                    msg = "Pesan sukses terkirim";
                    clearForm();
                } else {
                    msg = getString(R.string.api_error);
                }
                Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Bitmap... params) {
                HashMap<String,String> data = new HashMap<>();
                if (params.length > 0) {
                    Bitmap bitmap = params[0];
                    String uploadImage = getStringImage(bitmap);
                    data.put(UPLOAD_KEY, uploadImage);
                }
                data.put("pesan", pesan);
                data.put("device_id", Utility.uniqDevice(LaporanActivity.this));

                String uri = "https://"+ getString(R.string.api_url) + "/path/kirim_pesan";
                String result = rh.sendPostRequest(uri,data);
                return result;
            }
        }

        UploadImage ui = new UploadImage();
        if (mode.equals("gambar"))
            ui.execute(bitmap);
        else
            ui.execute();
    }

    private void clearForm() {
        ivImage.setImageResource(R.drawable.ic_menu_gallery);
        edPesanKirim.setText("");
        btnSelect.setFocusable(true);
    }
}
public class LaporanActivity扩展了appcompativity{
私有int请求\u摄像机=0,选择\u文件=1;
私人按钮b选择;
私人编辑文本edPesanKirim;
专用按钮btnUpload;
私有图像视图ivImage;
私有字符串userChoosenTask;
串电流光路;
Uri-photoURI;
公共静态最终字符串上传\u KEY=“image”;
公共静态最终字符串TAG=“Laporan”;
私有位图;
专用数据库数据库;
专用游标c;
字符串比桑,纳马,ktpsim,阿拉马特,惠普;
布尔值sudahUpload=false;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laporan);
db=openOrCreateDatabase(“用户”,Context.MODE_PRIVATE,null);
ivImage=(ImageView)findViewById(R.id.ivImage);
btnSelect=(按钮)findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
选择image();
}
});
edPesanKirim=(EditText)findViewById(R.id.edPesanKirim);
btnUpload=(按钮)findViewById(R.id.btnUpload);
btnUpload.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//检查jika数据,请参阅belum lengkap
c=db.rawQuery(“选择*来自用户”,空);
布尔存在=(c.getCount()>0);
如果(存在){
c、 moveToFirst();
pesan=edPesanKirim.getText().toString();
nama=c.getString(1);
ktpsim=c.getString(2);
alamat=c.getString(3);
hp=c.getString(4);
如果(!c.getString(0).equals(“”)| |!c.getString(1).equals(“”)| | c.getString(2).equals(“”)
||c.getString(3).equals(“”)| c.getString(4).equals(“”){
如果(!pesan.equals(“”){
if(sudahuload.equals(true)){
上传图像(“gambar”);
}否则{
上传图像(“pesan”);
}
}否则{
Toast.makeText(laporanacitivity.this,“Silahkan isi gambar and pesan terlebih dahulu”,Toast.LENGTH_SHORT.show();
}
}否则{
Toast.makeText(laporanacitivity.this,“Silahkan Lengkapi Profil user and a terlebih dahulu”,Toast.LENGTH_SHORT.show();
Intent Intent=新的Intent(LaporanActivity.this、ProfileDataActivity.class);
星触觉(意向);
}
}否则{
Toast.makeText(laporanacitivity.this,“Silahkan Lengkapi Profil user and a terlebih dahulu”,Toast.LENGTH_SHORT.show();
Intent Intent=新的Intent(LaporanActivity.this、ProfileDataActivity.class);
星触觉(意向);
}
c、 close();
}
});
}
@凌驾
public void onRequestPermissionsResult(int-requestCode、字符串[]权限、int[]grantResults){
开关(请求代码){
案例实用程序.MY\u权限\u请求\u读取\u外部存储:
if(grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION\u已授予){
if(userChoosenTask.equals(“Ambil Photo”))
cameraIntent();
else if(userChoosenTask.equals(“Pilih dari Galery”))
厨房内容();
}否则{
//拒绝代码
}
打破
}
}
私有void selectImage(){
最终字符序列[]项={“Ambil Photo”、“Pilih dari Galery”、“Cancel”};
AlertDialog.Builder=新建AlertDialog.Builder(LaporanActivity.this);
builder.setTitle(“Tambah照片!”);
setItems(items,新的DialogInterface.OnClickListener()对话框){
@凌驾
公共void onClick(对话框接口对话框,int项){
布尔结果=Utility.checkPermission(LaporanActivity.this);
如果(项目[item].equals(“Ambil照片”)){
userChoosenTask=“Ambil Photo”;
如果(结果)
cameraIntent();
}else if(items[item].equals(“Pilih dari Galery”)){
userChoosenTask=“Pilih dari Galery”;
如果(结果)
厨房内容();
}else if(items[item].equals(“取消”)){
dialog.dismise();
}
}
});
builder.show();
}
私人无效厨房内容()
{
意图=新意图();
intent.setType(“image/*”);
intent.setAction(intent.ACTION\u GET\u CONTENT)//
startActivityForResult(Intent.createChooser(Intent,“Pilih文件”),选择_文件);
}
私人帐篷
{
意向意向=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
//确保有摄像头活动来处理意图
if(intent.resolveActivity(getPackageManager())!=null){
//创建照片应该放在哪里的文件
文件photoFile=null;
试一试{
照片文件=
// Continue only if the File was successfully created
if (photoFile != null) {
    Uri photoURI = FileProvider.getUriForFile(this,
                        "com.dbothxrpsc119.soppeng.fileprovider",
                        photoFile);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
    startActivityForResult(intent, REQUEST_CAMERA);
}