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评论68阅读模式
英文:

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是实际的聊天界面。以下是我的代码:

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

返回到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:

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

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类:

public class MessagesViewModel extends ViewModel{
    
    // 定义你想要存储/交互的LiveData变量
    private MutableLiveData<ArrayList<Message>> messageList = new MutableLiveData<>();

    public MessagesViewModel(){
        // 在这里读取你的文件...
        
        // 使用文件的数据来更新LiveData的值
        messageList.setValue(newMessageList);
    }
    
    // 为你的Activity/Fragment创建一个访问LiveData的方法
    public LiveData<ArrayList<Message>> getMessageList(){
        return messageList;
    }
    
    // 为你的Activity/Fragment创建一个更新LiveData的方法
    public void updateMessageList(ArrayList<Message> updatedMessageList){
        messageList.setValue(updatedMessageList);
    }
    
    // 当所有连接的Activity/Fragment生命周期都已结束时调用
    // (如果需要的话,这是你可以清理ViewModel使用的任何资源的地方)
    @Override
    protected void onCleared(){
        // 在这里将你的数据保存回文件...
        
        super.onCleared();
    }
}

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

// 获取你的ViewModel
//(根据你可能需要从哪里访问ViewModel,你可能想将其设置为成员变量)
MessagesViewModel messagesViewModel = new ViewModelProvider(this).get(MessagesViewModel.class);

// 调用observe()来接收数据以及对数据的任何更新
messagesViewModel.getMessageList().observe(this, new Observer<ArrayList<Message>>(){
    @Override
    public void onChanged(ArrayList<Message> messageList){
        // 与你的数据做一些操作...
    }
});

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

// 创建你的更新数据...

// 使用新数据更新你的ViewModel
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:

public class MessagesViewModel extends ViewModel{
	
	// Define the LiveData variable(s) you want to store/interact with
	private MutableLiveData&lt;ArrayList&lt;Message&gt;&gt; messageList = new MutableLiveData&lt;&gt;();
	
	public MessagesViewModel(){
		// Read your file here ...
		
		// Use the file&#39;s data to update the value(s) of your LiveData
		messageList.setValue(newMessageList);
	}
	
	// Create a method for your Activity/Fragment(s) to access the LiveData
	public LiveData&lt;ArrayList&lt;Message&gt;&gt; getMessageList(){
		return messageList;
	}
	
	// Create a method for your Activity/Fragment(s) to update the LiveData
	public void updateMessageList(ArrayList&lt;Message&gt; updatedMessageList){
		messageList.setValue(updatedMessageList);
	}
	
	// Called when all connected Activity/Fragment lifecycles have finished
	// (If necessary, here is where you can clean up any resources your ViewModel uses)
	@Override
	protected void onCleared(){
		// Save your data back to file here ...
		
		super.onCleared();
	}
}

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

// Retrieve your ViewModel
// (You may want to make this a member variable depending on where you may need to access the ViewModel from)
MessagesViewModel messagesViewModel = new ViewModelProvider(this).get(MessagesViewModel.class);

// Call observe() to receive the data as well as any updates to it
messagesViewModel.getMessageList().observe(this, new Observer&lt;ArrayList&lt;Message&gt;&gt;(){
	@Override
	public void onChanged(ArrayList&lt;Message&gt; messageList){
		// Do something with your data ...
	}
});

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

// Create your updated data ...

// Update your ViewModel with the new data
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:

确定