简体   繁体   中英

NullObjectReference for Admob in different activities

I had read a few q&a in stackoverflow, but still not able to get it work. Admob on Multiple Activities?

Similar to above solutions, I got the below error

android.content.res.Resources android.content.Context.getResources()' on a null object reference

in this line

 AdView adView = new AdView(this);

Can anyone find out why it happens?

CommonCode.java

public class CommonCode extends AppCompatActivity{
//private AdView mAdView;

public void createAdview(){
    AdView adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
}}

MainActivity.java

public class MainActivity extends AppCompatActivity {

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

    CommonCode cc = new CommonCode();
    cc.createAdview();}}

You extends AppCompatActivity in CommonCode that define CommonCode as an Activity.Activity context is null untill it start. You need to remove extnds AppCompatActivity from CommonCode class and pass the context in a parameter as below :

public class CommonCode{

    public void createAdview(Context context){
        AdView adView = new AdView(context);
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
    }
}

Now in a MainActivity you need to call the method like this :

public class MainActivity extends AppCompatActivity {

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

        CommonCode cc = new CommonCode();
        cc.createAdview(this);
    }
}

You need to pass activity context in this line

AdView adView = new AdView(this);

Create common class like this

public class CommonCode {
public CommonCode (){
}
public void createAdview(Context context){
AdView adView = new AdView(context);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}}

And use it like this in your activity

CommonCode cc = new CommonCode();
cc.createAdview(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM