我的应用程序称为忠诚度应用程序 当我使用调试模式在手机上运行代码时,应用程序因错误而崩溃:不幸的是,忠诚度应用程序已经停止。
继承我的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
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清单
<?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>
主要活动
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;
}
}
答案 0 :(得分:0)
首先,您没有相机许可
将<uses-permission android:name="android.permission.CAMERA" />
添加到您的清单文件中
其次,请在崩溃时发布您的logcat输出。如果您不与我们分享详细信息,我们无法弄清楚出了什么问题。
更新:
这是一个NPE。根据您的logcat,相机按钮(btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
)为空,因为您在onCreate方法中使用完全不同的布局。
您使用setContentView(R.layout.activity_main);
,但您的btnCapturePicture在activity_camera.xml中的完全不同的布局中使用了您在camera.java文件的onCreate方法中的setContentView(R.layout.activity_camera);
。
答案 1 :(得分:0)
模拟器中有设置 转到设置->应用程序->相机->权限 允许所有选项
您完成了,就这样
祝你好运