2014-03-29 143 views
1

我有此活動 - 包括加載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> 

我應該聲明一些東西嗎?請給我一個線索!

回答

1

不要嘗試添加里面的AdView一個AdView作爲ListView中的一個元素。這是一個痛苦的祕訣,因爲它會與其他不同需求的產品完全不同。

將它作爲自己的元素添加到您的ListView的上方或下方。

而是創建一個的LinearLayout高於或你的ListView以下

<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); 
+0

現在的應用程序沒有任何錯誤運行,但廣告仍然沒有顯示... – chility

+0

NVM,它現在完美運行!謝謝您的幫助!!! – chility

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

你不能添加一個視圖適配器視圖