0

I am trying to send an image to my server. I am doing this by taking a look on tutorial in the LINK

However I need to send photo took from camera, not from gallery so I made a few changes, and I get an error like this:

FATAL EXCEPTION: main Process: com.example.audriusalekna.camerapht, PID: 25792 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.audriusalekna.camerapht/com.example.audriusalekna.camerapht.MainActivity}: 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 android.app.ActivityThread.deliverResults(ActivityThread.java:3887) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3930) at android.app.ActivityThread.access$1300(ActivityThread.java:178) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1561) at android.os.Handler.dispatchMessage(Handler.java:111) at android.os.Looper.loop(Looper.java:194) at android.app.ActivityThread.main(ActivityThread.java:5692) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) Caused by: 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.audriusalekna.camerapht.MainActivity.onActivityResult(MainActivity.java:70) at android.app.Activity.dispatchActivityResult(Activity.java:6346) at android.app.ActivityThread.deliverResults(ActivityThread.java:3883) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3930)  at android.app.ActivityThread.access$1300(ActivityThread.java:178)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1561)  at android.os.Handler.dispatchMessage(Handler.java:111)  at android.os.Looper.loop(Looper.java:194)  at android.app.ActivityThread.main(ActivityThread.java:5692)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372) 

My code from MainActivity is here:

package com.example.audriusalekna.camerapht;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import static android.R.attr.bitmap;
import static android.R.attr.x;
import static android.R.attr.y;
import static android.provider.ContactsContract.CommonDataKinds.Website.URL;


public class MainActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;
    private Uri fileUri;
    private ImageView imageView;
    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button cameraBtn = (Button) findViewById(R.id.push_button);
        imageView = (ImageView)findViewById(R.id.imageTest);

        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

            //sending image to server
            StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
                @Override
                public void onResponse(String s) {

                    if(s.equals("true")){
                        Toast.makeText(MainActivity.this, "Uploaded Successful", Toast.LENGTH_LONG).show();
                    }
                    else{
                        Toast.makeText(MainActivity.this, "Some error occurred!", Toast.LENGTH_LONG).show();
                    }
                }
            },new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(MainActivity.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
                }
            }) {
                //adding parameters to send
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> parameters = new HashMap<String, String>();
                    parameters.put("image", imageString);
                    return parameters;
                }
            };

            RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
            rQueue.add(request);

        }
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();

            try {
                //getting image from gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);

                //Setting image to ImageView
                imageView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
  • When you send the photo, do you see it in your `ImageView` ? – Guillaume Apr 13 '17 at 09:56
  • I think this link help full for you http://stackoverflow.com/questions/8373755/java-lang-runtimeexception-failure-delivering-result-resultinfowho-null-reque – ND1010_ Apr 13 '17 at 09:57
  • `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 `. Take your measures. – greenapps Apr 13 '17 at 09:59
  • `bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);` That should be: `photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);`. bitmap==null as you experienced. – greenapps Apr 13 '17 at 10:01
  • `However I need to send photo took from camera` You are not trying to send the photo taken but only a thumbnail of it. – greenapps Apr 13 '17 at 10:03

2 Answers2

0

Your bitmap is null, in order to do what you want you need to save the file localy and than send it . On your Onclick that calls the camera intent do this:

 Intent cameraIntent = new Intent("android.media.action.IMAGE_CAPTURE");
 File file = new File(YOUR_FILE_PATH + "/FILE.jpg");
 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
 startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);

And later onresult take the file from the path like this :

File f = new  File(YOUR_FILE_PATH + "/FILE.jpg");
Bitmap bitmap=null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
   bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
} catch (FileNotFoundException e) {
     e.printStackTrace();
}
imageView.setImageBitmap(bitmap);

Hope it helps.

yanivtwin
  • 617
  • 8
  • 32
0

@greenapps solution worked! I just changed bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); to photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);

  • Please dont put that as an answer yourself. Remove it. Instead you should invite the commenter to post the comment as answer if you think an answer should be there. – greenapps Apr 13 '17 at 10:59