0

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();}}
Tony Ming
  • 101
  • 1
  • 1
  • 11

2 Answers2

0

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);
    }
}
Rutvik Bhatt
  • 3,185
  • 1
  • 16
  • 28
  • Wonderful! It works like charm. Thanks a lot Just a questions, why do the case from the link extends activity and can still work in his case? – Tony Ming Jun 04 '18 at 07:45
0

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);
jatin rana
  • 825
  • 1
  • 9
  • 21