ListView with customAdapter not updated when notifyDataSetChanged is called? - java

I have a Listview with two adapters. They receive an Array with some data and when scrolled to bottom of the listview more data is loaded into the Array and here the listview should add the new data.
Question:
How can I make the listview reflect the new data and why isn't it updated when I call adAdapter.notifyDataSetChanged(); ?
Fragments inner class where I download data & update UI in onPostExecute:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
// list.setAdapter(adapter); this works when adapter.notifyDataSetChanged(); also is in the else statement but here I don't use the BannerAdListView2 adapter which i want to?
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
// adapter.notifyDataSetChanged(); // Here the listview should get refresh with the new data
adAdapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
// Attach the listener to the AdapterView onCreate
list.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if(pageNumberInt < totalPagesInt){
++incre;
new DownloadJSON().execute();
}
}
});
}
Here is my SearchListViewAdapter:
public class SearchListViewAdapter extends BaseAdapter{
Context context;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> mylist = new HashMap<>();
static String url;
static String title;
public SearchListViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row
final ViewHolder holder;
/*
* If convertView is not null, reuse it directly, no inflation
* Only inflate a new View when the convertView is null.
*/
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_list_item, parent, false);
holder = new ViewHolder();
holder.poster = (ImageView) convertView.findViewById(R.id.list_image);
holder.textForTitle = (TextView) convertView.findViewById(R.id.search_title);
holder.textForTitle.setTag(position);
convertView.setTag(holder);
}
else{
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
holder.textForTitle.setTag(data.get(position));
}
mylist = data.get(position);
final String mediaType = mylist.get("media_type");
if (mediaType.equals("movie")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("title");
} else if (mediaType.equals("tv")) {
String posterPath = mylist.get("poster_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("original_name");
} else {
String posterPath = mylist.get("profile_path");
url = "http://image.tmdb.org/t/p/w185" + posterPath;
title = mylist.get("name");
}
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
// load image url into poster
Picasso.with(context).load(url).into(holder.poster);
// set title to textview
holder.textForTitle.setText(title);
return convertView;
}
class ViewHolder {
ImageView poster;
TextView textForTitle;
}
}
And my BannerAdListView2 adapter:
public class BannerAdListView2 extends BaseAdapter
{
Activity activity;
Context context;
BaseAdapter delegate;
int k = 7;
int baseItems;
int noAds;
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// Total count includes list items and ads.
return baseItems + noAds;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(getOffsetPosition(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + noAds;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
if (position < k) return false;
// Calculate current offset caused by ads already embedded
if (position==k){
return true;
}
else {
return isItemAnAd(position-k);
}
}
// Get the position that is offset by the insertion of the ads
private int getOffsetPosition(int position) {
int currentNoAds = position / k;
return position - currentNoAds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Display every n list items
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
// Don’t instantiate new AdView, reuse old one
return convertView;
} else {
// Create a new AdView
AdView adView = new AdView(activity);
adView.setAdSize(AdSize.BANNER);
String bannerId = "My unit id";
adView.setAdUnitId(bannerId);
// Disable focus for sub-views of the AdView to avoid problems with
// trackpad navigation of the list.
for (int i = 0; i < adView.getChildCount(); i++)
{
adView.getChildAt(i).setFocusable(false);
}
adView.setFocusable(false);
// Convert the default layout parameters so that they play nice with
// ListView.
float density = activity.getResources().getDisplayMetrics().density;
int height = Math.round(AdSize.BANNER.getHeight() * density);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT,
height);
adView.setLayoutParams(params);
AdRequest bannerIntermediateReq = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("d9e108ab") //means that a test ad is shown on my phone
.build();
adView.loadAd(bannerIntermediateReq);
return adView;
}
} else {
// Offload displaying other items to the delegate
return delegate.getView(getOffsetPosition(position) ,
convertView, parent);
}
}
}
Edit:
Changed the constructor of BannerAdListView2
// Constructor takes in a BaseAdapter
public BannerAdListView2(Activity activity, final BaseAdapter delegate ) {
this.activity = activity;
this.delegate = delegate;
delegate.registerDataSetObserver(new DataSetObserver() {
public void onChanged() {
baseItems = delegate.getCount();
noAds = baseItems / k;
}
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
baseItems = delegate.getCount();
noAds = baseItems / k;
LayoutInflater mLayoutInflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
And in fragment
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
list = (ListView) getActivity().findViewById(R.id.search_listview_movie);
adapter = new SearchListViewAdapter(getActivity(), mylist);
adAdapter = new BannerAdListView2(getActivity(), adapter);
list.setAdapter(adAdapter);
bar.setVisibility(View.GONE);
}
else {
adapter.notifyDataSetChanged();
bar.setVisibility(View.GONE);
}
}

Try this solution ... DecorerAdapter:
public static abstract class DecorerAdapter extends BaseAdapter {
public int DECORER_ITEM_TYPE;
private final BaseAdapter mInnerAdapter;
private final int mRepeatAfterEvery;
private int mCount;
public DecorerAdapter(BaseAdapter innerAdapter, int repeatAfterEvery) {
mInnerAdapter = innerAdapter;
mRepeatAfterEvery = repeatAfterEvery;
mInnerAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
});
setupAdapter();
}
#Override
public void notifyDataSetChanged() {
setupAdapter();
super.notifyDataSetChanged();
}
private void setupAdapter(){
mCount = mInnerAdapter.getCount();
mCount += (mCount + mRepeatAfterEvery - 2) / (mRepeatAfterEvery - 1);
DECORER_ITEM_TYPE = mInnerAdapter.getViewTypeCount();
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object getItem(int position) {
if(position % mRepeatAfterEvery == 0)
return null;
return mInnerAdapter.getItem(calculateInnerPosition(position));
}
private int calculateInnerPosition(int position) {
return position - (position + mRepeatAfterEvery - 1) / mRepeatAfterEvery;
}
#Override
public long getItemId(int position) {
if(position % mRepeatAfterEvery == 0)
return -1;
return mInnerAdapter.getItemId(calculateInnerPosition(position));
}
#Override
public int getItemViewType(int position) {
if(position % mRepeatAfterEvery == 0)
return DECORER_ITEM_TYPE;
return mInnerAdapter.getItemViewType(calculateInnerPosition(position));
}
#Override
public boolean hasStableIds() {
return mInnerAdapter.hasStableIds();
}
#Override
public int getViewTypeCount() {
return mInnerAdapter.getViewTypeCount() + 1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position % mRepeatAfterEvery == 0)
return getDecorerView((position + mRepeatAfterEvery - 1) / mRepeatAfterEvery, convertView, parent);
return mInnerAdapter.getView(calculateInnerPosition( position), convertView, parent);
}
public abstract View getDecorerView(int position, View convertView, ViewGroup parent);
}
code with usage:
package pl.selvin.decoreradapter;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
/*** paste the DecorerAdapter class here ***/
public static class MyListFragment extends ListFragment{
final ArrayList<String> strings = new ArrayList<>();
private BaseAdapter innerAdapter;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add("Add rnd(10) more");
super.onCreateOptionsMenu(menu, inflater);
}
final Random rnd = new Random();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final String[] toAdd = new String[rnd.nextInt(10)];
int start = strings.size();
for(int i = 0; i < toAdd.length; i++)
toAdd[i] = (start + i) + "";
Collections.addAll(strings, toAdd);
Toast.makeText(getActivity(), "Added " + toAdd.length + " count: " + strings.size(), Toast.LENGTH_SHORT).show();
innerAdapter.notifyDataSetChanged();
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
for(int i = 0; i < 4; i++) {
strings.add(i + "");
}
innerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, strings);
setListAdapter(new DecorerAdapter(innerAdapter, 5) {
#Override
public View getDecorerView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = new TextView(getActivity());
convertView.setBackgroundColor(Color.RED);
}
((TextView)convertView).setText("AdView: " + position);
return convertView;
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String)l.getItemAtPosition(position);
Toast.makeText(getActivity(), "Item click: " + (item == null ? "ADVIEW" : item), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new MyListFragment(), "LIST").commit();
}
}
}
It repeats decorer view at every element passed to the constructor ...
all you need to do is implement getDecorerView in the similar way as getView in normal adapter

