-2

every thing seem to be ok but when i click to upload to server the app crushes

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

here is the error

E/Volley: [207] NetworkDispatcher.run: Unhandled exception java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference at com.example.mariamhp.inicrepot.increport$override.getStringImage(increport.java:318) at com.example.mariamhp.inicrepot.increport$override.static$access$300(increport.java:66) at com.example.mariamhp.inicrepot.increport$override.access$dispatch(increport.java) at com.example.mariamhp.inicrepot.increport.access$300(increport.java:0) at com.example.mariamhp.inicrepot.increport$8$override.getParams(increport.java:297) at com.example.mariamhp.inicrepot.increport$8$override.access$dispatch(increport.java) at com.example.mariamhp.inicrepot.increport$8.getParams(increport.java:0) at com.android.volley.Request.getBody(Request.java:434) at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:260) at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234) at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107) at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96) at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
moosa
  • 27
  • 4

1 Answers1

0
String image = getStringImage(bitmap);

bitmap is not defined anywhere in the code shown in your question, and it is not assigned a value in the code shown in your question. Apparently, bitmap is null. Either assign the appropriate value to bitmap or pass some other non-null value to getStringImage().

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • i figure it out... thank if (bmp != null) { bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); } – moosa Jun 05 '17 at 05:54