无法显示横幅

时间:2014-03-29 18:03:00

标签: java android android-activity admob

我有此活动 - 包括加载admob横幅广告所需的代码。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.gs.britishjokes.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AllJokes extends Activity {

    public static ArrayAdapter<String> adapter;
    public static ListView listView;
     private AdView adView;

      /* Your ad unit id. Replace with your actual ad unit id. */
      private static final String AD_UNIT_ID = "ca-app-pub-codehere/code";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_jokes);        

        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(AD_UNIT_ID);

        // Add the AdView to the view hierarchy. The view will have no size
        // until the ad is loaded.
        ListView layout = (ListView) findViewById(R.id.allJokesList);
        layout.addView(adView);

        // Create an ad request. Check logcat output for the hashed device ID to
        // get test ads on a physical device.
        AdRequest adRequest = new AdRequest.Builder()
//          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
//          .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
            .build();

        // Start loading the ad in the background.
        adView.loadAd(adRequest);

        final GlobalsHolder globals = (GlobalsHolder)getApplication();

//      if(globals.isLoaded == false){ SETJOKESNAMELIST MAI SE POLZVA OT DRUGO ACTIVITY!!!! ZATOVA IZLIZA PRAZNO SLED PROVERKATA!
            new loadJson().execute();
//      }
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
        adapter.clear();
        adapter.addAll(globals.getMyStringArray());

        listView = (ListView) findViewById(R.id.allJokesList);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                globals.setClickedJokeName((String) ((TextView) view).getText());
                openJokeBody(view);

                globals.setClickedPosition(position);

                // When clicked, shows a toast with the TextView text
                Toast.makeText(getApplicationContext(),
                ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
            }
        });

    }
     @Override
      public void onResume() {
        super.onResume();
        if (adView != null) {
          adView.resume();
        }
      }

      @Override
      public void onPause() {
        if (adView != null) {
          adView.pause();
        }
        super.onPause();
      }

      /** Called before the activity is destroyed. */
      @Override
      public void onDestroy() {
        // Destroy the AdView.
        if (adView != null) {
          adView.destroy();
        }
        super.onDestroy();
      }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.all_jokes, menu);
        return true;
    }

    public class loadJson extends AsyncTask<Void, Integer, String[]>{

        private ProgressDialog Dialog = new ProgressDialog(AllJokes.this);

        @Override
        protected void onPreExecute()
        {
            Dialog.setMessage("Fetching the latest jokes!");
            Dialog.show();
        }

        @Override
        protected String[] doInBackground(Void... params) {
            /*Getting the joke names JSON string response from the server*/
            URL u;
            StringBuffer buffer = new StringBuffer();
            StringBuffer buffer2 = new StringBuffer();
            try {
                u = new URL("https://site.com/android/Jokes/showJokes.php?JokeCat=allJokes");
                URLConnection conn = u.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String inputLine;
                while ((inputLine = in.readLine()) != null) 
                    buffer.append(inputLine);
                in.close();         
            }catch(Exception e){
                e.printStackTrace();
            }
            try {
                u = new URL("https://site.com/android/Jokes/showJokesBody.php?JokeCat=allJokes");
                URLConnection conn = u.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                String inputLine;
                while ((inputLine = in.readLine()) != null) 
                    buffer2.append(inputLine);
                in.close();         
            }catch(Exception e){
                e.printStackTrace();
            }
//          return buffer.toString(); ako se naloji da vurna - da pogledna tva return4e
            return new String[]{buffer.toString(), buffer2.toString()};
        }

        @SuppressLint("NewApi")
        protected void onPostExecute(String[] buffer) {
            final GlobalsHolder globals = (GlobalsHolder)getApplication();
            JSONArray jsonArray = new JSONArray();
            JSONArray jsonArray1 = new JSONArray();
            try {
                jsonArray = new JSONArray(buffer[0]);
                jsonArray1 = new JSONArray(buffer[1]);
            } catch (JSONException e) {
                e.printStackTrace();
            }           
       /*Looping trough the results and adding them to a list*/
        ArrayList<String> list = new ArrayList<String>();     
        ArrayList<String> list1 = new ArrayList<String>();   
        if (jsonArray != null) { 
           int len = jsonArray.length();
           for (int i=0;i<len;i++){ 
            try {
                list.add(jsonArray.get(i).toString());
                globals.setJokeNamesList(list);
            } catch (JSONException e) {
                e.printStackTrace();
            }
          } 
        }

        if (jsonArray != null) { 
               int len = jsonArray1.length();
               for (int i=0;i<len;i++){ 
                try {
                    list1.add(jsonArray1.get(i).toString());
                    globals.setList(list1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
              } 
            } 
           /* Redrwawing the view */
             adapter.clear();
             adapter.addAll(list);      
             Dialog.dismiss();
             globals.setLoaded(true);
         }

    }

    /*This method opens the new activity - TopJokesBody when a joke name from the list is clicked*/
    public void openJokeBody(View view) {
        Intent intent = new Intent(this, AllJokesBody.class);
        startActivity(intent);
    }   

}

这是我的第一次尝试,我已经坚持了。 Logcat浪费了大量的例外,说实话,我无法理解我做错了什么。

这里的例外是:

03-29 13:55:37.713: E/AndroidRuntime(1750): FATAL EXCEPTION: main
03-29 13:55:37.713: E/AndroidRuntime(1750): Process: com.gs.britishjokes, PID: 1750
03-29 13:55:37.713: E/AndroidRuntime(1750): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gelasoft.britishjokes.AllJokes}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.os.Looper.loop(Looper.java:136)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.ActivityThread.main(ActivityThread.java:5017)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at java.lang.reflect.Method.invoke(Method.java:515)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at dalvik.system.NativeStart.main(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.widget.AdapterView.addView(AdapterView.java:452)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at com.gelasoft.britishjokes.AllJokes.onCreate(AllJokes.java:55)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.Activity.performCreate(Activity.java:5231)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-29 13:55:37.713: E/AndroidRuntime(1750):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-29 13:55:37.713: E/AndroidRuntime(1750):     ... 11 more

我确定我错过了xml布局文件中的内容,但我无法将其视为初学者。

聚苯乙烯。这里的布局是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".AllJokes" >

    <ListView
              android:id="@+id/allJokesList"
              android:layout_height="wrap_content"
              android:layout_width="match_parent">
    </ListView>

</RelativeLayout>

我应该在其中声明一些内容吗?请给我一个线索!

3 个答案:

答案 0 :(得分:2)

Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView   

您无法向adapterview添加视图

答案 1 :(得分:2)

你的问题是

ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);

您需要在适配器中添加adView http://googleadsdeveloper.blogspot.co.il/2012/03/embedding-admob-ads-within-listview-on.html

答案 2 :(得分:1)

请勿尝试将AdView添加为ListView中的元素。这是一个痛苦的食谱,因为它将与您的其他需求不同的项目完全不同。

在ListView的上方或下方添加它自己的元素。

而是在ListView

之上或之下创建LinearLayout
<LinearLayout android:id="@+id/adViewContainer
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
/>

然后将onCreate的这一部分更改为

// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
final ViewGroup adViewContainer = (ViewGroup) findViewById(R.id.adViewContainer);
adViewContainer.addView(adView);