Bob Richardson
Bob Richardson

Reputation: 51

android logic error with embedding an adView within a listview fragment - latest admob sdk - revised using XML and Java

I finally got my ad working within my ListView fragment but now I am getting a strange logic error. The issue appears to be with tracking the position of the ad (position 0) and the rest of the items on the list. The first item is replaced by the add and after clicking on any item on the list to make an update, then returning back to the list of items. The list names appear to be out of order.

The following is a revision that I did using the adMob XML code with the few lines of java in my ListFragment class,

My XML code is as follows:

  <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      >
    <LinearLayout 
      android:id="@+id/adsContainer"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"/>
    <com.google.android.gms.ads.AdView
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/adView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      ads:adUnitId="ca-app-pub-9999999999999999999999999"
      ads:adSize="BANNER"/>
    <ListView
      android:id="@android:id/list"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      >
     </ListView>
     <ListView
       android:id="@android:id/empty"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:paddingLeft="4dp"
       android:paddingRight="4dp"
       android:text="@string/new_empty_desc" 
      >
      </ListView>
</

In my class public class BxListFragment extends SherlockListFragment :

import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdRequest.Builder; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.doubleclick.PublisherAdRequest; import com.google.android.gms.ads.doubleclick.PublisherAdView; import com.google.android.gms.drive.query.internal.InFilter; import com.robertrichardson.bxxxyxxxxzxxxLite.R.string;

/* * BxiedListFragment Class: Sets up and displays all Bxied Activity on the list. */

public class BxiedListFragment extends SherlockListFragment {

  private ArrayList<Bxied> mBxied;
  private boolean mSubtitleVisible;
  private LayoutInflater inflater;
  private PostData[] datas;

  private Activity mainActivity;

  private static final String AD_UNIT_ID = "ca-app-pub-4409647944042499/8301167762";

  public static final String TAG = "BxiedListFragment";
  private AdView adView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setHasOptionsMenu(true);
      getSherlockActivity().setTitle(R.string.app_name);
      mBxied = BxiedLab.get(getSherlockActivity()).getBxied();
      BxiedAdapter adapter = new BxiedAdapter(mBxied);
      setListAdapter(adapter);
      setRetainInstance(true);
      mSubtitleVisible = false;

      }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
      super.onViewCreated(view,  savedInstanceState);

      setEmptyText(getResources().getString(string.new_bxied_attack_empty_desc));

      registerForContextMenu(getListView());
      setHasOptionsMenu(true);
  } 

  @TargetApi(11)
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent,
          Bundle savedInstanceState) {

        View v = super.onCreateView(inflater,  parent,  savedInstanceState);

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
          if (mSubtitleVisible) {
              getSherlockActivity().getSupportActionBar().setSubtitle(R.string.subtitle);
          }
      }

      ListView listView = (ListView)v.findViewById(android.R.id.list);

      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {

          // Use floating point context menus on Froyer and Gingerbread
          registerForContextMenu(listView);

      } else {

          // Use contextual action bar on Honeycomb and higher
          listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
          listView.setMultiChoiceModeListener(new MultiChoiceModeListener()  {

              public boolean onActionItemClicked(
                      android.view.ActionMode arg0, android.view.MenuItem arg1) {
                  // TODO Auto-generated method stub
                  return false;
              }


              public boolean onCreateActionMode(android.view.ActionMode mode,
                      android.view.Menu menu) {
                  // TODO Auto-generated method stub
                  return false;
              }

              public void onDestroyActionMode(android.view.ActionMode mode) {
                  // TODO Auto-generated method stub

              }
              public boolean onPrepareActionMode(
                      android.view.ActionMode mode, android.view.Menu menu) {
                  // TODO Auto-generated method stub
                  return false;
              }

              public void onItemCheckedStateChanged(
                      android.view.ActionMode mode, int position, long id,
                      boolean checked) {
                  // TODO Auto-generated method stub
              }

          // ActionMode.Callback methods
      }); 
  }
         return v;

}

  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {
      Bxied c = ((BxiedAdapter)getListAdapter()).getItem(position);
      // Start Bxied Activity
      Intent i = new Intent(getSherlockActivity(), BxiedPagerActivity.class);
      i.putExtra(BxiedFragment.EXTRA_BULLIED_ID, c.getId());
      startActivityForResult(i, 0);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
      ((BxiedAdapter)getListAdapter()).notifyDataSetChanged();
  }

  @Override
  public void onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu, MenuInflater inflater) {
      super.onCreateOptionsMenu(menu, inflater);
      inflater.inflate(R.menu.fragment_bxied_list, menu);
   }

