我正在尝试从相机中单击图像并在gridview中显示它们。我使用下面的代码,但得到“不幸的相机已停止工作”错误。请建议
logcat:崩溃开始**07-09 01:14:01.734 3873-3873/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.sakshi.intel, PID: 3873
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sakshi.intel/com.example.sakshi.intel.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.example.sakshi.intel.MainActivity$ImageAdapter.getCount(MainActivity.java:89)
at android.widget.GridView.setAdapter(GridView.java:201)
at com.example.sakshi.intel.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)**
使用以下代码: activity_main.xml`
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="photo"
android:onClick="takePicture"/>
<GridView
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"></GridView>
`
MainActivity.java
公共类MainActivity扩展了ActionBarActivity {
private List<String> myList; // String list that contains file paths to images
private GridView gridview;
private String mCurrentPhotoPath; // File path to the last image captured
static final int REQUEST_TAKE_PHOTO = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize GridView
gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(new ImageAdapter(this));
// Initialize GridView Thumbnail Click Handler
/*gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send File Path to Image Display Activity
Intent intent = new Intent(getApplicationContext(), ImageDisplayActivity.class);
intent.putExtra("path", myList.get(position));
startActivity(intent);
}
});*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return myList.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(myList.get(position), bmOptions);
imageView.setImageBitmap(bitmap);
return imageView;
}
}
private void takePicture()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
File photoFile = null;
try
{
photoFile = createImageFile();
}
catch (IOException ex)
{
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null)
{
takePictureIntent.putExtra(MediaStore. EXTRA_OUTPUT,
Uri. fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException
{
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format( new Date());
String imageFileName = "JPEG_" + timeStamp + "_" ;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File. createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK)
{
// Save Image To Gallery
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE );
File f = new File(mCurrentPhotoPath );
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
// Add Image Path To List
myList.add( mCurrentPhotoPath);
// Refresh Gridview Image Thumbnails
gridview.invalidateViews();
}
}
}
答案 0 :(得分:0)
您正在尝试访问myList
课程内getCount()
内的列表ImageAdapter
的大小。这就是异常发生的地方。
发生异常是因为myList
是一个空对象。
为什么它为空?可能是因为在myList.add( mCurrentPhotoPath);
onActivityResult
内,mCurrentPhotoPath
的值可能为空。
在onActivityResult
:
if (mCurrentPhotoPath != null) {
myList.add(mCurrentPhotoPath);
} else {
// can't access image file path.Show a toast or something.
}
现在,根据我的经验,一些手机制造商会返回一个文件路径,其中有些会返回捕获的图像的位图。我不确定,有些人可能都会回归。 因此,只希望访问捕获图像的文件路径不会帮助您的应用。