0

I am trying to resolve this issue for two days but still, I am not able to figure out why I am getting a NullPointException.

I have tried changing the parameters of the model class but this couldn't help.

//call the task api
    private void taskuploadArt(String name,String width,String height,String year, String technique, String price,String contact)
    {
        String currency_code = currency.getText().toString().trim();
        String tags = painting_tags.getText().toString().trim();
        String info = painting_story.getText().toString().trim();
        String wishtosell;
        if(wisht_to_sell)
        {
            wishtosell="1";
            //Toast.makeText(this, "Done here", Toast.LENGTH_SHORT).show();
        }
        else
        {
           wishtosell="0";
        }

        String sellprints;
        if(sell_prints)
        {
         sellprints="1";
        }
        else {
            sellprints="0";
        }

        String createdby_me;
        if(createdbyme)
        {
            createdby_me="1";
        }
        else
        {
            createdby_me="0";
        }


         UploadArtApiInterface uploadartapiInterface;
        //API call
        uploadartapiInterface = ApiClient.getApiClient().create(UploadArtApiInterface.class);
        Call<TaskNew> call = uploadartapiInterface.uploadtask(api_key,
                name,
                info,
                year,
                technique,
                createdby_me,
                wishtosell,
                price,
                contact,
                dimen_unit,
                width,
                height,
                currency_code,
                sellprints,
                tags);

        call.enqueue(new Callback<TaskNew>() {
            //show progress dialog
            final ProgressDialog progressDialog = ProgressDialogPopup.showProgressDialog(UploadArt.this,
                    getResources().getString(R.string.loading), "");
            @Override
            public void onResponse(@NonNull Call<TaskNew> call, @NonNull Response<TaskNew> response) {

                //on response successful
                if(response.isSuccessful())
                {
                    //Toast.makeText(UploadArt.this,"upload task successful",Toast.LENGTH_SHORT).show();
                    //call image upload api
                    try
                    {
                        //Toast.makeText(UploadArt.this, "here", Toast.LENGTH_SHORT).show();
                        assert response.body() != null;
                        if(uploadArtImage(response.body().getTaskId().toString().trim(),response.body().getUserId().toString().trim()))
                        {
                            Toast.makeText(UploadArt.this, "Uploaded", Toast.LENGTH_SHORT).show();
                            //successfully image uploaded
                            progressDialog.dismiss();
                            UploadArt.super.onBackPressed();
                            //Toast.makeText(UploadArt.this, "Success", Toast.LENGTH_SHORT).show();
                            //AlertPopup.alertDialogShow(UploadArt.this, response.body().getMessage().toString(), "");

                            //Log.d("ImageUploadq123",response.body().toString());
                        }
                        else {
                            Toast.makeText(UploadArt.this, "Not uploaded", Toast.LENGTH_SHORT).show();
                            //image upload unsuccessful
                            progressDialog.dismiss();
                            //Log.d("ImageUploadq123",response.body().toString());
                        }
                    }
                    catch (Exception e)
                    {
                        progressDialog.dismiss();
                        AlertPopup.alertDialogShow(UploadArt.this, e.getMessage(), "");
                    }
                }
                else
                {
                    //Toast.makeText(UploadArt.this,"Upload task failed",Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                    //AlertPopup.alertDialogShow(UploadArt.this, "Some error occurred 2", "");
                    Toast.makeText(UploadArt.this, "Something wrong with your internet connection. Please try again.", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(@NonNull Call<TaskNew> call, @NonNull Throwable t) {
                progressDialog.dismiss();
                //Toast.makeText(UploadArt.this,"upload task failed",Toast.LENGTH_SHORT).show();
                AlertPopup.alertDialogShow(UploadArt.this, "Some error occurred 3", "");
                Toast.makeText(UploadArt.this, "Something wrong with your internet connection. Please try again.", Toast.LENGTH_SHORT).show();

            }
        });

    }




 //image upload api
    private boolean uploadArtImage(String task_Id, String user_Id)
    {
        // Build and send an Event.
        mTracker.send(new HitBuilders.EventBuilder()
                .setCategory(getString(R.string.ga_upload_action))
                .setAction(getString(R.string.ga_upload_action))
                .build());

        //check if pic is properly set to the imageview
        final Boolean[] imageresonse = new Boolean[1];

        if(imageadded)
        {
            //get the bytes
            Bitmap bitmap = ((BitmapDrawable) previewImage.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageInByte = baos.toByteArray();

            RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), imageInByte);
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", "image"+"_"+user_Id+"_"+task_Id+".jpg", requestFile);
            RequestBody userId = RequestBody.create(MediaType.parse("text/plain"), user_Id);
            RequestBody taskId = RequestBody.create(MediaType.parse("text/plain"), task_Id);

            UploadArtApiInterface uploadArtApiInterface = ApiClient.getApiClient().create(UploadArtApiInterface.class);
            Call<ProfilePicUploadResponse> call = uploadArtApiInterface.uploadArt(body,userId,taskId);

            final ProgressDialog progressDialog = ProgressDialogPopup.showProgressDialog(UploadArt.this,
                    getResources().getString(R.string.loading), "");
            call.enqueue(new Callback<ProfilePicUploadResponse>() {
                @Override
                public void onResponse(@NonNull Call<ProfilePicUploadResponse> call, @NonNull Response<ProfilePicUploadResponse> response) {

                    progressDialog.dismiss();

//                    ProfilePicUploadResponse profilePicUploadResponse = response.body();
//                    if (profilePicUploadResponse.getError() != null){
//                        AlertPopup.alertDialogShow(UploadArt.this, response.body().getMessage(), "");
//                    }
//                    else {
//                        AlertPopup.alertDialogShow(UploadArt.this, profilePicUploadResponse.getMessage(), "");
//                    }
                    if(response.isSuccessful())
                    {
                        imageresonse[0] =true;
                        //Toast.makeText(UploadArt.this,response.body().getMessage(),Toast.LENGTH_SHORT).show();
                        //AlertPopup.alertDialogShow(UploadArt.this, response.body().getMessage(), "");
                        Intent intent = new Intent();
                        intent.putExtra("message","message");
                        setResult(12);
                        finish();
                        //UploadArt.super.onBackPressed();
                        //Log.d("ImageUpload",response.body().toString());
                    }
                    else
                    {
                        //AlertPopup.alertDialogShow(UploadArt.this, response.body().getMessage(), "");
                        //Log.d("ImageUpload","error occurred");
                        imageresonse[0] =false;
                       //Toast.makeText(UploadArt.this,response.body().toString(),Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onFailure(@NonNull Call<ProfilePicUploadResponse> call, @NonNull Throwable t) {
                    imageresonse[0] =true;
                    //Toast.makeText(UploadArt.this,response.body().getMessage(),Toast.LENGTH_SHORT).show();
                    //AlertPopup.alertDialogShow(UploadArt.this, t.getMessage(), "");
                    Intent intent = new Intent();
                    intent.putExtra("message","message");
                    setResult(12);
                    finish();
//                    progressDialog.dismiss();
//                    Log.d("ImageUpload",t.getMessage());
//                    //AlertPopup.alertDialogShow(UploadArt.this, t.getMessage(), "");
//                    imageresonse[0] =false;
                }
            });
            return imageresonse[0];
        }
        else {
            return false;
        }

    }

I have a switch in UI, when it is on it ask for price. When it is off it doesn't ask for any other information.

Update: I have solved the problem. One of the parameter that I was posting was null.

  • 3
    What is the stack trace ? Did you look at the trace to figure out which object is getting the NullPointerException ? – Pratham Aug 12 '19 at 07:32
  • Where is the NPE coming from – Rafsanjani Aug 12 '19 at 07:35
  • I am not able to see which object is throwing nullpointerexception. Here is my StackTrace. java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Integer.toString()' on a null object reference 2019-08-12 13:05:22.743 21267-21267/com.codon.masterpiece W/System.err: at com.codon.masterpiece.ui.fullscreen_and_upload.UploadArt$14.onResponse(UploadArt.java:1012) 2019-08-12 13:05:22.743 21267-21267/com.codon.masterpiece W/System.err: at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83) – Jagdish Choudhary Aug 12 '19 at 07:37
  • How can I see from which object is giving NullPointException? – Jagdish Choudhary Aug 12 '19 at 07:40
  • add your log cat crash details – Suraj Vaishnav Aug 12 '19 at 07:44

2 Answers2

0

Do null checks on taskid and userid before converting them to strings.

if(uploadArtImage(response.body().getTaskId().toString().trim(),response.body().getUserId().toString().trim()))
Prasad
  • 1,089
  • 13
  • 21
  • I have checked it. getTaskId() is giving NullPointException. How can I resolve this? – Jagdish Choudhary Aug 12 '19 at 07:55
  • if response.body().getTaskId() is null then add some business logic specific to your business or throw some custom exception. easiest way is to replace this "response.body().getTaskId().toString()" with this (""response.body().getTaskId()+) But this is not the proper way to handle this,throwing exception is the better way to handle it. – Prasad Aug 12 '19 at 08:01
  • put a default value for userID, it will prevent the NPE, but if your wan to use that value, you need to find out why you are not getting it from the reponse – Lakhwinder Singh Aug 12 '19 at 10:32
  • @jagdish did it resolve? – Prasad Aug 20 '19 at 10:00
0

response.body() can be consumed only once.

if(uploadArtImage(response.body().getTaskId().toString().trim(),response.body().getUserId().toString().trim())) {...}

The second time you call response.body() would be null. You should store it like:

String body = response.body();
if(uploadArtImage(body.getTaskId().toString().trim(),body.getUserId().toString().trim())) {...}
TylerQITX
  • 318
  • 2
  • 9