在mainactivity.java上添加admob横幅代码后,我的应用程序崩溃了

时间:2018-07-26 23:55:40

标签: java android

这是 mainactivity.java 上的完整代码,我添加了这个代码:

mAdView = (AdView)findViewById(R.id.adView);

AdRequest adRequest = new AdRequest.Builder().build();

mAdView.loadAd(adRequest);

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Toast;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;


import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity  {



    DrawerLayout drawerLayout;
    Toolbar toolbar;
    ActionBarDrawerToggle actionBarDrawerToggle;
    NavigationView navigationView;
    RecyclerView recyclerView;
    LinearLayoutManager manager;
    PostAdapter adapter;
    List<Item> items = new ArrayList<>();
    Boolean isScrolling = false;
    int currentItems, totalItems, scrollOutItems;
    String token = "";
    SpinKitView progress;
    AdView mAdView;

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

        mAdView = (AdView)findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        recyclerView = (RecyclerView) findViewById(R.id.postList);
        manager = new LinearLayoutManager(this);
        adapter = new PostAdapter(this, items);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        progress = (SpinKitView) findViewById(R.id.spin_kit);



setUpToolbar();
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                int id = item.getItemId();

              switch (id) {

                  case R.id.nav_home:

                      break;
                  case R.id.nav_aboute: {
                      Intent intent = new Intent(MainActivity.this, aboutus.class);
                      startActivity(intent);
                      break;
                  }
                  case R.id.nav_contact: {
                      Intent intent = new Intent(MainActivity.this, contactus.class);
                      startActivity(intent);
                      break;
                  }
                  case R.id.nav_share:
                      String shareBody = getString(R.string.app_name) + " " + getString(R.string.url_app_google_play);
                      Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                      sharingIntent.setType("text/plain");
                      sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
                      sharingIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
                      startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.app_name)));
                      break;
              }
              return true;

          }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL)
            {
                isScrolling = true;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            currentItems = manager.getChildCount();
            totalItems = manager.getItemCount();
            scrollOutItems = manager.findFirstVisibleItemPosition();

            if(isScrolling && (currentItems + scrollOutItems == totalItems))
            {
                isScrolling = false;
                getData();
            }
        }


    });
    getData();
    }
    private void setUpToolbar()
    {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout, toolbar,R.string.app_name, R.string.app_name);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();


    }



    private void getData()
    {
        String url = BloggerAPI.url + "?key=" + BloggerAPI.key;
        if(token != ""){
            url = url+ "&pageToken="+ token;
        }
        if(token == null){
            return;
        }
        progress.setVisibility(View.VISIBLE);
        final Call<PostList> postList = BloggerAPI.getService().getPostList(url);
        postList.enqueue(new Callback<PostList>() {
            @Override
            public void onResponse(Call<PostList> call, Response<PostList> response) {
                PostList list = response.body();
                token = list.getNextPageToken();
                items.addAll(list.getItems());
                adapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
                progress.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<PostList> call, Throwable t) {
                Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
            }


        });

        }

}

这是xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hasry.ga.DetailActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_alignParentStart="true">

    </android.support.v7.widget.Toolbar>

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/detailView"
        android:layout_below="@id/toolbar" />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:id="@+id/progressBar"/>

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"
        android:layout_alignParentBottom="true"
        >
    </com.google.android.gms.ads.AdView>
</RelativeLayout>

字符串文件

<string name="banner_ad_unit_id">ca-app-pub-xxxxxxxxxxxxx</string>

我还添加了 build.gradle

implementation "com.google.android.gms:play-services-ads:15.0.1"

启动屏幕后应用程序崩溃的问题在哪里?

4 个答案:

答案 0 :(得分:0)

您忘记了在初始化 AdRequest

之前将此行添加到 onCreate()
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");

有关正确的指导,请参见下文。

https://firebase.google.com/docs/admob/android/quick-start

答案 1 :(得分:0)

我发现了错误

E/FA: Task exception on worker thread: java.lang.IllegalStateException: The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 12451000 but found 7095000.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />: com.google.android.gms.internal.measurement.zzik.zzdf(Unknown Source)

以及我发现将此代码添加到清单中的解决方案

<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

谢谢大家的帮助

答案 2 :(得分:0)

从应用gradle文件中更改您的 play-service-ads 版本

implementation 'com.google.android.gms:play-services-ads:16.0.0'

尝试更高或更低的版本会起作用

答案 3 :(得分:-2)

将此代码添加到清单文件中

<meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-2834184685160637~xxxxxx"/>`