Related

How to change one adapter value from another adapter?

I have a little bit problem.In my activity there is two Adapter one is for color selection and another is for size selection. While i clicked one of the item of color then recently the available size adapter should be change but i got problem in size adapter. it changes only when i click the size item. I research and try to solve problem but it doesnt works for me.
Here is my code.
AddToCartActivity.java
public class AddToCartActivity extends BaseActivity{
#Override
protected int getLayout() {
return R.layout.activity_add_to_cart;
}
#Override
protected void init() {
//api called here
}
// response of api
#Override
public void productDetail(ProductCommonModel productCommonModel,
ArrayList<ProductChildModel> productChildModels, HashMap<Integer,
ArrayList<ChildAttributeModel>> childWithAttribute, HashMap<Integer,
ArrayList<ChildImageModel>> childWithImages,
ArrayList<com.hazesoft.dokan.singleproductdetail.model.ColorModel>
colorModels, ArrayList<SizeModel> sizeModels,
ArrayList<RelatedProductModel> relatedProductModels) {
this.productCommonModel = productCommonModel;
this.productChildModels = productChildModels;
this.childWithAttribute = childWithAttribute;
this.childWithImages = childWithImages;
this.colorModels = colorModels;
this.sizeModels = sizeModels;
this.relatedProductModels = relatedProductModels;
tvProductName.setText(productCommonModel.getName());
if (productCommonModel.getSpecialPrice() == 0) {
tvSellingPrice.setText(getString(R.string.rs) + productCommonModel.getSellingPrice());
tvDiscount.setVisibility(View.GONE);
tvSpecialPrice.setVisibility(View.GONE);
} else {
tvSpecialPrice.setText(getString(R.string.rs) + productCommonModel.getSpecialPrice());
tvSellingPrice.setText(getString(R.string.rs) + productCommonModel.getSellingPrice());
tvSellingPrice.setPaintFlags(tvSellingPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
tvDiscount.setText(productCommonModel.getDiscount() + getString(R.string.percentage));
}
setChildDetail(childWithAttribute, productChildModels);
setColorModel(colorModels);
setSizeModel(sizeModels);
quantity = Integer.parseInt(tvQuantityCart.getText().toString());
}
// setcolor adapter
private void setColorModel(ArrayList<ColorModel> colorModels) {
MyColorGridViewAdapter adapter = new MyColorGridViewAdapter(this, colorModels);
gvColor.setAdapter(adapter);
gvColor.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedPostion(position);
adapter.notifyDataSetChanged();
}
});
}
// set size adapter
private void setSizeModel(ArrayList<SizeModel> sizeModels) {
sizeCustomModels = new ArrayList<>();
for(int i=0;i<sizeModels.size();i++){
sizeCustomModels.add(new SizeCustomModel(sizeModels.get(i).getAttName(),0));
}
setCustomSizeModelToAdapter(sizeCustomModels);
}
// this is code when i click color and change the size adapter but size doesnt change recently only changes when i click any item of the size
public void getSelectedC0lor(String color) {
selectedColor = color;
selectedSize=null;
sizeCustomModels = new ArrayList<>();
availableSize = new ArrayList<>();
for (int i = 0; i < skuColorSIzeList.size(); i++) {
if (skuColorSIzeList.get(i).getColor().equals(selectedColor)) {
availableSize.add(skuColorSIzeList.get(i).getSize());
}
}
for(int i=0;i<sizeModels.size();i++){
String size = null;
int status=0;
for(int j=0;j<availableSize.size();j++){
if(sizeModels.get(i).getAttName().equals(availableSize.get(j))){
size = sizeModels.get(i).getAttName();
status = 1;
break;
}else {
size = sizeModels.get(i).getAttName();
status = 0;
}
}
sizeCustomModels.add(new SizeCustomModel(size,status));
}
sizeRecylerAdapter.getNewModel(sizeCustomModels);
/*sizeRecylerAdapter = new MyCustomSizeRecylerAdapter(sizeCustomModels,this);
rvSize.setAdapter(sizeRecylerAdapter);
sizeRecylerAdapter.notifyDataSetChanged();*/
/*setCustomSizeModelToAdapter(sizeCustomModels);*/
}
}
MyColorGridViewAdapter.java
public class MyColorGridViewAdapter extends BaseAdapter {
Context context;
List<ColorModel> colorModelList;
String select_color;
boolean ch =false;
int checkPosition = -1;
public MyColorGridViewAdapter(Context context, List<ColorModel> colorModelList) {
this.context = context;
this.colorModelList = colorModelList;
}
public void setSelectedPostion(int postion){
this.checkPosition = postion;
}
#Override
public int getCount() {
return colorModelList.size();
}
#Override
public Object getItem(int position) {
return colorModelList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.custom_color_list_item,null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
Picasso.with(context).load(colorModelList.get(position).getImage()).into(holder.ivImage);
holder.tvColorName.setText(colorModelList.get(position).getAttName());
if(checkPosition==position){
holder.ivChecked.setVisibility(View.VISIBLE);
select_color = colorModelList.get(position).getAttName();
if( context instanceof AddToCartActivity){
((AddToCartActivity) context).getSelectedC0lor(select_color);
}
}else {
holder.ivChecked.setVisibility(View.GONE);
}
if(colorModelList.size()==1){
holder.ivChecked.setVisibility(View.VISIBLE);
select_color = colorModelList.get(position).getAttName();
if( context instanceof AddToCartActivity){
((AddToCartActivity) context).getSelectedC0lor(select_color);
}
}
return convertView;
}
class ViewHolder{
#BindView(R.id.view)
LinearLayout view;
#BindView(R.id.tv_color_name)
TextViewHelper tvColorName;
#BindView(R.id.iv_image)
ImageView ivImage;
#BindView(R.id.iv_checked)
ImageView ivChecked;
public ViewHolder(View view) {
ButterKnife.bind(this,view);
}
}
}
MyCustomSizeRecylerAdapter.java
public class MyCustomSizeRecylerAdapter extends RecyclerView.Adapter<MyCustomSizeRecylerAdapter.MyViewHolder> {
ArrayList<SizeCustomModel> sizeModels;
Context context;
int checkPosition = -1;
String selectedSize;
public MyCustomSizeRecylerAdapter(ArrayList<SizeCustomModel> sizeModels, Context context) {
this.sizeModels = sizeModels;
this.context = context;
}
public void getNewModel(ArrayList<SizeCustomModel> customModels) {
sizeModels.clear();
this.sizeModels = customModels;
selectedSize = null;
Log.d("sizemodel", "getNewModel: " + new Gson().toJson(sizeModels));
notifyDataSetChanged();
}
public void getSelectedPosition(int position) {
checkPosition = position;
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.size_adapter, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_sizeName.setText(sizeModels.get(position).getSize());
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
if (sizeModels.get(position).getStock_Status() == 0) {
holder.ll_mainview.setClickable(false);
holder.ll_sizeAdapter.setBackgroundResource(R.color.blue_700);
} else if (sizeModels.get(position).getStock_Status() == 1) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
if (checkPosition == position) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_green);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.white));
selectedSize = sizeModels.get(position).getSize();
if (context instanceof AddToCartActivity) {
((AddToCartActivity) context).getSelectSize(selectedSize);
}
} else {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_register);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.tv_black));
}
if (sizeModels.size() == 1) {
holder.ll_sizeAdapter.setBackgroundResource(R.drawable.ellipse_green);
holder.tv_sizeName.setTextColor(context.getResources().getColor(R.color.white));
selectedSize = sizeModels.get(position).getSize();
if (context instanceof AddToCartActivity) {
((AddToCartActivity) context).getSelectSize(selectedSize);
}
}
}
}
#Override
public int getItemCount() {
return sizeModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.tv_sizeName)
TextView tv_sizeName;
#BindView(R.id.ll_sizeAdapter)
LinearLayout ll_sizeAdapter;
#BindView(R.id.main_view)
LinearLayout ll_mainview;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
At first both adapter will set data and after click color item the size adapter must be change but it only changes when i click any of the item. adapter.notifyDataSetChanged() doesnt work here for me.
Both Adapter set
When i click color item but doesnt change size adapter
when i click size item only change size adapter
Use Interface to bridge with two adapter and communicate with each other.

