Android: Problem with Google Admob sample

孤街浪徒 提交于 2019-12-12 06:58:45

问题


I'm trying to create a sample admob application with just the bare essentials. I followed the directions and even copied most of the code from this site: http://code.google.com/mobile/ads/docs/android/fundamentals.html, but the app keeps force closing on my VD and on my real device. The debugger gives a "RuntimeException" at the line: layout.addView(adview). I'm sure there is a simple solution to this, but I can't figure it out. I've searched around, but most of the information online is for pre-google admob - which used a different procedure.

Here is my MainActivity (my only Activity):

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Create the adView
    AdView adView = new AdView(this, AdSize.BANNER, "a14dc6ed8aead31");
    LinearLayout layout = (LinearLayout)findViewById(R.layout.main);
    layout.addView(adView); //RuntimeException at this line
    AdRequest request = new AdRequest();
    request.setTesting(true);
    adView.loadAd(request);
}

Heres my logcat error output:

05-22 17:49:24.534: ERROR/AndroidRuntime(19619): Caused by: java.lang.NullPointerException

05-22 17:49:24.534: ERROR/AndroidRuntime(19619): at com.example.admobsample.MainActivity.onCreate(MainActivity.java:22)

05-22 17:49:24.534: ERROR/AndroidRuntime(19619): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

05-22 17:49:24.534: ERROR/AndroidRuntime(19619): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544)

05-22 17:49:24.534: ERROR/AndroidRuntime(19619): ... 11 more

05-22 17:49:26.024: ERROR/PackageInstallationReceiver(17825): Remove /data/local/tmp/com.example.admobsample.apk Fail!


回答1:


The NPE happens because layout is null, i.e., there is no view with the ID R.layout.main.

Interpreting the original example

    // Lookup your LinearLayout assuming it’s been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);

you need to add the attribute android:id to your LinearLayout (the ID should be different from R.id.main).




回答2:


Once you fix your NPE error you may get a further error.

You have to set a layouts height and width before adding it to a view.

AdView adView = new AdView(this, AdSize.BANNER, "a14dc6ed8aead31");
adView .setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
LinearLayout layout = (LinearLayout)findViewById(R.id.layoutMain);
layout.addView(adView);


来源:https://stackoverflow.com/questions/6089130/android-problem-with-google-admob-sample

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!