保存图片路径

Saving path to image

有一个功能,将用户图像添加到我的应用程序,但我需要图像再次使用,所以我选择了 SQLite 数据库来保存图像的路径,我的数据库工作正常。所以在 OnClick 方法中,应用程序显示 DialogWindow,用户从图库中选择图像:


choosePath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                //Type - image:
                photoPickerIntent.setType("image/*");
                //Start activity, waiting for result 
                startActivityForResult(photoPickerIntent, Pick_image);
            }
        });

然后调用onActivityResult:

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode){
            case Pick_image:
                if(requestCode == RESULT_OK){
                    try {
                        final Uri imageUri = imageReturnedIntent.getData();
                        final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        Log.e("mLog", "onActivityResult: " + imageStream + " " +  imageReturnedIntent + " " + imageUri);

                        pathToImage = imageUri.toString();
                    } catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
        }
    }


但是当我在 SQlite 中保存路径时:

ContentValues cv = new ContentValues();
                cv.put("description", description);
                cv.put("image_link", pathToImage);
                cv.put("category", category[0]);

                long res = mDb.insert("favourites", null, cv);
                if (res > -1) {
                    Toast.makeText(getApplicationContext(), "Шаблон добавлен в любимые", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(getApplicationContext(), "Ошибка", Toast.LENGTH_SHORT).show();
                }

我遇到异常:

E/SQLiteDatabase: Error inserting description=dog image_link=null category=
    android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favourites.image_link (code 1299 SQLITE_CONSTRAINT_NOTNULL)

我使用了调试器,但它对我没有帮助。 请帮我解决这个问题!

更正您的 if 条件,这会导致您的代码不在 if 条件内 运行 并获取 pathToImage 对象 null

 // you are matching here request code with result status
 if(requestCode == RESULT_OK)


 //It should be
 if(resultCode == RESULT_OK)