When passing an object to another Activity using Parcelable, how can I update the object and see the changes in the original Activity?

huangapple go评论95阅读模式
英文:

When passing an object to another Activity using Parcelable, how can I update the object and see the changes in the original Activity?

问题

我正在开发一个简单的Android短信应用程序。在我的MainActivity中,当用户点击与某人的对话时,我通过使用Parcelable将自定义的Conversation对象通过意图传递。这部分完美地实现了。问题是,如果我更改了此对象中的任何字段,在返回MainActivity时,没有显示任何更改。据我所知,Parcelable只是传递对象的副本,而不是传递对它的引用。是否有任何方法可以在活动之间保留这些更改?

我想要持续更新聊天中发送的最后一条消息。有一个RecyclerView.Adapter,它将使用新文本更新视图。这个最后一条消息文本将在返回我的主活动时显示。

我不能附加图像,因为我没有足够的声望点数。但是我的MainActivity只是对话列表。我的ChatActivity是实际的聊天界面。以下是我的代码:

  1. public class ChatActivity extends AppCompatActivity implements Parcelable {
  2. //在这里接收我的自定义Conversation对象,为简洁起见省略
  3. mConversation.setLastMessage("这是一条新消息。");
  4. mChatAdapter.notifyDataSetChanged();
  5. }

返回到MainActivity后,尽管修改了lastMessage字段,但没有显示任何更改。我应该如何做?或者是否有一种在活动之间持续更新对象的替代方法?

非常感谢任何帮助,谢谢您花费时间。如果这是一个令人困惑的问题,我表示抱歉。

英文:

I am working on a simple texting app in Android. In my MainActivity, when the user clicks on a conversation with someone, I send over my custom Conversation object through an intent using Parcelable. That works perfectly. Problem is, if I change any fields in this object, upon returning to the MainActivity, none of my changes are shown. As far as I can tell, Parcelable merely passes a copy of the object, rather than passing the reference to it. Is there any way I can have these changes preserved across activities?

I want to continuously update the last message that was sent in the chat. There is a RecyclerView.Adapter that will update the View with the new text. This last message text is to be displayed upon returning to my Main Activity.

I cannot attach an image because I do not have enough reputation points. But my MainActivity is just a list of conversations. My ChatActivity is the actual chat screen. Here is my code:

  1. public class ChatActivity extends AppCompatActivity implements Parcelable {
  2. //receive my custom Conversation object here, left out for brevity
  3. mConversation.setLastMessage("This is a new message.");
  4. mChatAdapter.notifyDataSetChanged();
  5. }

Upon returning to my MainActivity, despite modifying the lastMessage field, no changes are shown. How can I do this? Or is there an alternative way to continuously update an object across activities?

Any help is very much appreciated, and thank you for your time. Sorry if this was a confusing question.

答案1

得分: 1

你可以使用ViewModel来存储和更新数据。它允许你的Activities/Fragments监视数据的更新,并将其生命周期与连接的Activities/Fragments的生命周期协调。

创建一个新的ViewModel类:

  1. public class MessagesViewModel extends ViewModel{
  2. // 定义你想要存储/交互的LiveData变量
  3. private MutableLiveData<ArrayList<Message>> messageList = new MutableLiveData<>();
  4. public MessagesViewModel(){
  5. // 在这里读取你的文件...
  6. // 使用文件的数据来更新LiveData的值
  7. messageList.setValue(newMessageList);
  8. }
  9. // 为你的Activity/Fragment创建一个访问LiveData的方法
  10. public LiveData<ArrayList<Message>> getMessageList(){
  11. return messageList;
  12. }
  13. // 为你的Activity/Fragment创建一个更新LiveData的方法
  14. public void updateMessageList(ArrayList<Message> updatedMessageList){
  15. messageList.setValue(updatedMessageList);
  16. }
  17. // 当所有连接的Activity/Fragment生命周期都已结束时调用
  18. // (如果需要的话,这是你可以清理ViewModel使用的任何资源的地方)
  19. @Override
  20. protected void onCleared(){
  21. // 在这里将你的数据保存回文件...
  22. super.onCleared();
  23. }
  24. }

在你的两个Activities的onCreate()方法中获取你的ViewModel:

  1. // 获取你的ViewModel
  2. //(根据你可能需要从哪里访问ViewModel,你可能想将其设置为成员变量)
  3. MessagesViewModel messagesViewModel = new ViewModelProvider(this).get(MessagesViewModel.class);
  4. // 调用observe()来接收数据以及对数据的任何更新
  5. messagesViewModel.getMessageList().observe(this, new Observer<ArrayList<Message>>(){
  6. @Override
  7. public void onChanged(ArrayList<Message> messageList){
  8. // 与你的数据做一些操作...
  9. }
  10. });

当你需要从Activity内部更新数据时:

  1. // 创建你的更新数据...
  2. // 使用新数据更新你的ViewModel
  3. messagesViewModel.updateMessageList(updatedMessageList);

你可以在https://developer.android.com/topic/libraries/architecture/viewmodel找到有关ViewModel的更多信息。

英文:

You can use a ViewModel to store and update your data. It allows your Activities/Fragments to watch the data for updates and coordinates its lifecycle with the lifecycles of the connected Activities/Fragments.

Create a new ViewModel class:

  1. public class MessagesViewModel extends ViewModel{
  2. // Define the LiveData variable(s) you want to store/interact with
  3. private MutableLiveData&lt;ArrayList&lt;Message&gt;&gt; messageList = new MutableLiveData&lt;&gt;();
  4. public MessagesViewModel(){
  5. // Read your file here ...
  6. // Use the file&#39;s data to update the value(s) of your LiveData
  7. messageList.setValue(newMessageList);
  8. }
  9. // Create a method for your Activity/Fragment(s) to access the LiveData
  10. public LiveData&lt;ArrayList&lt;Message&gt;&gt; getMessageList(){
  11. return messageList;
  12. }
  13. // Create a method for your Activity/Fragment(s) to update the LiveData
  14. public void updateMessageList(ArrayList&lt;Message&gt; updatedMessageList){
  15. messageList.setValue(updatedMessageList);
  16. }
  17. // Called when all connected Activity/Fragment lifecycles have finished
  18. // (If necessary, here is where you can clean up any resources your ViewModel uses)
  19. @Override
  20. protected void onCleared(){
  21. // Save your data back to file here ...
  22. super.onCleared();
  23. }
  24. }

Retrieve your ViewModel from within both of your Activities' onCreate() methods:

  1. // Retrieve your ViewModel
  2. // (You may want to make this a member variable depending on where you may need to access the ViewModel from)
  3. MessagesViewModel messagesViewModel = new ViewModelProvider(this).get(MessagesViewModel.class);
  4. // Call observe() to receive the data as well as any updates to it
  5. messagesViewModel.getMessageList().observe(this, new Observer&lt;ArrayList&lt;Message&gt;&gt;(){
  6. @Override
  7. public void onChanged(ArrayList&lt;Message&gt; messageList){
  8. // Do something with your data ...
  9. }
  10. });

When you need to update the data from within your Activity:

  1. // Create your updated data ...
  2. // Update your ViewModel with the new data
  3. messagesViewModel.updateMessageList(updatedMessageList);

You can find more information on ViewModels at https://developer.android.com/topic/libraries/architecture/viewmodel

huangapple
  • 本文由 发表于 2020年9月3日 09:35:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63715586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定