Pergunta

My application is called Loyalty app When I ran the code on my phone using debugging mode the app crashed with an error: Unfortunately, Loyalty App has stopped.


heres my logcat:

04-03 20:31:49.546: D/AndroidRuntime(30853): Shutting down VM
04-03 20:31:49.546: W/dalvikvm(30853): threadid=1: thread exiting with uncaught exception (group=0x41e18700)
04-03 20:31:49.546: E/AndroidRuntime(30853): FATAL EXCEPTION: main
04-03 20:31:49.546: E/AndroidRuntime(30853): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.loyaltyapp/com.example.loyaltyapp.Camera}: java.lang.NullPointerException
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.os.Looper.loop(Looper.java:137)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.ActivityThread.main(ActivityThread.java:5419)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at java.lang.reflect.Method.invokeNative(Native Method)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at java.lang.reflect.Method.invoke(Method.java:525)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at dalvik.system.NativeStart.main(Native Method)
04-03 20:31:49.546: E/AndroidRuntime(30853): Caused by: java.lang.NullPointerException
04-03 20:31:49.546: E/AndroidRuntime(30853):    at com.example.loyaltyapp.Camera.onCreate(Camera.java:47)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.Activity.performCreate(Activity.java:5372)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-03 20:31:49.546: E/AndroidRuntime(30853):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
04-03 20:31:49.546: E/AndroidRuntime(30853):    ... 11 more

Heres my code:

camera.java

 package com.example.loyaltyapp;

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

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Camera extends Activity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";

private Uri fileUri; // file url to store image/video

private ImageView imgPreview;
private Button btnCapturePicture;

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

    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);

    /*
     * Capture image button click event
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });


    // Checking camera availability
    if (!isDeviceSupportCamera()) {
        Toast.makeText(getApplicationContext(),
                "Sorry! Your device doesn't support camera",
                Toast.LENGTH_LONG).show();
        // will close the app if the device does't have camera
        finish();
    }
}

/**
 * Checking device has camera hardware or not
 * */
private boolean isDeviceSupportCamera() {
    if (getApplicationContext().getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

/*
 * Capturing Camera Image will lauch camera app requrest image capture
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

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

/*
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on scren orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

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

    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}

/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // successfully captured the image
            // display it in image view
            previewCapturedImage();
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
        }
    }
}

/*
 * Display image from a path to ImageView
 */
private void previewCapturedImage() {
    try {
        imgPreview.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

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


/**
 * ------------ Helper Methods ---------------------- 
 * */

/*
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/*
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    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;
}
 }

activity_camera.xml

   <LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:baselineAligned="false"
android:orientation="horizontal"
tools:context="Camera" >

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:gravity="center"
    android:orientation="vertical" >

    <!-- Capture picture button -->

    <Button
        android:id="@+id/btnCapturePicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="Take a Picture" 
        android:onClick="Camera.captureImage()"/>

</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Preview"
        android:padding="10dp"
        android:textSize="15dp"/>

    <!-- To display picture taken -->

    <ImageView
        android:id="@+id/imgPreview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

</LinearLayout>

</LinearLayout>

LoyaltyApp Manifest

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.loyaltyapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

<!-- Accessing camera hardware -->
<uses-feature android:name="android.hardware.camera" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.loyaltyapp.MainActivity"
        android:label="@string/app_name"
        android:uiOptions="splitActionBarWhenNarrow" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.loyaltyapp.Camera"
        android:label="@string/title_activity_camera" >
    </activity>

</application>

</manifest>

main activity

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

if(id == R.id.action_camera) {
        Intent k = new Intent(this, Camera.class);
        startActivity(k);
        return true;
}

}
Foi útil?

Solução

First, you don't have a camera permission
Add the <uses-permission android:name="android.permission.CAMERA" /> to your manifest file
Second, please post your logcat output with your crash. We can't figure out what is wrong if you don't share details with us.

Update: It's a NPE. Based on your logcat, the camera button (btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);) is null because you are using a completely different layout in the onCreate method.
You use setContentView(R.layout.activity_main);, but your btnCapturePicture is in a complety different layout in activity_camera.xml
Use setContentView(R.layout.activity_camera); in the onCreate method of your camera.java file.

Outras dicas

There is setting in emulator Go to Setting -> Apps -> Camera -> Permissions allow every option

and you are done, Thats it

Good luck

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top