领域数据库未更新

时间:2017-03-23 06:38:18

标签: java android realm

嗨朋友请帮助我,我正在制作文本和图像转换的聊天应用程序每当用户更改其配置文件中的图像时,它也需要在转换中更新,但它没有得到更新,但每当我发送一个新的消息然后新图像正在更新,我也没有设置主键

以下链接我尝试过没有效果:

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());
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这种更新方式。

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();

如果您需要更新所有内容,请获取RealmResults对象并迭代

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

注意: 使用realm.copyToRealm()时,请务必记住只有返回的对象由Realm管理,因此对原始对象的任何进一步更改都不会保留。

Realm reference