How avoid refresh checkbox while expand list in android

I'm making NLevel expandable list using listview. I've added checkbox only last level data in list view. I have stuck in below scenario.
If I check checkbox then when I expand listview means checkbox gets automatically unchecked.I don't want it to be like that. If I checked checkbox it should stay checked until I uncheck manually.
Please anyone help me!! It's been two days I stuck here.
Here goes my code:
MainActivity.java
public class MainActivity extends Activity {
List<NLevelItem> list;
ListView listView;
Context context;
Button checkButton;
ArrayList<String>tempList;
CheckBox selected = null; //Make only one selection at a time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<NLevelItem>();
context = this;
checkButton = (Button)findViewById(R.id.buttons);
tempList = new ArrayList<String>();
//here we create 5 grandparent (top level) NLevelItems
//then foreach grandparent create a random number of parent (second level) NLevelItems
//then foreach parent create a random number of children (third level) NLevelItems
//we pass in an anonymous instance of NLevelView to the NLevelItem, this NLevelView is
//what supplies the NLevelAdapter with a View for this NLevelItem
Random rng = new Random();
final LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < 5; i++) {
final NLevelItem grandParent = new NLevelItem(new SomeObject("GrandParent "+i),null, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.GREEN);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(grandParent);
int numChildren = rng.nextInt(4) + 1;
for (int j = 0; j < numChildren; j++) {
NLevelItem parent = new NLevelItem(new SomeObject("Parent "+j),grandParent, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.YELLOW);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(parent);
int children = rng.nextInt(3)+1;
for(int x=0; x<children;x++){
final NLevelItem childs = new NLevelItem(new SomeObject("Parent1 "+x),parent, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) view.findViewById(R.id.textView);
//tv.setBackgroundColor(Color.BLUE);
String name = (String) ((SomeObject) item.getWrappedObject()).getName();
tv.setText(name);
return view;
}
});
list.add(childs);
int grandChildren = rng.nextInt(5)+1;
for( int k = 0; k < grandChildren; k++) {
NLevelItem child = new NLevelItem(new SomeObject("child "+k),childs, new NLevelView() {
#Override
public View getView(NLevelItem item) {
View view = inflater.inflate(R.layout.check_list, null);
TextView tv = (TextView) view.findViewById(R.id.checktextView);
final String name = (String) ((SomeObject) item.getWrappedObject()).getName();
final CheckBox checkBox = (CheckBox)view.findViewById(R.id.check);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected != null){ //Edit
selected.setChecked(false);
}
selected = checkBox; //Edit
if(checkBox.isChecked()){
tempList.add((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
else {
tempList.remove((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
}
});
//tv.setBackgroundColor(Color.GRAY);
tv.setText(name);
return view;
}
});
list.add(child);
}
}
}
}
NLevelAdapter adapter = new NLevelAdapter(list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
((NLevelAdapter)listView.getAdapter()).toggle(arg2);
((NLevelAdapter)listView.getAdapter()).getFilter().filter();
}
});
checkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<tempList.size();i++){
Toast.makeText(context,tempList.get(i),Toast.LENGTH_LONG).show();
}
}
});
}
class SomeObject {
public String name;
public SomeObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
NLevelAdapter.java
public class NLevelAdapter extends BaseAdapter {
List<NLevelItem> list;
List<NLevelListItem> filtered;
public void setFiltered(ArrayList<NLevelListItem> filtered) {
this.filtered = filtered;
}
public NLevelAdapter(List<NLevelItem> list) {
this.list = list;
this.filtered = filterItems();
}
#Override
public int getCount() {
return filtered.size();
}
#Override
public NLevelListItem getItem(int arg0) {
return filtered.get(arg0);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return getItem(arg0).getView();
}
public NLevelFilter getFilter() {
return new NLevelFilter();
}
class NLevelFilter {
public void filter() {
new AsyncFilter().execute();
}
class AsyncFilter extends AsyncTask<Void, Void, ArrayList<NLevelListItem> > {
#Override
protected ArrayList<NLevelListItem> doInBackground(Void...arg0) {
return (ArrayList<NLevelListItem>)filterItems();
}
#Override
protected void onPostExecute(ArrayList<NLevelListItem> result) {
setFiltered(result);
NLevelAdapter.this.notifyDataSetChanged();
}
}
}
public List<NLevelListItem> filterItems() {
List<NLevelListItem> tempfiltered = new ArrayList<NLevelListItem>();
OUTER: for (NLevelListItem item : list) {
//add expanded items and top level items
//if parent is null then its a top level item
if(item.getParent() == null) {
tempfiltered.add(item);
} else {
//go through each ancestor to make sure they are all expanded
NLevelListItem parent = item;
while ((parent = parent.getParent())!= null) {
if (!parent.isExpanded()) {
//one parent was not expanded
//skip the rest and continue the OUTER for loop
continue OUTER;
}
}
tempfiltered.add(item);
}
}
return tempfiltered;
}
public void toggle(int arg2) {
filtered.get(arg2).toggle();
}
}
Thanks in advance!!
i think you need to store the checkbox state in a boolean (is checked), and reflect that on the view, when getView() is called.
1- Add boolean checked to NLevelItem :
private boolean checked = false;
//add setter: setChecked(boolean)
//add getter isChecked()
2- Use that boolean in getView() (last one where checkbox is added)
#Override
public View getView(final NLevelItem item) {
// .......
final CheckBox checkBox = (CheckBox)view.findViewById(R.id.check);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//store checkbox state, note that NLevelItem item might need to be defined with 'final'
item.setChecked(checkBox.isChecked());
if(checkBox.isChecked()){
tempList.add((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
else {
tempList.remove((String) ((SomeObject)childs.getWrappedObject()).getName()+"+"+name);
}
}//onClick()
}//setOnClickListener()
//update checkbox state from the corresponding NLevelItem
checkBox.setChecked(item.isChecked());
//.......
}//getView()
-EDIT:
to select 1 item, you need to iterate all items, set checked = false, but 1
i am not sure if you have to do it on:
List<NLevelItem> list;
or
List<NLevelListItem> filtered;
in the adapter class
private void selectOnly(int position){
for(int a=0;a<list.size();a++){
if(a == position){
list.get(a).setChecked(true);
continue;
}
list.get(a).setChecked(false);
}//for loop
notifyDataSetChanged(); // to update views (checkbox state)
}
Usage: selectOnly(15);
Use ViewHolder class to set and get Tag like this:
public class ListAdapter extends BaseAdapter {
private Context con;
private List<String> dataLt;
private static LayoutInflater inflater = null;
public ListAdapter(Context context, List<String> dataList){
con = context;
dataLt = dataList;
inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return dataLt.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.list_item_search, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.textView = (TextView) vi.findViewById(R.id.textView);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
return vi;
}
public static class ViewHolder{
TextView textView;
}
}
Hope this may help.

How to fetch the value from custom ExpandableList Adapter class and set into previous fragment of UI component

I have the following two class one is fragment class and another one is custom expandablelistadapter class. i want the values fetch from the expandablelistadapter class and set the values into fragment UI component like set into textview i describe as comment in following class where to taken values
and where to set the values
SlideContentFragment.java
public class SlidingContentFragment extends Fragment {
static final String LOG_TAG = "SlidingContentFragment";
// store category list from Conastant list, used for to display pagetitle
List<String> catList = AppConstants.CATEGORY_LIST;
private static String[] tmpId = {"35","36","41","42","43","44","45","46"};
ExpandableListView exListCategory;
private SlidingTabLayout mSlidingTabLayout;
/**
* A {#link android.support.v4.view.ViewPager} which will be used in conjunction with the {#link SlidingTabLayout} above.
*/
private ViewPager mViewPager;
//private ExpandableListAdapter mAdapter; // added new
private SamplePagerAdapter myAdapter;
public SlidingContentFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sliding_content, container, false);
ImageButton cartImgBtn = (ImageButton)v.findViewById(R.id.imgBtnCart);
TextView totalCntItem = (TextView)v.findViewById(R.id.tvCartItemCount);
// I want here set the value of totalCounter from ExpandableList Adapter class when i click on plus
// OR minus button of particular item it updates its value as total count of all item selected
// here following line of code which not worked
totalCntItem.setText(String.format("%d",CategoryItemListAdapter.getTotalCounter()));
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// BEGIN_INCLUDE (setup_viewpager)
// Get the ViewPager and set it's PagerAdapter so that it can display items
this.myAdapter = new SamplePagerAdapter(); // added new
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(this.myAdapter);
// END_INCLUDE (setup_viewpager)
// BEGIN_INCLUDE (setup_slidingtablayout)
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
public class SamplePagerAdapter extends PagerAdapter {
public SamplePagerAdapter() {
super();
}
#Override
public int getCount() {
return catList.size();
}
#Override
public boolean isViewFromObject(View view, Object o){
return o == view;
}
#Override
public CharSequence getPageTitle(int position) {
return catList.get(position);
}
#Override
public int getItemPosition (Object object)
{
return PagerAdapter.POSITION_NONE;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
//return super.instantiateItem(container, position);
ViewPager viewPager = (ViewPager)container;
View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,
container, false);
viewPager.addView(view);
exListCategory = (ExpandableListView)view.findViewById(R.id.myExpandableListView);
//exListCategory.setIndicatorBounds(10,20);
exListCategory.setDividerHeight(2);
if(ConnectionDetector.isInternetAvailable(getActivity())) {
new CategoryJSONAsyncTask().execute("http://..../api/Main/GetCateenOrderCategoryItemListDetail?CategoryID=" + tmpId[position].trim());
}else{
Utility.buildDialog(getActivity()).show();
}
Log.i(String.format("%s: POSITION", LOG_TAG), String.valueOf(position));
Log.i(String.format("%s: CATLIST", LOG_TAG),String.valueOf(catList.get(position)));
view.setTag(position);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//viewpager
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
view.getTag(position);
viewPager.removeView(view);
//((ViewPager) container).removeView((View) object);
}
}
public class CategoryJSONAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
HttpGet httppost = new HttpGet(params[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
return result;
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ArrayList<CategoryParentItemList> listParent = fetchResponse(result.replace("\n","").trim());
/*for (Object obj : listParent){
if(obj.getClass() == CategoryParentItemList.class){
CategoryParentItemList p = (CategoryParentItemList)obj;
System.out.println("P-ItemName: "+ p.subCategoryName);
}
}*/
CategoryItemListAdapter adapter = new CategoryItemListAdapter(SlidingContentFragment.this.getActivity(), listParent);
exListCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
public ArrayList<CategoryParentItemList> fetchResponse(String result)
{
ArrayList<CategoryParentItemList> listParent = new ArrayList<>();
if (!result.equals(""))
{
try
{
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("SBL");
CategoryParentItemList parent;
for (int i = 0; i < jarray.length(); i++)
{
ArrayList<CategoryChildListItem> childrens = new ArrayList<>();
childrens.clear();
CategoryChildListItem child;
JSONObject object = jarray.getJSONObject(i);
//System.out.println("SCI: " + object.getInt("SubCategoryID"));
//System.out.println("SCN: " + object.getString("SubCategoryName"));
JSONArray subItemArray = object.getJSONArray("SubCategoryItemList");
if (subItemArray.length() > 0)
{
for (int j = 0; j < subItemArray.length(); j++)
{
JSONObject subItemObject = subItemArray.getJSONObject(j);
String strItemName = subItemObject.getString("ItemName");
String strDefaultPrice = subItemObject.getString("DefaultPrice");
child = new CategoryChildListItem(strItemName, strDefaultPrice);
childrens.add(child);
//Log.i("strItemName", strItemName);
//Log.i("strDefaultPrice", strDefaultPrice);
}
parent = new CategoryParentItemList(object.getString("SubCategoryName"),childrens);
listParent.add(parent);
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return listParent;
}
}
CategoryListItemAdaptor.java
public class CategoryItemListAdapter extends BaseExpandableListAdapter{
private Context context;
public static int totalCounter=0;
private ArrayList<CategoryParentItemList> listParent;
static class ViewHolderGroup {
public TextView lblSubCategoryName;
}
static class ViewHolderChild {
public TextView lblItemName;
public TextView lblDefualtPrice;
public TextView lblQty;
public ImageButton imgPlus;
public ImageButton imgMinus;
}
public CategoryItemListAdapter(Context context, ArrayList<CategoryParentItemList> listParent) {
super();
this.context = context;
this.listParent = listParent;
}
#Override
public int getGroupCount() {
return listParent.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.size();
}
#Override
public Object getGroup(int groupPosition) {
return listParent.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<CategoryChildListItem> ch = listParent.get(groupPosition).getChildList();
return ch.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
//CategoryParentItemList parentItem = (CategoryParentItemList)listParent.get(groupPosition);
CategoryParentItemList parentItem = (CategoryParentItemList) getGroup(groupPosition);
ViewHolderGroup holderGroup;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_header, null);
holderGroup = new ViewHolderGroup();
holderGroup.lblSubCategoryName = (TextView) convertView.findViewById(R.id.tvItemName);
convertView.setTag(holderGroup);
} else {
holderGroup = (ViewHolderGroup) convertView.getTag();
}
holderGroup.lblSubCategoryName.setText(parentItem.getSubCategoryName());
return convertView;
}
#Override
public View getChildView(int groupPosition,int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
//final CategoryParentItemList parentItem = (CategoryParentItemList) listParent.get(groupPosition);
//final CategoryChildListItem childItem = (CategoryChildListItem) parentItem.getChildList().get(childPosition);
CategoryChildListItem childItem = (CategoryChildListItem) getChild(groupPosition, childPosition);
ViewHolderChild holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
holder = new ViewHolderChild();
holder.lblItemName = (TextView) convertView.findViewById(R.id.tvSubItemName);
holder.lblDefualtPrice = (TextView) convertView.findViewById(R.id.tvrRupees);
holder.lblQty = (TextView) convertView.findViewById(R.id.tvQty);
holder.imgPlus = (ImageButton) convertView.findViewById(R.id.imageButtonPlus);
holder.imgMinus = (ImageButton) convertView.findViewById(R.id.imageButtonMinus);
convertView.setTag(holder);
} else {
holder = (ViewHolderChild) convertView.getTag();
}
holder.lblItemName.setText(childItem.getSubItemName());
holder.lblDefualtPrice.setText(childItem.getDefaultPrice());
int tmpCount = Integer.parseInt(holder.lblQty.getText().toString());
holder.imgPlus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
holder.imgMinus.setOnClickListener(new ClickUpdateListener(childItem,holder, tmpCount));
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
public static int getTotalCounter() {
return totalCounter;
}
private class ClickUpdateListener implements View.OnClickListener {
ViewHolderChild holder;
public CategoryChildListItem childItem;
int counter = 0;
String counterMin;
public ClickUpdateListener(CategoryChildListItem childItem,ViewHolderChild holder, int cnt) {
this.childItem = childItem;
this.holder = holder;
this.counter = cnt;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageButtonPlus) {
counter = counter + 1;
totalCounter+=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C+ :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}
if(v.getId() == R.id.imageButtonMinus){
counterMin = (String) holder.lblQty.getText();
counter = Integer.parseInt(counterMin.toString().trim());
counterMin = null;
if(counter > 0) {
counter = counter - 1;
totalCounter-=1;
System.out.println(childItem.getSubItemName()+" : "+childItem.getDefaultPrice() + ": C- :" + counter);
holder.lblQty.setText(String.format("%d", counter));
notifyDataSetChanged();
}else{
Toast.makeText(context,"Qty Zero",Toast.LENGTH_SHORT).show();
}
}
}
}
}

Need add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network

I need yout help. How to add Ad Unit (NativeAd) within a List of Articles, using Facebook Audience Network https://developers.facebook.com/docs/audience-network/android/native-api. Im not programmer and need all code how it should be. The ads have to be between posts (listview)Thanks
import com.facebook.ads.*;
public class Posts extends Fragment{
ArrayList<Post> mPosts;
private static final String KEY_CONTENT = "PostsFragment:array";
boolean isLoadMore = false;
int mPageCount = 0;
int mCurrectPage = 1;
PullToRefreshListView mListView;
MyAdapter mListViewAdapter;
View mLoadingFooter;
private Tracker tracker;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.tracker = EasyTracker.getInstance(this.getActivity());
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mPosts = (ArrayList<Post>) savedInstanceState.getSerializable(KEY_CONTENT);
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
#Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, "Article");
this.tracker.send( MapBuilder.createAppView().build() );
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_CONTENT, mPosts);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View _result = inflater.inflate(R.layout.list, null);
mLoadingFooter = inflater.inflate(R.layout.loading_footer, null);
mLoadingFooter.setVisibility(View.GONE);
if (mPosts == null)
{
mPosts = new ArrayList<Post>();
loadPostsList();
}
mListView = (PullToRefreshListView) _result.findViewById(R.id.listView);
mListViewAdapter = new MyAdapter(getActivity(), mPosts);
mListView.addFooterView(mLoadingFooter);
mListView.setAdapter(mListViewAdapter);
mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mCurrectPage = 1;
mPosts.clear();
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
});
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (totalItemCount > Constant.MIN_ITEM_COUNT && lastInScreen >= (totalItemCount - Constant.MIN_ITEM_COUNT_HALF) && !isLoadMore && mCurrectPage <= mPageCount)
{
mLoadingFooter.setVisibility(View.VISIBLE);
isLoadMore = true;
loadPostsList();
}
}
});
return _result;
}
public void loadPostsList() {
isLoadMore = true;
mLoadingFooter.setVisibility(View.VISIBLE);
new AsynckRequestGet().execute(getActivity(), TYPE_GET_OPERATION.POSTS, CodeRequestManager.codePosts(TempData.getInstance().getToken(), mCurrectPage));
}
private class AsynckRequestGet extends AbstractAsyncRequestGet {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
isLoadMore = false;
if(!isDetached()) {
mLoadingFooter.setVisibility(View.GONE);
mListView.onRefreshComplete();
}
if(result == null) return;
int[] t = JsonParser.parsePageCountResponse(result);
mPageCount = t[0];
mCurrectPage = t[1] +1;
ArrayList<Post> temp = JsonParser.parsePostsResponse(result);
if(temp == null || isDetached())
return;
mPosts.addAll(temp);
mListViewAdapter.notifyDataSetChanged();
}
}
private class MyAdapter extends ArrayAdapter<Post> {
private LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Post> objects) {
super(context, R.layout.post_item, objects);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.post_item, null);
final Post post = getItem(position);
final TextView postLikes = ((TextView) convertView.findViewById(R.id.post_likes));
final TextView postComments = ((TextView) convertView.findViewById(R.id.post_comments));
postComments.setText(post.getCountComment() + "");
postLikes.setText(post.getCountLike() + "");
if(post.isMyLike()) {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_my_icon, 0, 0, 0);
} else {
postLikes.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_icon, 0, 0, 0);
}
postLikes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AbstractAsyncRequestGet().execute(getActivity(), TYPE_GET_OPERATION.LIKE, CodeRequestManager.codeLike(TempData.getInstance().getToken(), post.getId(), post.isMyLike()? 0 : 1));
post.setCountLike((post.getCountLike()) + (post.isMyLike()? -1 : 1));
post.setMyLike(post.isMyLike()? 0 : 1);
postLikes.setText(post.getCountLike() + "");
mListViewAdapter.notifyDataSetChanged();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
((TrainingFragment) getParentFragment().getParentFragment()).showPostDetails(mPosts.get(arg2-1), new DetailListener() {
#Override
public void onRefresh() {
if(!isDetached())
mListViewAdapter.notifyDataSetChanged();
}
})
;}
});
((TextView) convertView.findViewById(R.id.post_title)).setText(post.getTitle());
((TextView) convertView.findViewById(R.id.post_content)).setText(post.getContent());
return convertView;
}
}
}
If you get the latest Facebook Android SDK, you can find the NativeAdSample project updated with how to display native ads in a list view. Code copied from the sample:
package com.facebook.samples.NativeAdSample;
import java.util.ArrayList;
import java.util.List;
import com.facebook.ads.Ad;
import com.facebook.ads.AdError;
import com.facebook.ads.AdListener;
import com.facebook.ads.NativeAd;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class NativeAdListActivity extends ListActivity implements AdListener {
private ListView listView;
private ListViewAdapter adapter;
private NativeAd listNativeAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listNativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
listNativeAd.setAdListener(this);
listNativeAd.loadAd();
listView = getListView();
adapter = new ListViewAdapter(getApplicationContext());
listView.setAdapter(adapter);
}
#Override
public void onAdClicked(Ad ad) {
Toast.makeText(this, "Ad Clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLoaded(Ad ad) {
adapter.addNativeAd((NativeAd) ad);
}
#Override
public void onError(Ad ad, AdError error) {
Toast.makeText(this, "Ad failed to load: " + error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
class ListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Object> list;
private NativeAd ad;
private static final int AD_INDEX = 2;
public ListViewAdapter(Context context) {
list = new ArrayList<Object>();
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 1; i <= 35; i++) {
list.add("ListView Item #" + i);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == AD_INDEX && ad != null) {
// Return the native ad view
return (View) list.get(position);
} else {
TextView view; // Default item type (non-ad)
if (convertView != null && convertView instanceof TextView) {
view = (TextView) convertView;
} else {
view = (TextView) inflater.inflate(R.layout.list_item, parent, false);
}
view.setText((String) list.get(position));
return view;
}
}
public synchronized void addNativeAd(NativeAd ad) {
if (ad == null) {
return;
}
if (this.ad != null) {
// Clean up the old ad before inserting the new one
this.ad.unregisterView();
this.list.remove(AD_INDEX);
this.ad = null;
this.notifyDataSetChanged();
}
this.ad = ad;
View adView = inflater.inflate(R.layout.ad_unit, null);
NativeAdSampleActivity.inflateAd(ad, adView, NativeAdListActivity.this);
list.add(AD_INDEX, adView);
this.notifyDataSetChanged();
}
}
}

