Search code examples
javaandroidlambdaads

Convert Mobile Ads method to a Lambda expression. How could I do that?


First of all, my code is working, so this is more like a "best practice" kind of question.

I am working with Mobile Ads SDK, using the following code with MobileAds.initialize method:

import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;

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

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
    }
}

Android Studio is giving me the following warning:

Anonymous new OnInitializationCompleteListener() can be replaced with lambda

I checked out about lambda expressions here.

But I am not sure how, if I should do this conversion, and what would be the benefits of it (just more readability?)

If someone could enlight me I will be thankful.


Solution

  • Basically to solve Warnings in android developing and If you are using Android Studio you can solve those mistakes pretty easily by Ide itself!

    Like you are getting warning -

    Anonymous new OnInitializationCompleteListener() can be replaced with lambda

    you can easily solve by pressing alt + enter or clicking a light bulb and then you will get lot of option to fix those warnings

    In your problem you can convert it like this -

    MobileAds.initialize(this, initializationStatus -> { 
       // your code here 
    });
    

    for example you can see this image by Light Bulb or Alt + Enter while putting cursor in the grey code line.

    enter image description here