I'm trying to create an android app which receives Firebase message from server and changes the source image of a ImageView by calling a function.
my firebase Service:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String body = remoteMessage.getNotification().getBody();
MainActivity.changeUi(body);
}
My MainActivity:
public class MainActivity extends AppCompatActivity {
static ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Loading Home Layout
setContentView(R.layout.activity_home);
iv=findViewById(R.id.imgView);
}
public static void changeUi(String s){
if(s=="change")
iv.setImageResource(R.drawable.image2);
}
}
The App Crashes on sending firebase message. This is my first app and I could not understand other answers. Thanks for the help.
Calling static method will create new instance of that activity. Here its crashing due to imageView not initialize.
You can use BroadCast Receiver here. Below is an example.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String body = remoteMessage.getNotification().getBody();
Intent myIntent = new Intent("FBR-IMAGE");
myIntent.putExtra("action",body);
this.sendBroadcast(myIntent);
}
On Activity you need to create and register receiver
public BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
changeUi(action);
}
};
@Override
protected void onResume() {
super.onResume();
registerReceiver(myReceiver, new IntentFilter("FBR-IMAGE"));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments