1

I try to execute a method automatically from my class MyFirebaseMessaging.java that receives by firebase message by cloud, and when it arrives all this code is activated, executing the method that is in Home.

The error is that when I still declare onCreate and globally declare the variable the CardView cardUDatos, it tells me that:

E/UncaughtException: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.CardView.setVisibility(int)' on a null object reference

MyFirebaseMessaging.java

public class MyFirebaseMessaging extends FirebaseMessagingService {
@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
if(remoteMessage.getData() != null) {

        Map<String,String> data = remoteMessage.getData();
        String title = data.get("title");
        final String message = data.get("message");
   if (title.equals("Aceptar")) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Home SDI = new Home();
                SDI.MostrarDatos();

            }
        });
    }
     }
   }
    }

Clase Home.java donde esta el layout

 CardView cardUDatos;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
{
 .
 .
 .
 cardUDatos = (CardView) findViewById(R.id.cardview_user);
 .
 .
 .
}

 public void MostrarDatos(){ DatabaseReference UserInformation = FirebaseDatabase.getInstance().getReference(Common.User);
  UserInformation.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if(dataSnapshot.exists()){
            List<Object> map = (List<Object>) dataSnapshot.getValue();

       String name

       name = String.valueOf(map.get(2).toString());

   }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // ...
    }
});


cardUDatos.setVisibility(View.VISIBLE);
}
Sagar
  • 23,903
  • 4
  • 62
  • 62

1 Answers1

2

The problem is following line:

Home SDI = new Home();

You shouldn't try to access Activity in this way. This will only create the instance of Activity. This instance won't have any relation with the actual Activity (if running in foreground). The life-cycle methods won't be called as a consequence your cardUDatos won't be initialized.

One way is to implement the LocalBroadcastReceiver. Refer to this SO for implementation details

Sagar
  • 23,903
  • 4
  • 62
  • 62