应用程序崩溃使用相机时

时间:2017-08-30 03:52:17

标签: android android-camera filepath android-cursor

我是Android的新手,现在已经挣扎了好几天了,我有我的应用程序和一个打开相机的按钮,当我使用相机拍照并将其存储在设备上的文件夹之后有一个按钮,将此图片发送到数据库,但应用程序崩溃,我已经实现了相同的选择图库中的图片没有问题。我已经读过可能导致这个问题的原因,我已经发布了这个问题,但仍然无法弄清楚是什么问题。我想我可能对于为什么会这样,但不知道如何解决它有一些想法。

所以我不知道应用程序在该行崩溃的原因是因为光标所引用的图片不在该文件夹中,而是在创建该图片以存储图片或接收文件路径时这是空的。我真的希望有人可以帮助我。

这是代码:

 botonflotante.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            filePath = Uri.fromFile(getOutputMediaFile());
            //filePath = getOutputMediaFile(MEDIA_TYPE_IMAGE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, filePath);
            startActivityForResult(intent, CAM_REQUEST);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CAM_REQUEST && resultCode == Activity.RESULT_OK){
try {
            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), (filePath));
            imageView.setImageBitmap(bitmap);
  getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, filePath));

        } catch (IOException e) {
            e.printStackTrace();
        }


 public String getPath(Uri uri) {
    Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

    cursor = getActivity().getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();
        return path;

 private static File getOutputMediaFile(){
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(   //getExternalStoragePublicDirectory
            Environment.DIRECTORY_PICTURES), "Vallarta en tus manos Nougat");

    if (!mediaStorageDir.exists()){
        if (!mediaStorageDir.mkdirs()){
            Log.d("Vallarta en tus manos", "failed to create directory");
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    return new File(mediaStorageDir.getPath() + File.separator +
            "IMG_"+ timeStamp + ".jpg");
}

   public class CargarDatos extends AsyncTask<String, Void, String> {
    protected String doInBackground(String... urls) {

        ////////////////-------------
        String correo = campo_correo.getText().toString().trim();
        String nombre = campo_nombre.getText().toString().trim();
        String apellido= campo_apellido.getText().toString().trim();
        String telefono= campo_telefono.getText().toString().trim();
        String categoria= customspinner.getSelectedItem().toString().trim();
        String titulo = campo_titulo.getText().toString().trim();
        String descripcion = campo_descripcion.getText().toString().trim();
        String latitud = Double.toString(latitudeeeee);
        String longitud = Double.toString(longitudeeee);

        String s = (campo_publico.isChecked() ? "1" : "0");
        String r = (campo_terminos.isChecked() ? "1" : "0");

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(TerminosYC.this.getActivity(), uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name",correo) //Adding text parameter to the request
                    .addParameter("nombre",nombre)
                    .addParameter("apellido",apellido)
                    .addParameter("telefono", telefono)
                    .addParameter("categoria", categoria)
                    .addParameter("titulo", titulo)
                    .addParameter("descripcion", descripcion)
                    .addParameter("publico", s)
                    .addParameter("terminos", r)
                    .addParameter("latitud",latitud)
                    .addParameter("longitud",longitud)
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(TerminosYC.this.getActivity(), exc.getMessage(), Toast.LENGTH_SHORT).show();
        }

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

清单:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />

logcat的:

08-29 22:46:49.200 11628-11628/com.example.lupitagarcia.yosoyvallarta E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                    java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
                                                                                        at com.example.lupitagarcia.yosoyvallarta.TerminosYC.getPath(TerminosYC.java:529)
                                                                                        at com.example.lupitagarcia.yosoyvallarta.TerminosYC$1.onClick(TerminosYC.java:362)
                                                                                        at android.view.View.performClick(View.java:5721)
                                                                                        at android.widget.TextView.performClick(TextView.java:10936)
                                                                                        at android.view.View$PerformClick.run(View.java:22620)
                                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7406)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

1 个答案:

答案 0 :(得分:0)

移动的第一步是添加运行时权限代码以启用对外部存储和摄像头的访问,并添加访问硬件(摄像头)的权限。然后,您可以继续使用相机意图代码。

硬件访问代码

<uses-feature android:name="android.hardware.camera"
                  android:required="true" />

代码ti启动摄像头意图

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }

在ActivityResult上收到图片

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}

如果要保存和管理外部存储中的文件,请不要忘记将文件提供程序添加到清单中:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.example.android.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>

这将是您的文件路径XML文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

将图像保存在图库中 private void galleryAddPic(){

    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);
}