@TargetApi(11) @Override public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) { switch (item.getItemId()) { case R.id.settings: Intent i=new Intent(getSherlockActivity(), Preferences.class); startActivity(i); return(true); case R.id.about: i=new Intent(getSherlockActivity(),BxiedContentActivity.class); i.putExtra(BxiedContentActivity.EXTRA_FILE, "file:///android_asset/misc/about.html"); startActivity(i); return(true); case R.id.help: i=new Intent(getSherlockActivity(),BxiedContentActivity.class); i.putExtra(BxiedContentActivity.EXTRA_FILE, "file:///android_asset/misc/help.html"); startActivity(i); return(true); case R.id.disclaimer: i=new Intent(getSherlockActivity(),BxiedContentActivity.class); i.putExtra(BxiedContentActivity.EXTRA_FILE, "file:///android_asset/misc/disclaimer.html"); startActivity(i); return(true); case R.id.menu_item_new_bxied: Bxied bxied = new Bxied(); BxiedLab.get(getSherlockActivity()).addBxied(bxied); i = new Intent(getSherlockActivity(), BxiedPagerActivity.class); i.putExtra(BxiedFragment.EXTRA_BULLIED_ID, bxied.getId()); startActivityForResult(i,0); return true; default: return super.onOptionsItemSelected(item); } }

  @Override
  public void onCreateContextMenu(ContextMenu menu,View v, ContextMenuInfo menuInfo) {
      getActivity().getMenuInflater().inflate(R.menu.bxied_list_item_context, menu);
  }

  @Override
  public boolean onContextItemSelected(android.view.MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
      int position = info.position;
      BxiedAdapter adapter = (BxiedAdapter)getListAdapter();
      Bxied bxied = adapter.getItem(position);

      switch (item.getItemId()) {
         case R.id.menu_item_delete_bxied:
             BxiedLab.get(getActivity()).deleteBxied(bxied);
             adapter.notifyDataSetChanged();
             return true;
      }
      return super.onContextItemSelected(item);
  }

  private class BxiedAdapter extends ArrayAdapter<Bxied> {
      public BxiedAdapter(ArrayList<Bxied> bxied) {
          super(getSherlockActivity(), android.R.layout.simple_list_item_1, bxied);
      }    

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
       Log.i("1", "msg1");

      // If we weren't given a view, inflate one
      if (convertView == null) {
          convertView = getSherlockActivity().getLayoutInflater()
                  .inflate(R.layout.list_item_bxied, null);
      }  

      // Enter the view of this Bxied Attack
      Bxied c = getItem(position);

      TextView titleTextView =
              (TextView)convertView.findViewById(R.id.bxied_list_item_titleTextView);
      titleTextView.setText(c.getTitle());
      TextView dateTextView =
              (TextView)convertView.findViewById(R.id.bxied_list_item_dateTextView);
      dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy  hh : mm a", c.getDate()).toString());

      CheckBox resolvedCheckBox =
              (CheckBox)convertView.findViewById(R.id.bxied_list_item_resolvedCheckBox);
      resolvedCheckBox.setChecked(c.isResolved());
      return convertView;
  }

}

   @Override
  public void onResume() {
      super.onResume();
      ((BxiedAdapter)getListAdapter()).notifyDataSetChanged();
      }
  }

I'm trying to add this piece of code within the above ListFragment. currently I'm getting a syntax error findVuewById(int) undefined. My question is where can I best insert this piece of code om my listfragment to place the ads in the above XML?

  /*
   * New ads Logic    
   */

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

      AdRequest adRequest = new AdRequest.Builder()
          .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
          .addTestDevice("TEST_DEVICE_ID")
          .build();

      adView.loadAd(adRequest);

Upvotes: 3

Views: 1418

Answers (3)

Bob Richardson
Bob Richardson

Reputation: 51

FYI - I finally figured it out. I ended up with correctly inserting all the ads logic in my GetView with the ads posted on top

The following is my code:

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
        if (position == 0)  {
            if (convertView instanceof AdView) {
       // Don’t instantiate new AdView, reuse old one
                return convertView;
        } else {
              Context mainActivity = getActivity();
          adView = new AdView(mainActivity);
          adView.setAdUnitId("ca-app-pub-9999998888888888");
          adView.setAdSize(AdSize.BANNER);                    
       // Convert the default layout parameters so that they play nice with
       // ListView.
          float density = mainActivity.getResources().getDisplayMetrics().density;
          int height = Math.round(AdSize.BANNER.getHeight() * density);
          AbsListView.LayoutParams params = new AbsListView.LayoutParams(
          AbsListView.LayoutParams.FILL_PARENT,
          height);
          adView.setLayoutParams(params);
          AdRequest adRequest = new AdRequest.Builder()
              .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
              .addTestDevice("TEST_DEVICE_ID")
              .build();
          adView.loadAd(adRequest);
          }
          convertView = adView;
         } else {
          convertView = getSherlockActivity().getLayoutInflater()
              .inflate(R.layout.list_item_bxied,null);
              // Enter the view of this Bxlied Attack
              // If we weren't given a view, inflate one
              // Enter the view of this Bxlied Attack

          Bxlied c = getItem(position);
          TextView titleTextView =
               (TextView)convertView.findViewById(R.id.bxied_list_item_titleTextView);
          titleTextView.setText(c.getTitle());
          TextView dateTextView =
               (TextView)convertView.findViewById(R.id.bxied_list_item_dateTextView);
          dateTextView.setText(DateFormat.format("EEEE, MMM dd, yyyy  hh : mm a", c.getDate()).toString());
          CheckBox resolvedCheckBox =
               (CheckBox)convertView.findViewById(R.id.bxied_list_item_resolvedCheckBox);
          resolvedCheckBox.setChecked(c.isResolved());
          }
          return convertView;
       }
    }

Upvotes: 0

William
William

Reputation: 20196

I think you are asking "where should I place the code that loads the ad?".

If so then you want to add the following code to your ListFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  AdView adView = (AdView)this.findViewById(R.id.adView);

  AdRequest adRequest = new AdRequest.Builder()
      .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
      .addTestDevice("TEST_DEVICE_ID")
      .build();

  adView.loadAd(adRequest);

  ...
}

Upvotes: 0

ProjectJourneyman
ProjectJourneyman

Reputation: 3606

The problem might be related to making 0 a special case, but having a data source also have a zero element. The list and adapter are no longer aligned.

Putting the ad view in a header might work. See here: https://developer.android.com/reference/android/widget/ListView.html#addHeaderView%28android.view.View,%20java.lang.Object,%20boolean%29

Upvotes: 0

Related Questions