简体   繁体   中英

Displaying image taken by camera API android

I have been following this tutorial: AndroidHive - working with Camera API to try and enable taking photos in my app. However, I'm getting an error once I press my "take photo button".

LogCat:

    09-16 11:04:00.539  19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/Dob_in_a_Hoon_photos﹕ Failed to create Dob_in_a_Hoon_photos directory
09-16 11:04:00.539  19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/AndroidRuntime﹕ Shutting down VM
09-16 11:04:00.539  19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40e21438)
09-16 11:04:00.559  19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException: file
            at android.net.Uri.fromFile(Uri.java:441)
            at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.getOutputMediaFileUri(dob_in_a_hoon.java:97)
            at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.captureImage(dob_in_a_hoon.java:89)
            at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.access$000(dob_in_a_hoon.java:28)
            at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon$1.onClick(dob_in_a_hoon.java:60)
            at android.view.View.performClick(View.java:4191)
            at android.view.View$PerformClick.run(View.java:17229)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4963)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
            at dalvik.system.NativeStart.main(Native Method)
09-16 11:04:10.529  19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour I/Process﹕ Sending signal. PID: 19561 SIG: 9

Here is my .java file:

public class dob_in_a_hoon extends ActionBarActivity {

    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    public static final int MEDIA_TYPE_IMAGE = 1;

    private static final String IMAGE_DIRECTORY_NAME = "Dob_in_a_Hoon_photos";

    private Uri fileUri;

    private ImageView Hoon_Image;
    private Button button_take_photo;


    private String driver_spinner_array[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dob_in_a_hoon);
        driver_spinner_array = new String[2];
        driver_spinner_array[0] = "Yes";
        driver_spinner_array[1] = "No";
        Spinner Driver_spinner = (Spinner) findViewById(R.id.driver_selector);
        ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, driver_spinner_array);
                Driver_spinner.setAdapter(adapter);

        Hoon_Image = (ImageView) findViewById(R.id.CapturedImage);
        button_take_photo = (Button)findViewById(R.id.btn_take_photo);

        button_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                captureImage();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dob_in_a_hoon, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void captureImage(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

    public Uri getOutputMediaFileUri(int type){
        return Uri.fromFile(getOutputMediaFile(type));
    }

    private static File getOutputMediaFile(int type){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);

        if (!mediaStorageDir.exists()){
            if (!mediaStorageDir.mkdirs()){
                Log.d(IMAGE_DIRECTORY_NAME, "Failed to create " + IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type==MEDIA_TYPE_IMAGE){
            mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");
        }else {
            return null;
        }

        return mediaFile;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
            if (resultCode==RESULT_OK){
                previewCapturedImage();
            }else if (resultCode == RESULT_CANCELED){
                Toast.makeText(getApplicationContext(),"User Cancelled image Capture", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getApplicationContext(),"Failed to capture image", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void previewCapturedImage(){
        try{
            Hoon_Image.setVisibility(View.VISIBLE);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8;
            final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);

            Hoon_Image.setImageBitmap(bitmap);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState){
        super .onSaveInstanceState(outState);

        outState.putParcelable("file_uri", fileUri);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState){
        super.onRestoreInstanceState(savedInstanceState);

        fileUri = savedInstanceState.getParcelable("file_uri");
    }
}

Can anybody see where I am going wrong in my code, and what I have to do to fix it?

I created a sample snippet and tested out the mkdirs as shown in your code, it causes similar exception if i removed the permissions

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Can you please check your manifest to make sure you have these defined.

If above is not the problem, another (unlikely) source of error could be your SD card is running out of space or some permissions restrictions. In this case, i would try the app on android emulator or another device.

This should be added in Manifest to use camera feature:

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:glEsVersion="0x00020000"
              android:required="true"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM