我已经在stackoverflow中阅读了一些q& a,但仍然无法使其正常工作。 Admob on Multiple Activities?
与上述解决方案类似,我收到以下错误
android.content.res.Resources android.content.Context.getResources()' on a null object reference
在这一行
AdView adView = new AdView(this);
任何人都可以找出它发生的原因吗?
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();}}
答案 0 :(得分:0)
您将AppCompatActivity
中的CommonCode
扩展为将CommonCode定义为Activity.Activity上下文为null,直到它开始。
您需要从CommonCode类中删除extnds AppCompatActivity
并在参数中传递上下文:
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);
}
}
现在在MainActivity
中你需要调用这样的方法:
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);
}
}
答案 1 :(得分:0)
您需要在此行中传递活动上下文
login_email
像这样创建公共类
AdView adView = new AdView(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);
}}