-1

I've been trying to start a really simple camera intent. So I went through a turorial, did all the functions, but when I press the button I get null pointer exception.

This is my code:

package vidas.shay.mobilebridgetask;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by pitsponet on 26/03/2015.
 */
public class userDetailesTopFragment extends Fragment implements     View.OnClickListener {

    //text views
    EditText firstNameTextView;
    EditText lastNameTextView;
    EditText emailTextView;
    EditText phoneNumberTextView;
    EditText adressTextView;
    Button addImageButton;
    Button addHobbiesButton;
    Switch statusSwitch;
    ImageView userProfileImageView;

    Button findMyFriendsButton;
    Button updateMyLocationButton;
    Button usersListButton;

    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;

    private Uri fileUri;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.user_detailes_top_fragment_layout, container, false);

        //v.findViewById(R.id.BT_addImageToProfile).setOnClickListener(this);
        addImageButton = (Button) v.findViewById(R.id.BT_addImageToProfile);
        addImageButton.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View v) {
        Log.d("here", "here ?");

        if (v == addImageButton) {
            startCamera();
        }
    }

    private void startCamera() {
        // create Intent to take a picture and return control to the calling application
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

        // start the image capture Intent
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // Image captured and saved to fileUri specified in the Intent
                Toast.makeText(getActivity(), "Image saved to:\n" +
                        data.getData(), Toast.LENGTH_LONG).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // User cancelled the image capture
            } else {
                // Image capture failed, advise user
            }
        }

        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // Video captured and saved to fileUri specified in the Intent
                Toast.makeText(getActivity(), "Video saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
                //Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                // User cancelled the video capture
            } else {
                // Video capture failed, advise user
            }
        }
    }

    /**
     * Create a file Uri for saving an image or video
     */
    private static Uri getOutputMediaFileUri(int type) {
        return Uri.fromFile(getOutputMediaFile(type));
    }

    /**
     * Create a File for saving an image or video
     */
    private static File getOutputMediaFile(int type) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_" + timeStamp + ".jpg");
        } else if (type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_" + timeStamp + ".mp4");
        } else {
            return null;
        }
        return mediaFile;
    }
}

This is the error I get:

03-27 15:13:28.620    3042-3042/vidas.shay.mobilebridgetask E/AndroidRuntime﹕     FATAL EXCEPTION: main
Process: vidas.shay.mobilebridgetask, PID: 3042
java.lang.NullPointerException: file
        at android.net.Uri.fromFile(Uri.java:447)
        at vidas.shay.mobilebridgetask.userDetailesTopFragment.getOutputMediaFileUri(userDetailesTopFragment.java:130)
        at vidas.shay.mobilebridgetask.userDetailesTopFragment.startCamera(userDetailesTopFragment.java:87)
        at vidas.shay.mobilebridgetask.userDetailesTopFragment.onClick(userDetailesTopFragment.java:75)
        at android.view.View.performClick(View.java:4756)
        at android.view.View$PerformClick.run(View.java:19749)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        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:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Danielson
  • 2,605
  • 2
  • 28
  • 51
Shay Vidas
  • 47
  • 10
  • It would be better to post the part of the code where the exception is thrown rather then post this huge piece of code we would have to check. (life is too short for this). – WonderWorld Mar 27 '15 at 15:29
  • @Shay Vidas:`"failed to create directory"` - this log has never been printed? – Trinimon Mar 27 '15 at 15:40
  • see my answer here: http://stackoverflow.com/questions/31334378/null-pointer-exception-on-file-uri/43228221#43228221 – temirbek Apr 05 '17 at 10:17

1 Answers1

0

You are returning null from this piece of code:

File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
    mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
    mediaFile = new File(mediaStorageDir.getPath() + File.separator +
            "VID_" + timeStamp + ".mp4");
} else {
    return null;
}

So I guess you're not passing a correct media type, or the file itself fails to create so your getting null.

You should debug that code in order to see what's happening.

== EDIT ==

I haven't noticed that you're passing MEDIA_TYPE_IMAGE as parameter, so I think what is failing is:

if (!mediaStorageDir.exists())

Because mediaStorageDir is null.

Pablo
  • 1,041
  • 8
  • 23
  • From what we can see, he does: `fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);` – Trinimon Mar 27 '15 at 15:36
  • ohh ok yes i see that now, maybe it's becouse i'm building it to the simulator ? or it is somthing else ? – Shay Vidas Mar 27 '15 at 15:56
  • try adding `mediaStorageDir.mkdirs();` before checking if that folder exists. I suppose you haven't created it before. – Pablo Mar 27 '15 at 16:14