简体   繁体   中英

Realm database is not updating

Hi friends please help me out i am making chating app with the conversion of text and images Whenever user changes the image in his profile it need to be update in the conversion as well but its not getting updated but whenever i sends a new message then the new image is updating and also i dont set the primary key

Here is below link i had tried nothing worked:

How to update the values in Table using Realm android?

Update mutiple rows in table using Realm in Android

public class Chat_history extends AppCompatActivity {
    @BindView(R.id.chat_history_toolbar)
    CustomToolbar chat_history_toolbar;
    @BindView(R.id.sendmessgae)
    CustomEditText sendmessgae;
    @BindView(R.id.chat_history_list)
    ListView chat_history_list;
    Chat_history_Adapter chathisadapter;
    RealmResults<Chat_history_pojo> chathistorylist;
    Realm chatrealm;
    BroadcastReceiver chatreceiver;
    public static final String BroadCastAction = "com.parallelspace.parallelspace.Chat_history";
    RealmChangeListener chatupdatelisterner = new RealmChangeListener() {
        @Override
        public void onChange(Object element) {
            chathisadapter.addmessage(chathistorylist);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_history);
        ButterKnife.bind(this);
        Realm.init(getApplicationContext());
        setSupportActionBar(chat_history_toolbar);
        assert getSupportActionBar() != null;
        **chatrealm = Realm.getDefaultInstance();
        chatrealm.beginTransaction();
        RealmQuery<Chat_history_pojo> getLoginData= chatrealm.where(Chat_history_pojo.class).beginGroup().equalTo("receiverid", getIntent().getStringExtra("rid")).endGroup();
        RealmResults<Chat_history_pojo> registrationRealm = getLoginData.findAll();
        for (Chat_history_pojo chtapojo:registrationRealm) {
            chtapojo.setReciever_profile(getIntent().getStringExtra("rimage"));
            chatrealm.copyToRealm(registrationRealm);
        }
        chatrealm.commitTransaction();**
        chathistorylist = chatrealm.where(Chat_history_pojo.class).beginGroup()
                .equalTo("senderid", Session.getUserID(getApplicationContext()))
                .equalTo("receiverid", getIntent().getStringExtra("rid"))
                .endGroup()
                .or()
                .beginGroup()
                .equalTo("receiverid", Session.getUserID(getApplicationContext()))
                .equalTo("senderid", getIntent().getStringExtra("rid"))
                .endGroup()
                .findAll();
        chathisadapter = new Chat_history_Adapter(Chat_history.this, chathistorylist);
        chat_history_list.setStackFromBottom(true);
        chat_history_list.setTranscriptMode(chat_history_list.TRANSCRIPT_MODE_NORMAL);
        chat_history_list.setAdapter(chathisadapter);
        /*chatrealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                Constant.l("Realm Update Called");
                RealmResults<Chat_history_pojo> updatehispojo = chatrealm.where(Chat_history_pojo.class).equalTo("receiverid", getIntent().getStringExtra("rid")).findAll();
                for(Chat_history_pojo updatepojo:updatehispojo){
                    updatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
                    chatrealm.insertOrUpdate(updatepojo);
                    chathisadapter.notifyDataSetChanged();
                }
            }
        });*/

        sendmessgae.setDrawableClickListener(new DrawableClickListener() {
            @Override
            public void onClick(DrawablePosition target) {
                switch (target) {
                    case RIGHT:
                        if (sendmessgae.getText().toString().isEmpty()) {
                            Constant.t(getApplicationContext(), "Please Enter Message");
                        } else {
                            sendmessage();
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        if (getIntent().hasExtra("mtype")) {
            chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
            chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
        } else {
            chat_history_toolbar.toolbaricon(getApplicationContext(), getIntent().getStringExtra("rimage"));
            chat_history_toolbar.toolbartext(getIntent().getStringExtra("rname"));
        }
        chat_history_toolbar.Whichonclicked("back", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Session.removepushnotification(getApplicationContext());
                Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
                chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(chathistoryintent);
            }
        });
        chat_history_toolbar.Whichonclicked("toolbar", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent chathisintent = new Intent(getApplicationContext(), Detailed_friend.class);
                chathisintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                chathisintent.putExtra("rname", getIntent().getStringExtra("rname"));
                chathisintent.putExtra("rimage", getIntent().getStringExtra("rimage"));
                chathisintent.putExtra("rid", getIntent().getStringExtra("rid"));
                startActivity(chathisintent);
            }
        });
        chat_history_toolbar.Whichonclicked("delete", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatrealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        RealmResults<Chat_history_pojo> deleteresults = realm.where(Chat_history_pojo.class).beginGroup()
                                .equalTo("senderid", Session.getUserID(getApplicationContext()))
                                .equalTo("receiverid", getIntent().getStringExtra("rid"))
                                .endGroup()
                                .or()
                                .beginGroup()
                                .equalTo("receiverid", Session.getUserID(getApplicationContext()))
                                .equalTo("senderid", getIntent().getStringExtra("rid"))
                                .endGroup()
                                .findAll();
                        deleteresults.deleteAllFromRealm();
                    }
                });
            }
        });
        chatreceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                chatrealm = Realm.getDefaultInstance();
                chatrealm.beginTransaction();
                Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
                chatupdatepojo.setSenderid(getIntent().getStringExtra("rid"));
                chatupdatepojo.setReceiverid(Session.getUserID(getApplicationContext()));
                chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
                chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
                chatupdatepojo.setMessage(intent.getStringExtra("msg").replace("$", " "));
                chatupdatepojo.setType("text");
                if (intent.getStringExtra("type").equals("image")) {
                    chatupdatepojo.setType("image");
                } else if (intent.getStringExtra("type").equals("text")) {
                    chatupdatepojo.setType("text");
                }
                chatrealm.commitTransaction();
                chatrealm.close();
            }
        };
        IntentFilter intfil = new IntentFilter(BroadCastAction);
        registerReceiver(chatreceiver, intfil);

    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(chatreceiver);
        super.onDestroy();

    }

    @Override
    protected void onStart() {
        super.onStart();
        chatrealm.addChangeListener(chatupdatelisterner);
        Session.pushnotification(getApplicationContext());
    }

    @Override
    protected void onStop() {
        super.onStop();
        chatrealm.removeChangeListener(chatupdatelisterner);
        Session.removepushnotification(getApplicationContext());
    }

    @OnClick(R.id.camera)
    public void camera() {
        TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(Chat_history.this)
                .setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
                    @Override
                    public void onImageSelected(Uri uri) {
                        try {
                            Bitmap sendimage = MediaStore.Images.Media.getBitmap(Chat_history.this.getContentResolver(), uri);
                            sendimages(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("rid"), sendimage);
                        } catch (IOException e) {
                            Constant.l(e.toString());
                        }
                    }
                })
                .setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
                .create();

        bottomSheetDialogFragment.show(getSupportFragmentManager());
    }

    private void sendimages(String sid, String rid, Bitmap sendbitmap) {
        Constant.showloader(Chat_history.this);
        String sendumageurl = Constant.psurl + "chatdocument&task=send&sender_id=" + sid + "&reciever_id=" + rid;
        Constant.l(sendumageurl);
        AndroidNetworking.post(sendumageurl).addBodyParameter("image", Constant.getStringImage(sendbitmap)).build().getAsJSONObject(new JSONObjectRequestListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString("status").equals("Success")) {
                        Constant.l(String.valueOf(response));
                        chatrealm = Realm.getDefaultInstance();
                        chatrealm.beginTransaction();
                        Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
                        chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
                        chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
                        chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
                        chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
                        chatupdatepojo.setMessage(response.getString("url"));
                        chatupdatepojo.setType("image");
                        chatrealm.commitTransaction();
                        chatrealm.close();
                    }
                } catch (JSONException e) {
                    Constant.l(e.toString());
                    Constant.dismissloader();
                }
                Constant.dismissloader();
            }

            @Override
            public void onError(ANError anError) {
                Constant.l(anError.toString());
                Constant.dismissloader();
            }
        });
    }

    @Override
    public void onBackPressed() {
        Session.removepushnotification(getApplicationContext());
        Intent chathistoryintent = new Intent(getApplicationContext(), Chadim_Home.class);
        chathistoryintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(chathistoryintent);
    }

    private void sendmessage() {
        String schatsendmesg = Constant.psurl + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("rid") + "&message=" + sendmessgae.getText().toString().replace(" ", "$");
        Constant.l(schatsendmesg);
        AndroidNetworking.get(schatsendmesg).setOkHttpClient(Constant.okClient()).build().getAsJSONObject(new JSONObjectRequestListener() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getString("status").equals("Success")) {
                        chatrealm = Realm.getDefaultInstance();
                        chatrealm.beginTransaction();
                        Chat_history_pojo chatupdatepojo = chatrealm.createObject(Chat_history_pojo.class);
                        chatupdatepojo.setSenderid(Session.getUserID(getApplicationContext()));
                        chatupdatepojo.setReceiverid(getIntent().getStringExtra("rid"));
                        chatupdatepojo.setMessage(sendmessgae.getText().toString());
                        chatupdatepojo.setSender_profile(Session.getUserimage(getApplicationContext()));
                        chatupdatepojo.setReciever_profile(getIntent().getStringExtra("rimage"));
                        chatupdatepojo.setType("text");
                        chatrealm.commitTransaction();
                        chatrealm.close();
                        sendmessgae.setText("");
                    }
                } catch (JSONException e) {
                    Constant.l(e.toString());
                }
            }

            @Override
            public void onError(ANError anError) {
                Constant.l(anError.toString());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Session.pushnotification(getApplicationContext());
    }

    @Override
    protected void onPause() {
        super.onPause();
        Session.removepushnotification(getApplicationContext());
    }
}

Try this way of updation.

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();

//Here i am checking the condition 
RealmQuery<RegistrationRealm> getLoginData= realm.where(RegistrationRealm.class).equalTo("id",1);

//finding the first set if matches the criteria
RegistrationRealm registrationRealm = getLoginData.findFirst();

//setting the values
registrationRealm.setFirstname(firstname);
registrationRealm.setLastname(lastname);

//Updating the same object with new values
realm.copyToRealm(registrationRealm);
//commiting the current transaction
realm.commitTransaction();

If you need to update all, then get a RealmResults object and iterate through

RealmResults<RegistrationRealm> registrationRealm = getLoginData.findAll();

NOTE: When using realm.copyToRealm() it is important to remember that only the returned object is managed by Realm, so any further changes to the original object will not be persisted.

Realm reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM