Getter returning null in different class

kewlprogramz :

while making an Android app, I have ran in the following problem:

My MainActivity looks like this:

...
private String token;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
tokenSetter();
}
private void tokenSetter() {
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(task -> {
                if (!task.isSuccessful()) {
                    Log.w("TRAZENITOKEN", "getInstanceId failed", task.getException());
                    return;
                }

                // Get new Instance ID token
                String token = Objects.requireNonNull(task.getResult()).getToken();
                setToken(token);

                Log.d("TRAZENITOKEN", "onGetToken: " + token);

                // Log and toast
                // Log.d("TRAZENITOKEN", "onComplete: " + token);
            });
}
public String getToken() {
    return token;
}

public void setToken(String token) {
    this.token = token;
}

I know that the token value is being set as in an another method inside this MainActivity class, when I call getToken(), I get the value.

However, when I try to call getToken from an another Activity, something like this:

...
button.setOnClickListener(view -> {
        FirebaseActions firebaseActions = new FirebaseActions();
        MainActivity  mainActivity = new MainActivity();
        //firebaseActions.setUserNameOnToken(editText.getText().toString());
        if(mainActivity.getToken() != null) editText.setText(mainActivity.getToken());
        else editText.setText("Skafiskafnjak");
    });

(I opted for the editText.setText method for debugging purposes, I am going to use it in the commented way) The code snippet above always goes to the else part as the getToken is null. Why does it return null in this class, if it returns a value in it's own class? Could it be perhaps because I did MainActivity mainActivity = new MainActivity();

An answer would be appreciated. Thanks in advance!

Code-Apprentice :

MainActivity mainActivity = new MainActivity();

This activity instance is not the same one that the Android system created where you see the token being set. Besides, we never create an activity with new. The Android system creates activities according to the activity lifecycle and your code must work within this structure. To pass data between activities, you need to send it in the Intent when you call startActivity(). See the documentation for an example of how to do this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=300280&siteId=1