Make Firebase Analytics simple and easy to use with the Singleton and Builder patterns

Background and overview

If you set Firebase Analytics simply based on the reference, it will be as follows. quickstart-android

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    //① Define a Firebase Analytics instance in a field so that it can be used throughout the class
    private FirebaseAnalytics mFirebaseAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //② Set Firebase Analytics instance at the timing of onCreate
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        TextView helloWorld = (TextView) findViewById(R.id.hello_world);
        helloWorld.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.hello_world) {
            // ③ 「Hello World!Fires the event log when the text is clicked
            Bundle params = new Bundle();
            params.putString("param1", "test");
            params.putInt("param2", 100);
            params.putDouble("param3", 3.14);
            mFirebaseAnalytics.logEvent("event1", params);
        }
    }
}

If you write the code according to the reference, as mentioned above, ** Firebase Analytics instance definition location **, ** instance setting location **, ** event log firing location using that instance ** are different. .. This makes it difficult to manage instances of Firebase Analytics within each class, and it is difficult to use Firebase Analytics.

Also, apart from the above, the parameter setting part to be added to the event log also becomes redundant as the number of parameters increases, and if possible, this part can also be set more simply (for example, using a chain method). Want to.

1. Use the Singleton pattern to make everything from instance definition to event log firing simpler

Implement FirebaseAnalyticsHelper class using Singleton pattern as follows. Regarding the Singleton pattern, [the one posted on Wikipedia](https://ja.wikipedia.org/wiki/Singleton_%E3%83%91%E3%82%BF%E3%83%BC%E3%83 I referred to% B3).

public class FirebaseAnalyticsHelper {

    //① Define a Firebase Analytics instance in the field
    private FirebaseAnalytics mFirebaseAnalytics;

    //② Set up a Firebase Analytics instance with "Singleton pattern"
    private static FirebaseAnalyticsHelper sInstance;
    private FirebaseAnalyticsHelper(Context context){
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(context.getApplicationContext());
    }
    public static synchronized FirebaseAnalyticsHelper getInstance(Context context){
        if(sInstance == null){
            sInstance = new FirebaseAnalyticsHelper(context);
        }
        return sInstance;
    }

    //③ Create a method to fire the event log
    public void logEvent(@NonNull final String name, Bundle params) {
        mFirebaseAnalytics.logEvent(name, params);
    }
    public void logEvent(@NonNull final String name) {
        mFirebaseAnalytics.logEvent(name, null);
    }
}

When applied to the above-mentioned MainActivity using this FirebaseAnalyticsHelper class, the code related to ** FirebaseAnalytics can be written only in the part that fires the event log as shown below. ** **

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView helloWorld = (TextView) findViewById(R.id.hello_world);
        helloWorld.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.hello_world) {
            //「Hello World!Fires the event log when the text is clicked
            Bundle params = new Bundle();
            params.putString("param1", "test");
            params.putInt("param2", 100);
            params.putDouble("param3", 3.14);
            FirebaseAnalyticsHelper.getInstance(this).logEvent("event1", params);
        }
    }
}

Below is the sample code. hinom77/SimpleFirebaseAnalytics ~ Branch: feature_singleton

2. Simpler parameter management with Builder pattern

Implement the FirebaseAnalyticsParams class using the Builder pattern as follows. Regarding the Builder pattern, there are various patterns as in the article Builder pattern pattern written in Java, but here ** Effective Java Builder ** is used.

public class FirebaseAnalyticsParams {

    //(1) Define parameter settings in "Builder pattern"
    private Bundle mParams;
    private FirebaseAnalyticsParams(Builder builder) {
        mParams = builder.params;
    }
    public static class Builder {
        private Bundle params = new Bundle();

        public Builder param1(String param1) {
            params.putString("param1", param1);
            return this;
        }

        public Builder param2(Integer param2) {
            params.putInt("param2", param2);
            return this;
        }

        public Builder param3(Double param3) {
            params.putDouble("param3", param3);
            return this;
        }

        public FirebaseAnalyticsParams build() {
            return new FirebaseAnalyticsParams(this);
        }
    }

    //(2) Return the Params value as a Bundle type
    public Bundle getBundleParams() {
        return mParams;
    }
}

When applied to the above-mentioned MainActivity using this FirebaseAnalyticsParams class, the code of the parameter setting part can be as simple as **, no matter how many variables there are.

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView helloWorld = (TextView) findViewById(R.id.hello_world);
        helloWorld.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.hello_world) {
            //「Hello World!Fires the event log when the text is clicked
            FirebaseAnalyticsParams params = new FirebaseAnalyticsParams
                    .Builder().param1("test").param2(100).param3(3.14).build();
            FirebaseAnalyticsHelper.getInstance(this).logEvent("event1", params);
        }
    }
}

Note that the FirebaseAnalyticsHelper class also needs to be partially rewritten in response to the above.

Below is the sample code. hinom77/SimpleFirebaseAnalytics ~ Branch: feature_builder

Recommended Posts

Make Firebase Analytics simple and easy to use with the Singleton and Builder patterns
How to use @Builder and @NoArgsConstructor together
[Swift] How to link the app with Firebase
Super easy way to use enum with JSP
Easy to make LINE BOT with Java Servlet
When importing CSV with Rails, it was really easy to use the nkf command
How to use RealSense with ubuntu 20.04 and ROS Noetic
Easy to make LINE BOT with Java Servlet Part 2: I tried image messages and templates
[Beginner] Try to make a simple RPG game with Java ①
Make Docker confusing with Pokemon and make it easier to attach
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
Uppercase only the specified range with substring. (How to use substring)
[Java] Use ResolverStyle.LENIENT to handle the date and time nicely
How to use the certificate and private key created by Docker's BASIC authentication with AWS ALB
If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.