Getting activity reference in AndroidViewModel

I have an AndroidViewModel that I'm using GoogleSignIn with. The GoogleSignIn method I'm using requires an activity context to perform SilentSignIn. I have tried using the Application context that is provided with AndroidViewModel using getApplication().

Although it doesn't throw an error in Android Studio

enter image description here

at run time it throws the error:

Cannot cast application context

How can I get reference to the Activity that uses the ViewModel?

public class MembersViewModel extends AndroidViewModel {

    public MembersViewModel(@NonNull Application application) {
        super(application);
        repo = new MembersRepo(application, this);
    }


public void signIn(){
   Log.d(TAG, "onGetMembers: Invalid Access Token...Logging in again");
   GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                     .requestIdToken(getApplication().getString(R.string.idclient))
                        .requestEmail()
                        .build();
   GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(getApplication(), gso);
                

I have an activity that uses a MembersFragment that uses the MembersViewModel.

Answers 1

  • How can I get reference to the Activity that uses the ViewModel?

    You can't.

    Instead, have your MembersViewModel emit an event that your activity observes and responds to by doing whatever it is that you need to have done with the activity. "Emit an event" could be via an RxJava PublishSubject or a carefully-constructed "single live event" form of LiveData. If you were using Kotlin, a BroadcastChannel would be another possibility.


Related Articles