Android: Problem with Google Admob sample

2019-09-04 19:16发布

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!

标签: android admob
2条回答
做个烂人
2楼-- · 2019-09-04 19:47

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).

查看更多
Emotional °昔
3楼-- · 2019-09-04 19:55

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);
查看更多
登录 后发表回答