图像未从Android相机

时间:2016-11-10 01:43:27

标签: android android-fragments android-intent nullpointerexception camera

我是JAVA的新手,我正在尝试使用Google培训文档学习android开发。我写了一些使用此培训的代码module

这基本上是调用相机意图 - >单击图像,然后将图像写入外部存储(SD卡)的外部根目录。使用代码我可以使用现有的相机应用程序成功点击照片,我可以查看缩略图,但当我尝试导航到文件夹(有我的包名称)时,我不是能够查看通过应用程序点击的图像,即包含我的包名称的文件夹,但其中没有图像文件。

从下面的代码可以看出,我已经实现了createImageFile()函数来创建外部存储中的图像文件,并且在addListenerOnButton()函数内部我已经将createImageFile()的返回值赋给了照片uri 。这不会创建一个图像文件吗?或者我错过了介于两者之间的任何步骤。我研究了一下,发现“write()”方法应该实现,以便将图像数据写入由createImageFile()函数创建的文件路径,但由于我是新手,我试过但我无法想象我应该在哪里实现write()方法以及应该将哪些数据传递给它。

以下是我的代码 -

package com.app.simple.simplecamera;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.io.FileOutputStream;
import java.io.IOException;

import android.widget.Toast;

import static android.app.Activity.RESULT_OK;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }
    /**creating View instance*/
    View rootview;
    /**setting image capture intent to 1**/
    static final int REQUEST_IMAGE_CAPTURE = 1;
    //static final int RESULT_OK = 1;
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    Context context;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        /**instantiating rootview to infalter,so that whenever
         * fragment is inflated the camera fucntion will be called**/
        rootview = inflater.inflate(R.layout.fragment_main, container, false);
        /**calling the public funtion addlistenerbutton so as to invoke camera intent**/
        addListenerOnButton();
       // getActivity().setResult(RESULT_OK);

        /**return the rootview instance whenever oncreate function is invoked in fragment**/
        return rootview;
    }

    /**setting image capture intent to 1**/
    //static final int REQUEST_IMAGE_CAPTURE = 1;
    //static final int RESULT_OK = 1;
    //Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    /**public function for registering button action**/
    /**public void addListenerOnButton(){*/

    String mCurrentPhotoPath;

    public File createImageFile() throws IOException{
    //create a timestamp for the file
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    //the filename should be as below
    String imageFileName = "JPEG" + timestamp + "_";
    /**assiging a directory to store the file
     here the getExternalFilesDir is accessed via the getActivity()(since it's inside a fragement
     and DIRECTORY_PICTURES on the device is allocated for storage**/
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    //a temp file is created
    File image = File.createTempFile(
                imageFileName, /* prefix */
                ".jpg",        /* suffix */
                storageDir     /* directory */
        );
    mCurrentPhotoPath = "file:" + image.getAbsolutePath();
    //FileOutputStream out = new FileOutputStream(image);
    //out.write(mCurrentPhotoPath.getBytes());

    //galleryAddPic();
    return image;
    }


    public void addListenerOnButton(){

        /**creating a button instance and assiging it to the
         * oncreateview function via the rootview object*/
        Button button = (Button) rootview.findViewById(R.id.button);
        /**setOnClickListener contains the camera action within it**/
        button.setOnClickListener(new View.OnClickListener(){
            /**onClick fucntion to invoke the exisitng camera app via the camera intent**/
            public void onClick(View v) {
                /*Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);*/
                /**if camera exists, which is checked by the getpackagemanager fucntion, then capture image**/
                if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                    //startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                    Context context = getContext().getApplicationContext();
                    // Create the File where the photo should go
                    File photoFile = null;
                    try{
                        photoFile = createImageFile();
                    }
                    catch (IOException ex){
                        // Error occurred while creating the File
                        Toast toast = Toast.makeText(context, "There was a problem saving the photo...", Toast.LENGTH_SHORT);
                        toast.show();
                    }

                    // File pictureFile = createPhotoFile();
                    // Continue only if the File was successfully created
                    if (photoFile != null){
                        //Uri photoURI = FileProvider.getUriForFile(this, "com.app.simple.simplecamera.fileprovider", photoFile);
                        Uri photoURI = FileProvider.getUriForFile(context, "com.app.simple.simplecamera.fileprovider", photoFile);
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

                        //getActivity().setResult(RESULT_OK,takePictureIntent);
                        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                        //startActivityForResult(takePictureIntent, RESULT_OK)


                    }
                }


            }
        });

    }



   @Override
   ///**overriding the onactivityresult method so that it creates a tumbnail
   // * it takes int he request_image_capture value from addlistenronbutton method
   // * result code formthe camera activity inside the addlistneronbiutton method
   // * and data from the intent that invokes the camera and takes picture**/
   public void onActivityResult(int requestCode, int resultCode, Intent data){
       /**checking if request i simagecapture and result is ok**/
       if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
           Bundle extras = data.getExtras();


           /**creating a data bundle with teh object extra**/
           Bundle extras = data.getExtras();
           /**creating bitmap from the captured image data which is etched from
            * the intent data inside addlistneronbutton**/
           Bitmap imageBitmap = (Bitmap) extras.get("data");
           /**creating a placeholder for the image thumbnail using the Imageview instance and the corresponding xml image placeholder "result"
            * refer the fragment xml for the image placeholder**/
           ImageView imageView = (ImageView)rootview.findViewById(R.id.result);
           imageView.setImageBitmap(imageBitmap);

       }
   }



}

编辑 - 我忘了提到onActivityResult()在'boolean android.graphics.Bitmap.compress

上抛出一个空指针异常

以下是我的堆栈跟踪 - AndroidRuntime:FATAL EXCEPTION:主要                   处理:com.app.simple.simplecamera,PID:641                   java.lang.RuntimeException:将结果ResultInfo {who = null,request = 65537,result = -1,data = null}传递给activity {com.app.simple.simplecamera / com.app.simple.simplecamera.MainActivity}: java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap $ CompressFormat,int,java.io.OutputStream)'                       在android.app.ActivityThread.deliverResults(ActivityThread.java:3948)                       在android.app.ActivityThread.handleSendResult(ActivityThread.java:3991)                       在android.app.ActivityThread.-wrap16(ActivityThread.java)                       在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1542)                       在android.os.Handler.dispatchMessage(Handler.java:111)                       在android.os.Looper.loop(Looper.java:207)                       在android.app.ActivityThread.main(ActivityThread.java:5769)                       at java.lang.reflect.Method.invoke(Native Method)                       在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:789)                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)                    引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap $ CompressFormat,int,java.io.OutputStream)'                       在com.app.simple.simplecamera.MainActivityFragment.onActivityResult(MainActivityFragment.java:176)                       在android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:175)                       在android.app.Activity.dispatchActivityResult(Activity.java:6845)                       在android.app.ActivityThread.deliverResults(ActivityThread.java:3944)                       在android.app.ActivityThread.handleSendResult(ActivityThread.java:3991)                       在android.app.ActivityThread.-wrap16(ActivityThread.java)                       在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1542)                       在android.os.Handler.dispatchMessage(Handler.java:111)                       在android.os.Looper.loop(Looper.java:207)                       在android.app.ActivityThread.main(ActivityThread.java:5769)                       at java.lang.reflect.Method.invoke(Native Method)                       在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:789)                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) I /处理:发送信号。 PID:641 SIG:9 断开与目标VM的连接,地址:'localhost:8600',transport:'socket'

0 个答案:

没有答案