保存相机照片时会忽略File.createNewFile()

时间:2017-07-26 02:57:54

标签: android

我在尝试将摄像头拍摄的图像保存到手机的存储空间时遇到问题,但是我一直收到一个错误,我之前没有看到过会说File.createNewFile()会被忽略。有人如何纠正这一点,以便保存照片?或者是否有另一种可能更好的方法,我可以保存相机捕获的图像并将其显示在ImageView中?问题区域可以在PICK_IMAGE_CAMERA else if else下的onActivityResult()中找到。

主要活动

package com.example.stins.orbotcamera;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.SyncStateContract;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private FloatingActionButton fab;
    private ImageView imageView;
    private Uri file;
    private GPSTracker gps;
    private EditText imageComment;
    private CoordinatorLayout coordinatorLayout;
    private TextView imageLat, imageLong;
    private String mLat, mLong;
    private File destination = null;
    private String imgPath = null;
    String mCurrentPhotoPath;

    public static final String UPLOAD_URL = "http://192.168.1.77/UploadExamples/upload.php";

    private Bitmap bitmap;

    private final int PICK_IMAGE_CAMERA = 1, PICK_IMAGE_GALLERY = 2;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageComment = (EditText) findViewById(R.id.imageComment);
        imageLat = (TextView) findViewById(R.id.imageLat);
        imageLong = (TextView) findViewById(R.id.imageLong);

        //fab.setOnClickListener(this);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            fab.setEnabled(false);
            imageComment.setEnabled(false);
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
        }

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectImage();

            }
        });


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                fab.setEnabled(true);
                imageComment.setEnabled(true);
            }

            else{
                coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                final Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Accept all permissions to use app", Snackbar.LENGTH_INDEFINITE);
                snackbar.setAction("OK", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = getBaseContext().getPackageManager()
                                .getLaunchIntentForPackage( getBaseContext().getPackageName() );
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                });

                snackbar.setActionTextColor(Color.WHITE);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.GRAY);


                snackbar.show();
        }


        }

    }

    public void selectImage(){

        try {
            PackageManager pm = getPackageManager();
            int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
            if (hasPerm == PackageManager.PERMISSION_GRANTED) {
                final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Select Option");
                builder.setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals("Take Photo")) {
                            dialog.dismiss();
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, PICK_IMAGE_CAMERA);
                        } else if (options[item].equals("Choose From Gallery")) {
                            dialog.dismiss();
                            Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
                        } else if (options[item].equals("Cancel")) {
                            dialog.dismiss();
                        }
                    }
                });
                builder.show();
            } else
                Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }



    public void uploadImage() {
        //getting name for the image
        String name = imageComment.getText().toString().trim();

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


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

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name", name) //Adding text parameter to the request
                    .addParameter("latitude", mLat)
                    .addParameter("longitude", mLong)
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

            Log.d("Upload", "uploadImage: " + path);

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



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

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

        return path;
    }










    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 0 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            file = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), file);
                imageView.setImageBitmap(bitmap);
                imageComment.setVisibility(View.VISIBLE);

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



        if (requestCode == 0) {
            gps = new GPSTracker(MainActivity.this);

            if (resultCode == RESULT_OK) {
                if (gps.canGetLocation()) {
                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                     mLat = Double.toString(latitude);
                     mLong = Double.toString(longitude);

                    imageLat.setText(mLat);
                    imageLong.setText(mLong);

                    // \n is for new line
                    //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                     final Snackbar snackbar = Snackbar
                            .make(coordinatorLayout, "Current location recorded", Snackbar.LENGTH_LONG);

                    snackbar.setActionTextColor(Color.WHITE);

                    View sbView = snackbar.getView();
                    TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                    textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_on_white_24dp,0,0,0);
                    textView.setTextColor(Color.WHITE);


                    snackbar.show();
                } else {
                    // Can't get location.
                    // GPS or network is not enabled.
                    // Ask user to enable GPS/network in settings.

                }

            } else if (resultCode == RESULT_CANCELED) {
                // user cancelled Image capture
                coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                final Snackbar snackbar = Snackbar
                        .make(coordinatorLayout,"Picture Cancelled", Snackbar.LENGTH_SHORT);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_cancel_white_24dp,0,0,0);
                textView.setTextColor(Color.WHITE);

                snackbar.show();
            } else {
                // failed to capture image
                coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                final Snackbar snackbar = Snackbar
                        .make(coordinatorLayout,"Error Taking Picture", Snackbar.LENGTH_SHORT);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_error_outline_white_24dp,0,0,0);
                textView.setTextColor(Color.WHITE);

                snackbar.show();
            }
        }

        if (requestCode == PICK_IMAGE_CAMERA && (data!=null)) {
            try {
                file = data.getData();
                bitmap = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                //bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);

                Log.e("Activity", "Pick from Camera::>>> ");

                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
                destination = new File(Environment.getExternalStorageDirectory() + "/" +
                        getString(R.string.app_name), "IMG_" + timeStamp + ".jpg");
                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                imgPath = destination.getAbsolutePath();
                imageView.setImageBitmap(bitmap);
                imageComment.setVisibility(View.VISIBLE);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == PICK_IMAGE_GALLERY && (data!=null)) {
            file = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), file);
                Log.e("Activity", "Pick from Gallery::>>> ");

                imgPath = getPath(file);
                destination = new File(imgPath);
                imageView.setImageBitmap(bitmap);
                imageComment.setVisibility(View.VISIBLE);

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

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "OrbotCamera");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("OrbotCamera", "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");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return true;
    }





    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (item.getItemId()) {
            case R.id.action_send:
                if(imageView.getDrawable()==null){
                    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
                    final Snackbar snackbar = Snackbar
                            .make(coordinatorLayout,"Sorry, you'll need an image for that!", Snackbar.LENGTH_SHORT);

                    View sbView = snackbar.getView();
                    TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                    textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_error_outline_white_24dp,0,0,0);
                    textView.setTextColor(Color.WHITE);

                    snackbar.show();
                }
                else {
                    uploadImage();
                }
                return true;


        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {

        new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert)
                .setTitle("Exit")
                .setMessage("Are you sure you want to close Orbot Camera?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }

                })
                .setNegativeButton("No", null)
                .show();


    }

    @Override
    public void onClick(View v) {

        Intent i;
        if(v.getId()==R.id.fab)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), 0);

        }

    }
}

