Apple Appala Apple Appala - 2 months ago 18
Android Question

How to call method or some part of code from one class to another?

Okay, How do you write code if you need same thing again? Like In my case I have implemented a Fullscreen ad like below code and I need same thing in another activity when button press but I don't want to write all the code, I want to call is from previous activity.
I have tried is

Cover cc=new Cover();
cc.showIndustrial();


but it thow me a null pointer exception.
I want to do is Create a new class for Industrial ad and write full code there and call from another class if I need. How do we do simply ?

I have put Interstitial ad on Activity like this

public class Cover extends AppCompatActivity{
public static String DEFAULT = "en";
InterstitialAd mInterstitialAd;
AdRequest adRequest;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-xxx-xxx-xxx");
adRequest = new AdRequest.Builder().addTestDevice("0F7B337499FCAAA05252B09EFC57223C").build();
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
showInterstitial();
}
});

}

private void showInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}


Any help would be appreciated!! ;)

Answer

create a new helper class class:

public class AdsHelper() {

static InterstitialAd mInterstitialAd;
static AdRequest adRequest;

public static showAd(Activity activity) {
    mInterstitialAd = new InterstitialAd(activity);
    mInterstitialAd.setAdUnitId("ca-app-pub-xxx-xxx-xxx");
    adRequest = new AdRequest.Builder().addTestDevice("0F7B337499FCAAA05252B09EFC57223C").build();
    mInterstitialAd.loadAd(adRequest);
    mInterstitialAd.setAdListener(new AdListener() {
        public void onAdLoaded() {
            showInterstitial();
        }
    });

}

public static void showInterstitial() {
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    }
}

and use it in your 2 activities:

public class Cover extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AdHelper.showAd(this); // this will show the ad
}
Comments