Android - 应用程序在尝试保存图像时崩溃

时间:2017-08-17 20:50:25

标签: android image crash

我是Android新手,我希望我能在这里找到解决方案。 在我的活动中,我可以拍照并从画廊中选择它。按下保存按钮后,应用程序应将图像保存在数据库中。但我得到的是以下错误

08-17 22:52:41.326 2683-2697/android.process.media E/DatabaseUtils: Writing exception to parcel
                                                                    java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35 from pid=4424, uid=10060 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                        at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:605)
                                                                        at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:480)
                                                                        at android.content.ContentProvider$Transport.enforceFilePermission(ContentProvider.java:471)
                                                                        at android.content.ContentProvider$Transport.openTypedAssetFile(ContentProvider.java:416)
                                                                        at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:313)
                                                                        at android.os.Binder.execTransact(Binder.java:453)

08-17 22:42:31.929 4290-4290/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.group6.travlhoe, PID: 4290
                                                                   java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
                                                                       at com.group6.TakeOff.activity_unterkunft.imageViewToByte(activity_unterkunft.java:187)
                                                                       at com.group6.TakeOff.activity_unterkunft$3.onClick(activity_unterkunft.java:205)
                                                                       at android.view.View.performClick(View.java:5198)
                                                                       at android.view.View$PerformClick.run(View.java:21147)
                                                                       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:5417)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我的Java代码:     public class activity_unterkunft扩展了AppCompatActivity {

    DatabaseHelper myDb;
    Button btn_save;
    Spinner ChooseProject;
    EditText Entfernung,Price,MWST;
    String selectedspinner;

    ImageView imageView6;
    private static int PICK_IMAGE = 100;
    Uri imageUri;


    private BottomNavigationViewEx bottomNavigationViewEx;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unterkunft);
        myDb = new DatabaseHelper(this);

        ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
        Entfernung = (EditText) findViewById(R.id.Entfernung);
        Price = (EditText) findViewById(R.id.Preis);
        MWST = (EditText) findViewById(R.id.MwSt);
        btn_save=(Button) findViewById(R.id.btn_save);

        ImageButton btnCamera= (ImageButton)findViewById(R.id.btnCamera);
        imageView6=(ImageView) findViewById(R.id.imageView6);

        loadSpinnerData();
        SaveData();

        //CameraInitialisierung
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        //++++++++++++BOTTOM NAVIGATION BAR++++++++++++//
        bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavigationView);

        bottomNavigationViewEx.setOnNavigationItemSelectedListener(new BottomNavigationViewEx.OnNavigationItemSelectedListener(){
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item){
                if (item.getItemId()==R.id.menu_start){
                    startActivity(new Intent(activity_unterkunft.this, MainActivity.class));
                } else if(item.getItemId()==R.id.menu_allgemein){
                    startActivity(new Intent(activity_unterkunft.this, activity_allgemein.class));
                } else if(item.getItemId()==R.id.menu_transport){
                    startActivity(new Intent(activity_unterkunft.this, activity_transport.class));
                } else if(item.getItemId()==R.id.menu_rechnung){
                    startActivity(new Intent(activity_unterkunft.this, activity_rechnung.class));
                } else if(item.getItemId()==R.id.menu_unterkunft){
                    startActivity(new Intent(activity_unterkunft.this, activity_unterkunft.class));
                }
                return true;
            }
        });

        bottomNavigationViewEx.setSelectedItemId(R.id.menu_unterkunft);
        BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
    }
    public void onButtonClicked(View v){
        if(v.getId()==R.id.btnCamera) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            String pictureName= getPictureName();
            File imageFile=  new File(pictureDirectory,pictureName);

            //URI weil putExtra sonst nicht mit File elementen klar kommt!
            Uri pictureUri = Uri.fromFile(imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);

            startActivityForResult(intent, 0);
        }
        if(v.getId()==R.id.goToGPS) {
            //Intent intent2 = new Intent(activity_unterkunft.this, function_gps.class );
            Intent intent2 = new Intent(activity_unterkunft.this, MapsActivity.class );
            startActivity(intent2);
        }
        if(v.getId()==R.id.btnGallery){
            openGallery();
        }
    }

    private void openGallery() {
        Intent Gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Gallery, PICK_IMAGE);
    }

    private String getPictureName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = sdf.format(new Date());
        return "Rechnung"+ timestamp + ".jpg";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK && requestCode==PICK_IMAGE){
            imageUri= data.getData();
            imageView6.setImageURI(imageUri);
        }

        // Bitmap bitmap = (Bitmap)data.getExtras().get("data");

        //imageView.setImageBitmap(bitmap);
    }



    /**
     * Function to load the spinner data from SQLite database
     * */
    private void loadSpinnerData() {
        // database handler
        DatabaseHelper db = new DatabaseHelper (getApplicationContext());

        // Spinner Drop down elements
        List<String> projects = db.getAllProjects();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, projects);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        ChooseProject.setPrompt("Projekt auswählen");

        // attaching data adapter to spinner
        ChooseProject.setAdapter(dataAdapter);

        //Listener für den Spinner damit ich den Wert abspeichern kann
        ChooseProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                //selectedspinner =String.ValueOf(parent.getItemAtPosition(pos));
                selectedspinner = (String) ChooseProject.getSelectedItem();
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


    }

    public static byte[] imageViewToByte(ImageView image) {
        Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        return byteArray;
    }

    //++++++++++++Save Data++++++//
    public void SaveData(){
        btn_save.setOnClickListener(
        new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isInserted = myDb.createUnterkunft(
                                selectedspinner,
                                Integer.valueOf(Price.getText().toString()),
                                Integer.valueOf(MWST.getText().toString()),
                                Integer.valueOf(Entfernung.getText().toString()),
                                imageViewToByte(imageView6)
                        );
                        if(isInserted=true)
                            Toast.makeText(activity_unterkunft.this, "Daten gespeichert", Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(activity_unterkunft.this, "Daten nicht gespeichert", Toast.LENGTH_LONG).show();

                    }
                }
        );
    }
}

我的DB-Helper中的相应方法:

 //+++++++++++++CREATE A UNTERKUNFT++++++++++++//
    public boolean createUnterkunft(String project, int price, int steuer, int entfernung, byte [] image){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_PROJECT, project);
        contentValues.put(KEY_PRICE, price);
        contentValues.put(KEY_MWST, steuer);
        contentValues.put(KEY_ENTFERNUNG, entfernung);
        contentValues.put(KEY_RECHNUNG_IMG, image);
        long result = db.insert(TABLE_UNTERKUNFT,null,contentValues);
        if(result == -1)
            return false;
        else
            return true;

    }

我希望有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

自Android 6.0以来,已经引入了运行时权限。确保您已经请求了READ_EXTERNAL_STORAGE权限,否则您将无法访问外部存储中的文件。更多信息:https://developer.android.com/training/permissions/requesting.html