简体   繁体   English

领域数据库未更新

[英]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? 如何使用Realm Android更新Table中的值?

Update mutiple rows in table using Realm in Android 在Android中使用Realm更新表中的多个行

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对象并进行迭代

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.copyToRealm() ,请务必记住,只有返回的对象由Realm管理,因此对原始对象的任何进一步更改都不会保留。

Realm reference 领域参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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