java.lang.IndexOutOfBoundsException: Invalid index 20, size is 20

I'm using a custom adapter to load 20 items from a JSON string as well as implement ads in the 4th and 14th position. What I'm encountering is that when I scroll to view item #19, it crashes with the error in the title.
I know that the error is saying that it's trying to access an index that is not in the array but I think it's because it's included the adViews in the index (which it shouldn't). I feel like this is something simple that I am missing but please help. Here are my 2 adapters:
public class ListViewAdapter extends BaseAdapter implements AdListener {
private final Activity activity;
private final BaseAdapter delegate;
public ListViewAdapter(Activity activity, BaseAdapter delegate) {
this.activity = activity;
this.delegate = delegate;
}
#Override
public int getCount() {
// Total count includes list items and ads.
return delegate.getCount() + 2;
}
#Override
public Object getItem(int position) {
// Return null if an item is an ad. Otherwise return the delegate item.
if (isItemAnAd(position)) {
return null;
}
return delegate.getItem(position - 1);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (isItemAnAd(position)) {
if (convertView instanceof AdView) {
return convertView;
} else {
AdView adView = new AdView(activity, AdSize.SMART_BANNER,"AD ID (removed for post)" );
AdRequest adRequest = new AdRequest();
adView.loadAd(adRequest);
return adView;
}
} else {
return delegate.getView(position-1, convertView, parent);
}
}
#Override
public int getViewTypeCount() {
return delegate.getViewTypeCount() + 1;
}
#Override
public int getItemViewType(int position) {
if (isItemAnAd(position)) {
return delegate.getViewTypeCount();
} else {
return delegate.getItemViewType(getOffsetPosition(position));
}
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (!isItemAnAd(position)) && delegate.isEnabled(getOffsetPosition(position));
}
private boolean isItemAnAd(int position) {
// Place an ad at the first and last list view positions.
return (position == 4 || position == 14);
}
#Override
public void onDismissScreen(Ad arg0) {
}
#Override
public void onFailedToReceiveAd(Ad arg0, AdRequest.ErrorCode arg1) {
}
#Override
public void onLeaveApplication(Ad arg0) {
}
#Override
public void onPresentScreen(Ad arg0) {
}
#Override
public void onReceiveAd(Ad arg0) {
}
private int getOffsetPosition(int position) {
return position - 1;
}
}
Here's the custom adapter which sets the listview:
class CustomMovieAdapter extends BaseAdapter {
private ArrayList<SearchResults> searchArrayList;
private LayoutInflater mInflater;
public CustomMovieAdapter(Context context, ArrayList<SearchResults> results){
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return searchArrayList.size()+2;
}
#Override
public Object getItem(int position) {
return searchArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
if(convertView == null){
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
assert convertView != null;
holder.txtRating = (TextView) convertView.findViewById(R.id.movieRating);
holder.txtMovieName = (TextView) convertView.findViewById(R.id.movieName);
holder.txtMovieSize = (TextView) convertView.findViewById(R.id.movieSize);
holder.txtImdbRating = (TextView) convertView.findViewById(R.id.imdbScore);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtRating.setText(searchArrayList.get(position+1).getRating());
holder.txtMovieName.setText(searchArrayList.get(position+1).getName());
holder.txtMovieSize.setText(searchArrayList.get(position+1).getSize());
holder.txtImdbRating.setText(searchArrayList.get(position+1).getImdbRating());
return convertView;
}
class ViewHolder {
TextView txtRating;
TextView txtMovieName;
TextView txtMovieSize;
TextView txtImdbRating;
}
}
#Override
public int getCount() {
// Total count includes list items and ads.
return delegate.getCount() + 2;
}
you should return the size of the dataset without changing it. If you need to show more items, add those to the dataset. Changing it with
#Override
public int getCount() {
// Total count includes list items and ads.
return delegate.getCount() ;
}
Should fix your exception.
Edit, in getView you should avoid tampering the position android is providing you:
position+1

Categories