-1

I have these following methods defined inside class DriverDetails. Whenever I set the image , I get these NullPointerException. Can anyone guide me through this?

08-25 13:10:28.156: E/AndroidRuntime(6890): FATAL EXCEPTION: main
08-25 13:10:28.156: E/AndroidRuntime(6890): java.lang.NullPointerException
08-25 13:10:28.156: E/AndroidRuntime(6890):     at in.veho.vehodriver.DriverDetails.setCarImage(DriverDetails.java:692)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at in.veho.vehodriver.DriverDetails.access$5(DriverDetails.java:683)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at in.veho.vehodriver.DriverDetails$UploadCarImageTask.onPostExecute(DriverDetails.java:632)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at in.veho.vehodriver.DriverDetails$UploadCarImageTask.onPostExecute(DriverDetails.java:1)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at android.os.AsyncTask.finish(AsyncTask.java:631)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at android.os.Looper.loop(Looper.java:137)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at android.app.ActivityThread.main(ActivityThread.java:5227)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at java.lang.reflect.Method.invokeNative(Native Method)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at java.lang.reflect.Method.invoke(Method.java:511)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
08-25 13:10:28.156: E/AndroidRuntime(6890):     at dalvik.system.NativeStart.main(Native Method)

==============================================================================

private void setDriverImage(String pValue) {

    byte[] decodeString;
    try {

    Gson gson = new GsonBuilder().create();
        Content content = gson.fromJson(pValue, Content.class);
         String imageData = content.imagedata;
         imageData = imageData.substring(imageData.indexOf(",") + 1);
        decodeString = Base64.decode(imageData);

        if (decodeString != null && decodeString.length > 0) {
            mDriverImageBitmap = BitmapFactory.decodeByteArray(
                    decodeString, 0, decodeString.length);
            byte[] lImage = TextUtilis.getBytes(mDriverImageBitmap);
            TukxiCache.saveDataToDisk(Constants.UPDATED_DRIVER_IMAGE_TAG,
                    DriverDetails.this, true);
            TukxiCache.saveDataToDisk(Constants.DRIVER_IMAGE_TAG,
                    DriverDetails.this, lImage);
            mDriverImageField.setImageBitmap(mDriverImageBitmap);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

==========================================================================

public class UploadCarImageTask extends AsyncTask<Bitmap, Void, String> {

    @Override
    protected void onPreExecute() {
        showCustomDialogs(PROGRESS_DIALOG);

    }

    @Override
    protected String doInBackground(Bitmap... params) {
        if (!NetworkUtility.isNetworkConnected(DriverDetails.this)) {
            return getString(R.string.internet_fail);
        }

        String lResponse = TukxiDriverServerUtils.uploadCarImage(
                DriverDetails.this, params[0], mUserInfo.getPhoneNumber(),
                filePath); //here i m made change from file path to uri of the image
        if (lResponse != null) {
            return lResponse;
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        dismissCustomDialogs(PROGRESS_DIALOG);
        if (TextUtils.isEmpty(result)) {

            DialogUtility.getOKDialog(DriverDetails.this, null,
                    getString(R.string.image_uploaded_successfully_text),
                    null).show();
            setCarImage(result);
            mUploadedCarImage = true;
            updateContinueBtn();

        } else {
            DialogUtility.getOKDialog(DriverDetails.this, null,
                    getString(R.string.image_uploaded_failed_text), null)
                    .show();
        }               
    }
}

=======================================================

public class Content 
{
     @SerializedName("imagedata")
     public String imagedata;
}

==========================================================

public static String uploadCarImage(Context pContext, Bitmap pBitmap,
        String pPhoneNumber, String filePath) {

    String type = "carphoto";
    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > Build.VERSION_CODES.FROYO) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    // Making HTTP request
    try {

        // new url for new API
        String result;

        String Upload_Image_Url = Constants.main_url + Constants.driver_url
                + "/" + pPhoneNumber + Constants.driver_photo_upload_url
                + "/" + type;
        Log.i("Upload_Image_Url", Upload_Image_Url);

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(Upload_Image_Url);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("type", new StringBody(type));
        entity.addPart("phone", new StringBody(pPhoneNumber));
        entity.addPart("image", new FileBody(new File(filePath),
                "image/jpg"));


        post.setEntity(entity);
        Log.i("MimeTypeMap",MimeTypeMap.getFileExtensionFromUrl(filePath).toString());

        HttpResponse response = client.execute(post);
        //Log.i("car image response server",response.toString());
        HttpEntity httpEntity = response.getEntity();

        // receive response as inputStream
        //InputStream inputStream = null;
        InputStream inputStream = httpEntity.getContent();
        TukxiDriverParsers.uploadPhotoResponse(pContext, inputStream);

    } catch (Exception e) {
        Constants.printLog("Upload Photo response ", "exception occured "
                + e.getMessage());
        return e.getMessage();
    }
    return null;
}

============================================================

public static String uploadPhotoResponse(Context pContext, InputStream lResponse) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(lResponse, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    lResponse.close();
    String response = sb.toString();
    Constants.printLog("uploadPhotoResponse ", ""+response);
    return null;
}

SOLVED: Fixed the problem. I was returning the null in the response. I fixed that for correct results.

2 Answers2

1

You are returning null from your uploadCarImage method. See the line just after the try-catch block.

Also your uploadPhotoResponse is always returning null.

Kaustuv
  • 816
  • 5
  • 9
  • But the thing is that - having all these problems, the image is uploaded to the server but crashes instantly. So will instead of returning as `null` , `return response` works? – Sanjog Shrestha Aug 25 '14 at 16:44
  • @Sanjog Shrestha That's because you are uploading image before all those 'null' values, in your `uploadCarImage` method inside the try-catch block. – Kaustuv Aug 25 '14 at 17:05
  • Fixed the problem. I was returning the `null` in the `response` as mentioned by @kaustuv . Thankyou! Cheers to that! – Sanjog Shrestha Aug 25 '14 at 21:01
1

Add Getter/Setter to Content.java,

 public class Content 
{
 @SerializedName("imagedata")
 public String imagedata;

 public string getImagedata(){
     return imagedata;
 }
 public void setImagedata(String imageData){
        imagedata = imageData;
 }

}

In setDriverImage(String pValue),

     String imageData = content.imagedata; //use content.getImagedata(); instead

     imageData = imageData.substring(imageData.indexOf(",") + 1);
     decodeString = Base64.decode(imageData);

For reference , please check

http://www.mysamplecode.com/2012/05/java-convert-json-string-object.html http://examples.javacodegeeks.com/core-java/gson/convert-java-object-to-from-json-using-gson-example/ JSON GSON.fromJson Java Objects

Hope it works. Happy coding :)

Community
  • 1
  • 1
vijay
  • 2,004
  • 3
  • 19
  • 37
  • `Getter Setter` is not required at the context as I am using `gson library` and parsing from there within. Anyway thankyou for the effort! – Sanjog Shrestha Aug 25 '14 at 21:00
  • getters & setters are required as gson library maps to it only. Also I have added some links for reference above.can you provide some sample pValue in setDriverImage(pValue). – vijay Aug 26 '14 at 04:54