虽然ID不同,但android对象框数据库正在放置对象两次

时间:2018-06-06 09:24:10

标签: java android objectbox

我正在使用Greenrobot的对象框数据库。我正在创建一个笔记应用程序,其中有一个活动负责添加笔记。我有一个密码验证,通过显示一个对话框,如果用户输入正确的密码,它会触发 Eventbus 的事件,然后执行操作,保存或删除。问题是当我保存笔记它工作正常但是对于第二个笔记以及之后它也保存了(n-1)笔记。例如。如果当前保存的音符应该 3 那么它会再次保存第一个和第二个音符,总共 6个音符(1-1,2-1,2 ,3)即可。我已尝试使用事务和普通put方法,但两者都给出了相同的错误结果。这可能是什么问题?我负责保存和删除的活动代码如下所示,它也是同一个活动,它负责根据创建时传递给它的标志值编辑备注。

public class AddNoteActivity extends AppCompatActivity {

    SharedPrefManager sharedPrefManager;
    Box<Note> noteBox;
    private final int REQUEST_IMAGE=123;
    String encodedImage=null;
    Note note,newNote;
    String reason;
    public static int action=-1;

    EnterPinDialog enterPinDialog;

    @BindView(R.id.noteTitle)
    EditText noteTitle;
    @BindView(R.id.noteDesc)
    EditText noteDesc;
    @BindView(R.id.noteImage)
    ImageView noteImage;
    @BindView(R.id.addNoteHolder)
    RelativeLayout addNoteHolder;
    @BindView(R.id.imgDelete)
    ImageView imgDelete;

    @OnClick(R.id.noteImage)
    public void openImage(View view){
        openImagePicker();
    }

    @OnClick(R.id.imgSave)
    public void saveNote(View view){
        action=0;
        enterPinDialog=new EnterPinDialog(this);
        enterPinDialog.show();

    }

