I am a Xamarin developer and I have followed the URL https://help.branch.io/partners-portal/docs/google-analytics-4#properties-sent-to-google-analytics to integrate Google Analytics 4 in Xamarin forms Android to send branch data to Google Analytics dashboard, but I got exception while running the app, saying
BranchXamarinSDK.BranchException: you must initialize Branch before you can use the Branch object
I have implemented code below in MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set the request metadata before initializing the Branch SDK
BranchAndroid.GetInstance().SetRequestMetadata("$firebase_app_instance_id", (string) FirebaseAnalytics.GetInstance(this).GetAppInstanceId());
BranchAndroid.GetInstance().SetRequestMetadata("$firebase_user_id", "{user_id}");
BranchAndroid.Init(this, Resources.GetString(Resource.String.branch_test_key), this);
LoadApplication(new App());
}
No, if you want to call the SetRequestMetadata()
method, the BranchAndroid.GetInstance()
must have value or it will be null.
In addition, I have check the official document about the Branch and the resource code about the BranchAndroid.
The official document said:
So just make the SetRequestMetadata()
called before the session initialization and after the instance initialization is ok. Your code should be:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
BranchAndroid.Init(this, Resources.GetString(Resource.String.branch_test_key), this);
// Set the request metadata before initializing the Session
BranchAndroid.GetInstance().SetRequestMetadata("$firebase_app_instance_id", (string) FirebaseAnalytics.GetInstance(this).GetAppInstanceId());
BranchAndroid.GetInstance().SetRequestMetadata("$firebase_user_id", "{user_id}");
LoadApplication(new App());
}