将拾取的图像从库和相机上传到数据库,导致java.lang.NullPointerException错误

时间:2017-06-04 15:28:07

标签: android bitmap nullpointerexception

每件事情似乎都没问题但是当我点击上传到服务器时,应用程序会粉碎

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            //uploadimage function
            uploadImage();
        }
    }

     private void uploadImage() {
            final ProgressDialog loading = ProgressDialog.show(this, 
   "Uploading....","Please wait...",false,false);
          StringRequest stringRequest = new 
                    StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(increport.this, s , Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(increport.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);

            //Creating parameters
            Map<String,String> params = new Hashtable<>();

            //Adding parameters
            params.put(KEY_IMAGE, image);

            //returning parameters
            return params;
        }
    };
    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

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


 @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("Take Photo"))
                    cameraIntent();
                else if(userChoosenTask.equals("Choose from Library"))
                    galleryIntent();
            } else {
                //code for deny
            }
            break;
    }
}

private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from Library",
            "Cancel" };

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

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

            } else if (items[item].equals("Choose from Library")) {
                userChoosenTask ="Choose from Library";
                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, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, REQUEST_CAMERA);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
        if (requestCode == SELECT_FILE)
            onSelectFromGalleryResult(data);
        else if (requestCode == REQUEST_CAMERA)
            onCaptureImageResult(data);
    }

}

private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

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

这是错误

E / Volley:[207] NetworkDispatcher.run:未处理的异常java.lang.NullPointerException:尝试调用虚方法'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap $ CompressFormat,int,java.io .OutputStream)'对空对象引用           java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap $ CompressFormat,int,java.io.OutputStream)'               at com.example.mariamhp.inicrepot.increport $ override.getStringImage(increport.java:318)               在com.example.mariamhp.inicrepot.increport $ override.static $ access $ 300(increport.java:66)               at com.example.mariamhp.inicrepot.increport $ override.access $ dispatch(increport.java)               在com.example.mariamhp.inicrepot.increport.access $ 300(increport.java:0)               在com.example.mariamhp.inicrepot.increport $ 8 $ override.getParams(increport.java:297)               在com.example.mariamhp.inicrepot.increport $ 8 $ override.access $ dispatch(increport.java)               在com.example.mariamhp.inicrepot.increport $ 8.getParams(increport.java:0)               在com.android.volley.Request.getBody(Request.java:434)               在com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260)               在com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)               在com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)               在com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)               在com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

1 个答案:

答案 0 :(得分:0)

String image = getStringImage(bitmap);

bitmap未在问题中显示的代码中的任何位置定义,并且未在问题中显示的代码中分配值。显然,bitmapnull。将适当的值分配给bitmap或将其他非null值传递给getStringImage()