Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing an class object through intent to broadcast receiver in android

Hi all I am got stuck in a point , please help me out.

In my service

ChatMessage chatMessage = new ChatMessage();
chatMessage.setId(10)
chatMessage.setMessage("hello");
Intent intent = new Intent("MessageReceiver");
intent.putExtra("chatobj", chatMessage);
getApplicationContext().sendBroadcast(intent);

in my Activity

public final BroadcastReceiver ReceiveChat = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
ChatMessage chatMessage = new ChatMessage(getIntent().getSerializableExtra("chatobj"));
Log.v(CommonUtilities.TAG, chatMessage.getMessage()+": new message");
}};

This code is at my start of the activity , before oncreate(). Is this a problem ? The Log has null value. why is that ?

like image 894
manjari Avatar asked Jan 30 '23 21:01

manjari


1 Answers

Implements Serializable in model class. Issue will be resolved

Like this

public class ChatMessage  implements Serializable{

 int id; 
 String name;
}

send data like this

Intent intent = new Intent("MessageReceiver");
Bundle args = new Bundle();
args.putSerializable("chatobj",(Serializable)chatobj);
intent.putExtra("DATA",args);
startActivity(intent);

receive data like this

Intent intent = getIntent();
Bundle args = intent.getBundleExtra("DATA");
ChatMessage chatMessage = (ChatMessage) args.getSerializable("chatobj");
like image 158
AskNilesh Avatar answered Feb 03 '23 07:02

AskNilesh