java - Android:java.lang.IllegalStateException:无法执行 Activity 的方法

标签 java android

为什么我会收到此错误?

04-27 16:09:19.823  32255-32255/com.example.myapplication D/AndroidRuntime﹕ Shutting down VM
04-27 16:09:19.823  32255-32255/com.example.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41597db8)
04-27 16:09:19.823  32255-32255/com.example.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 32255
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:3830)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.myapplication.MainActivity.storeImage(MainActivity.java:139)
            at com.example.myapplication.MainActivity.save_btn(MainActivity.java:150)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3825)
            at android.view.View.performClick(View.java:4445)
            at android.view.View$PerformClick.run(View.java:18446)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)

我的应用程序所做的是,通过 Intent 打开相机应用程序。然后将 image/bitmao 加载到 imageview 中。每当我单击 save_btn 按钮时,都会出现此错误。有人可以告诉我原因并给我解决方案吗?谢谢。

package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.text.SimpleDateFormat;


public class MainActivity extends Activity {

    static final int REQUEST_IMAGE_CAPTURE = 1;
    ImageView imageView;
    private static final String TAG = "MyActivity";
    Bitmap image;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openCamera();
        setContentView(R.layout.activity_main);
        findViewById(R.id.captureImage).bringToFront();
        findViewById(R.id.saveImage).bringToFront();
        imageView = (ImageView) findViewById(R.id.imageView2);

    }

    protected void onSaveInstanceState(Bundle outState){
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
        file.delete();
    }

    public void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Check that request code matches ours:
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            //Get our saved file into a bitmap object:
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
            Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
            imageView.setImageBitmap(image);
        }
    }

// Reduce the amount of dynamic heap used by expanding the JPEG into a memory array that's already scaled to match the size of the destination view
    public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH
        //First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize, Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        }
        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }

        options.inSampleSize = inSampleSize;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }

    public void capture_btn(View v) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "TMP.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }

    /** Create a File for saving an image or video */
    private  File getOutputMediaFile(){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Pictures/Wiki_Camera"
                + getApplicationContext().getPackageName()
                + "/Files");

        // 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()){
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
        String mImageName="camera_wiki"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
        return mediaFile;
    }

    public void storeImage(Bitmap image) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            Log.d(TAG,
                    "Error creating media file, check storage permissions: ");// e.getMessage());
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }

    public void save_btn(View v) {

        storeImage(image);
    }
}

最佳答案

只是猜测,但似乎您仅为局部变量存储拍摄的图像

Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);

稍后在代码中,您尝试从具有相同名称的类变量存储图像

image.compress(Bitmap.CompressFormat.PNG, 90, fos);

关于java - Android:java.lang.IllegalStateException:无法执行 Activity 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29899540/

相关文章:

java - 这个 IllegalArgumentException 的可能原因是什么?

android - 如何检查编辑文本是否可绘制

android - Swapon 尝试启用 zram 失败

java - 如果收到 HTTP 错误 403,如何从 JavaFx 中的 URL 加载图像

java - Spring安全组件扫描

Java Swing 自定义游标不可见

c# - .Net Hashtable、Java Hashtable 和 HashMap 的区别

android - Div 在 Android 上居中对齐但在 iPhone 上不居中

android - Firebase 事件不显示 NAME 属性

android - 升级到 2.3,现在 ant 构建不包括我的 libs 目录中的 jars