    @OnClick(R.id.imgDelete)
    public void onDeleteClick(View view){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setMessage("Are you sure you want to delete this note?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                action=1;
                enterPinDialog=new EnterPinDialog(AddNoteActivity.this);
                enterPinDialog.show();
            }
        });

        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog alertDialog=builder.create();
        alertDialog.show();

    }

    @OnLongClick(R.id.noteImage)
    public boolean onImageLongClick(View view){
        if(encodedImage !=null && !encodedImage.equals("")){

            FullScreenDialog fullScreenDialog=new FullScreenDialog();
            Bundle bundle=new Bundle();
            bundle.putString("image_base64",encodedImage);
            fullScreenDialog.setArguments(bundle);
            fullScreenDialog.show(getSupportFragmentManager(),FullScreenDialog.TAG);
        }

        return false;
    }

    @Subscribe
    public void onPinCorrect(EventManager.CorrectPin correctPin){
        save();
    }

    @Subscribe
    public void onPinCorrectDelete(EventManager.CorrectPinDelete correctPinDelete){
        delete();
    }

    public void delete(){
        if(reason !=null && reason.equals(Constants.EDIT)){
            MyApplication.getBoxStore().runInTxAsync(new Runnable() {
                @Override
                public void run() {
                    noteBox.remove(note.id);
                    Log.d("ANURAN","deleting note with id "+note.getId());
                }
            }, new TxCallback<Void>() {
                @Override
                public void txFinished(@javax.annotation.Nullable Void result, @javax.annotation.Nullable Throwable error) {
                    Snackbar.make(addNoteHolder,"Note deleted successfully.",Snackbar.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new EventManager.NewNote());
                    finish();
                }
            });
        }

    }

    public void save(){
        String title=noteTitle.getText().toString();
        String desc=noteDesc.getText().toString();
        if(Utils.isEmpty(title) || Utils.isEmpty(desc)){
            Snackbar.make(addNoteHolder,"Note Title and Descriptions are mandatory.",Snackbar.LENGTH_SHORT).show();
            return;
        }

        String noteTitleEnc= AES.encrypt(title,sharedPrefManager.getEncryptionKey());
        String noteDescEnc=AES.encrypt(desc,sharedPrefManager.getEncryptionKey());
        String noteImageDB="";
        if(encodedImage!=null){
            noteImageDB=AES.encrypt(encodedImage,sharedPrefManager.getEncryptionKey());
        }

        newNote=new Note(new Date().getTime(),noteTitleEnc,noteDescEnc,noteImageDB,new Date().getTime()+"");
        if(reason.equals(Constants.EDIT)){
            MyApplication.getBoxStore().runInTxAsync(new Runnable() {
                @Override
                public void run() {

                    note.setTitle(newNote.getTitle());
                    note.setDescription(newNote.getDescription());
                    note.setTime(new Date().getTime()+"");
                    note.setImage(newNote.getImage());
                    Log.d("ANURAN EDIT","putting note with id "+note.getId());
                    noteBox.put(note);
                }
            }, new TxCallback<Void>() {
                @Override
                public void txFinished(@javax.annotation.Nullable Void result, @javax.annotation.Nullable Throwable error) {
                    Snackbar.make(addNoteHolder,"Note updated successfully.",Snackbar.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new EventManager.NewNote());
                    finish();
                }
            });
        }else if(reason.equals(Constants.ADD)){
//            MyApplication.getBoxStore().runInTxAsync(new Runnable() {
//                @Override
//                public void run() {
//                    Log.d("ANURAN ADD","putting note with id "+newNote.getId());
//                    noteBox.put(newNote);
//                }
//            }, new TxCallback<Void>() {
//                @Override
//                public void txFinished(@javax.annotation.Nullable Void result, @javax.annotation.Nullable Throwable error) {
//                    Snackbar.make(addNoteHolder,"Note saved successfully.",Snackbar.LENGTH_SHORT).show();
//                    EventBus.getDefault().post(new EventManager.NewNote());
//                    finish();
//                }
//            });
            noteBox.put(newNote);
            Snackbar.make(addNoteHolder,"Note saved successfully.",Snackbar.LENGTH_SHORT).show();
            EventBus.getDefault().post(new EventManager.NewNote());
            finish();
        }
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_note);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        noteBox= MyApplication.getBoxStore().boxFor(Note.class);
        sharedPrefManager=MyApplication.getSharedPrefManager();

        reason=getIntent().getExtras().getString(Constants.EDIT_OR_ADD);
        if(reason!=null && reason.equals(Constants.EDIT)){
            note=findNote(Long.parseLong(getIntent().getExtras().getString(Constants.NOTE_TO_EDIT)));
            populateEdits(note);
        }else if(reason !=null && reason.equals(Constants.ADD)){
            imgDelete.setVisibility(View.INVISIBLE);
        }
    }

    private Note findNote(long l) {
        QueryBuilder<Note> builder=noteBox.query();
        builder.equal(Note_.__ID_PROPERTY,l);
        Note n=builder.build().findFirst();
        return n;
    }

    private void populateEdits(Note note) {
        noteTitle.setText(AES.decrypt(note.getTitle(),sharedPrefManager.getEncryptionKey()));
        noteDesc.setText(AES.decrypt(note.getDescription(),sharedPrefManager.getEncryptionKey()));
        noteImage.setImageBitmap(decodeImage(AES.decrypt(note.getImage(),sharedPrefManager.getEncryptionKey())));
        if(note.getImage() !=null && !note.getImage().equals(""))
            convertImageToBase64();
        else
            noteImage.setImageResource(R.drawable.ic_add_gray_24dp);
    }

    public void openImagePicker(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_IMAGE){
            if(data !=null){
                Uri imageURI=data.getData();
                Picasso.get().load(imageURI).into(noteImage, new Callback() {
                    @Override
                    public void onSuccess() {
                        convertImageToBase64();
                    }

                    @Override
                    public void onError(Exception e) {
                        Snackbar.make(addNoteHolder,"Could not load the image.Please try again.",Snackbar.LENGTH_SHORT).show();
                    }
                });

            }
        }
    }

    private void convertImageToBase64() {

        Bitmap bitmap= ((BitmapDrawable)noteImage.getDrawable()).getBitmap();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
        byte[] b = baos.toByteArray();
        encodedImage= Base64.encodeToString(b,Base64.DEFAULT);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right);
    }


    @Override
    protected void onStop() {
        super.onStop();
        action=-1;
    }

    public Bitmap decodeImage(String encodedImage){
        byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
        Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
        return decodedBitmap;
    }
}

0 个答案:

没有答案