logcat的

07-26 10:56:30.757 23865-23865/com.example.stins.orbotcamera E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.stins.orbotcamera, PID: 23865
                                                                               java.lang.NullPointerException: uri
                                                                                   at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:111)
                                                                                   at android.content.ContentResolver.query(ContentResolver.java:519)
                                                                                   at android.content.ContentResolver.query(ContentResolver.java:478)
                                                                                   at com.example.stins.orbotcamera.MainActivity.getPath(MainActivity.java:215)
                                                                                   at com.example.stins.orbotcamera.MainActivity.uploadImage(MainActivity.java:188)
                                                                                   at com.example.stins.orbotcamera.MainActivity.onOptionsItemSelected(MainActivity.java:427)
                                                                                   at android.app.Activity.onMenuItemSelected(Activity.java:3383)
                                                                                   at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:408)
                                                                                   at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                                                                                   at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:113)
                                                                                   at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:679)
                                                                                   at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                                   at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
                                                                                   at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
                                                                                   at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:959)
                                                                                   at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:623)
                                                                                   at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:154)
                                                                                   at android.view.View.performClick(View.java:6261)
                                                                                   at android.widget.TextView.performClick(TextView.java:11157)
                                                                                   at android.view.View$PerformClick.run(View.java:23748)
                                                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:154)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

1 个答案:

答案 0 :(得分:0)

尝试使用此方法

String file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"";
            File dir = new File(file_path);
            if(!dir.exists()){
                dir.mkdirs();
            }
            File cacheDir = getCacheDir();
            File file1 = new File(cacheDir, dir.toString());
            file1.delete();
            file = new File(dir, "temp.jpeg");

            FileOutputStream fo;

            try
            {
                fo = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fo);
                fo.flush();
                fo.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }