Last active
April 18, 2016 19:59
-
-
Save amitprabhudesai/41011a75582ce5c3374d0aae822c639c to your computer and use it in GitHub Desktop.
InMobi Native ads integration sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.inmobi.samples.nativeads; | |
import android.annotation.TargetApi; | |
import android.app.Activity; | |
import android.app.AlertDialog; | |
import android.app.ProgressDialog; | |
import android.content.Context; | |
import android.content.DialogInterface; | |
import android.net.Uri; | |
import android.os.Build; | |
import android.os.Bundle; | |
import android.support.v4.app.ListFragment; | |
import android.support.v4.app.LoaderManager; | |
import android.support.v4.content.Loader; | |
import android.util.Log; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.AdapterView; | |
import android.widget.ArrayAdapter; | |
import android.widget.ListView; | |
import android.widget.TextView; | |
import com.facebook.drawee.view.SimpleDraweeView; | |
import com.inmobi.ads.InMobiAdRequestStatus; | |
import com.inmobi.ads.InMobiNative; | |
import com.inmobi.samples.R; | |
import com.inmobi.samples.utils.AdBuilder; | |
import com.inmobi.samples.utils.ContentBuilder; | |
import com.inmobi.samples.utils.ContentItem; | |
import com.inmobi.samples.utils.ContentLoader; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import java.lang.ref.WeakReference; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
public class NewsHeadlinesFragment extends ListFragment implements LoaderManager.LoaderCallbacks<List<ContentItem>> { | |
private static final String TAG = NewsHeadlinesFragment.class.getSimpleName(); | |
private static final int MAX_ADS = 50; | |
private FeedAdapter mAdapter; | |
private ProgressDialog mProgressDialog; | |
private Map<ContentItem, WeakReference<InMobiNative>> mNativeAdMap = new HashMap<>(); | |
private InMobiNative[] mNativeAds = new InMobiNative[MAX_ADS]; | |
private static final String FEED_URL = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=30&q=http://rss.nytimes.com/services/xml/rss/nyt/World.xml"; | |
private static final String FALLBACK_IMAGE_URL = "http://www.darrickbynum.com/wp-content/uploads/2014/07/News729x6581.jpg"; | |
private static final int[] AD_PLACEMENT_POSITIONS = new int[]{2, 4, 8, 13, 21}; | |
private static final long YOUR_PLACEMENT_ID = /*123456789L*/; | |
private OnHeadlineSelectedListener mCallback; | |
private final AdBuilder mAdBuilder = new AdBuilder(); | |
private final ContentBuilder mNewsHeadlinesBuilder = new NewsHeadlinesBuilder(); | |
public interface OnHeadlineSelectedListener { | |
void onArticleSelected(int position); | |
} | |
@Override | |
public Loader<List<ContentItem>> onCreateLoader(int id, Bundle args) { | |
mProgressDialog = ProgressDialog.show(getActivity(), | |
"Loading", "Getting news headlines"); | |
return new ContentLoader(getActivity(), FEED_URL, mNewsHeadlinesBuilder); | |
} | |
@Override | |
public void onLoadFinished(Loader<List<ContentItem>> loader, List<ContentItem> data) { | |
if (mProgressDialog != null) { | |
mProgressDialog.dismiss(); | |
} | |
mAdapter.setData(data); | |
placeNativeAds(); | |
} | |
@Override | |
public void onLoaderReset(Loader<List<ContentItem>> loader) { | |
mAdapter.setData(null); | |
} | |
private void placeNativeAds() { | |
Log.d(TAG, "Requesting ads ..."); | |
for (int i = 0; i < AD_PLACEMENT_POSITIONS.length; i++) { | |
final int position = AD_PLACEMENT_POSITIONS[i]; | |
InMobiNative nativeAd = new InMobiNative(YOUR_PLACEMENT_ID, new InMobiNative.NativeAdListener() { | |
@Override | |
public void onAdLoadSucceeded(final InMobiNative inMobiNative) { | |
ContentItem item = mAdapter.getItem(position); | |
WeakReference<InMobiNative> nativeAdRef = mNativeAdMap.get(item); | |
if (null == nativeAdRef) { | |
try { | |
ContentItem ad = mAdBuilder.build(new JSONObject((String) inMobiNative.getAdContent())); | |
mAdapter.insert(ad, position); | |
mNativeAdMap.put(ad, new WeakReference<>(inMobiNative)); | |
mAdapter.notifyDataSetChanged(); | |
Log.d(TAG, "Placed ad unit (" + inMobiNative.hashCode() + | |
") at position " + position); | |
} catch (JSONException e) { | |
Log.e(TAG, e.toString()); | |
} | |
} | |
} | |
@Override | |
public void onAdLoadFailed(InMobiNative inMobiNative, InMobiAdRequestStatus inMobiAdRequestStatus) { | |
Log.e(TAG, "Failed to load ad. " + inMobiAdRequestStatus.getMessage()); | |
} | |
@Override | |
public void onAdDismissed(InMobiNative inMobiNative) { | |
} | |
@Override | |
public void onAdDisplayed(InMobiNative inMobiNative) { | |
} | |
@Override | |
public void onUserLeftApplication(InMobiNative inMobiNative) { | |
} | |
}); | |
nativeAd.load(); | |
mNativeAds[i] = nativeAd; | |
} | |
} | |
@Override | |
public void onAttach(Activity activity) { | |
super.onAttach(activity); | |
try { | |
mCallback = (OnHeadlineSelectedListener) activity; | |
} catch (ClassCastException e) { | |
throw new ClassCastException(activity.toString() | |
+ " must implement OnSettingsSavedListener"); | |
} | |
} | |
@Override | |
public void onResume() { | |
super.onResume(); | |
for (InMobiNative nativeAd : mNativeAds) { | |
if (nativeAd != null) { | |
nativeAd.resume(); | |
} | |
} | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
mAdapter = new FeedAdapter(getActivity()); | |
setListAdapter(mAdapter); | |
return super.onCreateView(inflater, container, savedInstanceState); | |
} | |
@Override | |
public void onActivityCreated(Bundle savedInstanceState) { | |
super.onActivityCreated(savedInstanceState); | |
getLoaderManager().initLoader(0, null, this); | |
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { | |
@Override | |
public boolean onItemLongClick(final AdapterView<?> adapterView, final View view, final int position, final long id) { | |
AlertDialog.Builder confirmationDialog = new AlertDialog.Builder(getActivity()); | |
confirmationDialog.setTitle("Delete Item?"); | |
confirmationDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
FeedAdapter adapter = (FeedAdapter) adapterView.getAdapter(); | |
adapter.remove(adapter.getItem(position)); | |
adapter.notifyDataSetChanged(); | |
} | |
}); | |
confirmationDialog.setNegativeButton("No", new DialogInterface.OnClickListener() { | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
dialog.cancel(); | |
} | |
}); | |
confirmationDialog.show(); | |
return true; | |
} | |
}); | |
} | |
@Override | |
public void onPause() { | |
for (InMobiNative nativeAd: mNativeAds) { | |
if (nativeAd != null) { | |
nativeAd.pause(); | |
} | |
} | |
super.onPause(); | |
} | |
@Override | |
public void onDetach() { | |
mCallback = null; | |
mNativeAdMap.clear(); | |
super.onDetach(); | |
} | |
@Override | |
public void onListItemClick(ListView l, View v, int position, long id) { | |
mCallback.onArticleSelected(position); | |
ContentItem contentItem = ((FeedAdapter) l.getAdapter()).getItem(position); | |
final WeakReference<InMobiNative> nativeAdRef = mNativeAdMap.get(contentItem); | |
if (nativeAdRef != null && nativeAdRef.get() != null) { | |
nativeAdRef.get().reportAdClickAndOpenLandingPage(null); | |
} | |
getListView().setItemChecked(position, true); | |
} | |
class ViewHolder { | |
TextView headline; | |
TextView content; | |
TextView tag; | |
SimpleDraweeView icon; | |
} | |
public class FeedAdapter extends ArrayAdapter<ContentItem> { | |
private LayoutInflater mInflater; | |
public FeedAdapter(Context context) { | |
super(context, R.layout.news_headline_view); | |
mInflater = LayoutInflater.from(context); | |
} | |
@TargetApi(Build.VERSION_CODES.HONEYCOMB) | |
public void setData(List<ContentItem> items) { | |
clear(); | |
if (items != null) { | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { | |
addAll(items); | |
} | |
} | |
} | |
@Override | |
public View getView(int position, View convertView, ViewGroup parent) { | |
View rowView = convertView; | |
if (null == rowView) { | |
rowView = mInflater.inflate(R.layout.news_headline_view, parent, false); | |
ViewHolder viewHolder = new ViewHolder(); | |
viewHolder.headline = (TextView) rowView.findViewById(R.id.caption); | |
viewHolder.content = (TextView) rowView.findViewById(R.id.content); | |
viewHolder.icon = (SimpleDraweeView) rowView.findViewById(R.id.photo); | |
viewHolder.tag = (TextView) rowView.findViewById(R.id.sponsored); | |
rowView.setTag(viewHolder); | |
} | |
final ContentItem contentItem = getItem(position); | |
ViewHolder holder = (ViewHolder) rowView.getTag(); | |
holder.headline.setText(contentItem.getTitle()); | |
holder.content.setText(contentItem.getContent()); | |
holder.icon.setImageURI(Uri.parse(contentItem.getImageUrl())); | |
WeakReference<InMobiNative> nativeAdRef = mNativeAdMap.get(contentItem); | |
if (null == nativeAdRef) { | |
holder.tag.setVisibility(View.GONE); | |
InMobiNative.unbind(rowView); | |
} else { | |
// we have an ad at this position | |
InMobiNative nativeAd = nativeAdRef.get(); | |
if (nativeAd != null) { | |
holder.tag.setVisibility(View.VISIBLE); | |
holder.tag.setText(R.string.default_sponsored_text); | |
InMobiNative.bind(rowView, nativeAd); | |
} | |
} | |
return rowView; | |
} | |
} | |
static final class NewsHeadlinesBuilder extends ContentBuilder { | |
@Override | |
public List<ContentItem> toContentItems(JSONObject jsonObject) { | |
List<ContentItem> contentItems = new ArrayList<>(); | |
try { | |
JSONArray feed = jsonObject. | |
getJSONObject("responseData"). | |
getJSONObject("feed"). | |
getJSONArray("entries"); | |
for (int i = 0; i < feed.length(); i++) { | |
contentItems.add(build(feed.getJSONObject(i))); | |
} | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return contentItems; | |
} | |
return contentItems; | |
} | |
@Override | |
public String getTitle(JSONObject item) { | |
try { | |
return item.getString("title"); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return ""; | |
} | |
} | |
@Override | |
public String getImageUrl(JSONObject item) { | |
try { | |
if (item.isNull("mediaGroups")) { | |
return FALLBACK_IMAGE_URL; | |
} else { | |
return item.getJSONArray("mediaGroups") | |
.getJSONObject(0) | |
.getJSONArray("contents") | |
.getJSONObject(0) | |
.getString("url"); | |
} | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return ""; | |
} | |
} | |
@Override | |
public String getContentBody(JSONObject item) { | |
try { | |
return item.getString("contentSnippet"); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return ""; | |
} | |
} | |
@Override | |
public String getLandingPageUrl(JSONObject item) { | |
try { | |
return item.getString("link"); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
return ""; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment