How to get only updated checkbox status in listview android - java

I have a listview with a checkbox in a dialog. Now I need to get only the updated checkbox item from the dialog's 'ok click'. For example if the user checks only one checkbox in the row I need to get only that status, but if the user checks and unchecks the checkbox I don't want that status. I tried using a hash table to get and remove statuses when checked, but on listview scroll the checkbox event gets executed and hash table filled with the wrong values.
public class SelectGroupAdaptor extends BaseAdapter {
Activity activity;
ArrayList<SelectGroupItems> data = new ArrayList<>();
Hashtable<Integer,Boolean> status;
public SelectGroupAdaptor(Activity activity) {
this.activity = activity;
}
public void add(SelectGroupItems selectGroupItems) {
this.data.add(selectGroupItems);
notifyDataSetChanged();
status=new Hashtable<>();
}
public ArrayList<SelectGroupItems> getCheckedData () {
return data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TextView textView;
CheckBox checkBox;
if (convertView == null) {
convertView = LayoutInflater.from(activity).inflate(R.layout.layout_select_group_row, null);
}
textView = (TextView) convertView.findViewById(R.id.label);
textView.setTypeface(Util.setCustomFont(activity));
checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
textView.setText(data.get(position).getGroupName());
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
data.get(position).setChecked(isChecked);
if(status!=null)
{
if(status.get(position)!=null)
{
status.remove(position);
}else
{
status.put(position,isChecked);
}
}
}
});
checkBox.setChecked((data.get(position).isChecked()));
return convertView;
}
public Hashtable<Integer,Boolean> getStatus()
{
return status;
}
}
Can anyone help me

You don't need HashMap, a simple item holder class with a status property would help you. See your modified code:
Edit: If I understood you correctly, you want to get the SelectGroupItems object when its check status changed? If so see edited code below:
public class SelectGroupAdaptor extends BaseAdapter {
Activity activity;
ArrayList<SelectGroupItemHolder> data = new ArrayList<SelectGroupItemHolder>();
OnItemCheckStatusChangedListener onItemCheckStatusChangedListener;
// a item holder class, not a view holder
private static class SelectGroupItemHolder {
SelectGroupItems selectGroupItems;
boolean status;
}
public interface OnItemCheckStatusChangedListener {
public void onItemCheckStatusChanged(SelectGroupItems selectGroupItems, boolean checkStatus, int position);
}
public void setOnItemCheckStatusChangedListener(OnItemCheckStatusChangedListener onItemCheckStatusChangedListener) {
this.onItemCheckStatusChangedListener = onItemCheckStatusChangedListener;
}
public SelectGroupAdaptor(Activity activity) {
this.activity = activity;
}
public void add(SelectGroupItems selectGroupItems) {
SelectGroupItemHolder selectGroupItemHolder = new SelectGroupItemHolder();
selectGroupItemHolder.selectGroupItems = selectGroupItems;
this.data.add(selectGroupItemHolder);
notifyDataSetChanged();
}
public ArrayList<SelectGroupItems> getCheckedData() {
ArrayList<SelectGroupItems> checkedItemList = new ArrayList<SelectGroupItems>();
for (SelectGroupItemHolder selectGroupItemHolder : data) {
if (selectGroupItemHolder.status) {
checkedItemList.add(selectGroupItemHolder.selectGroupItems);
}
}
return checkedItemList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TextView textView;
CheckBox checkBox;
if (convertView == null) {
convertView = LayoutInflater.from(activity).inflate(R.layout.layout_select_group_row, null);
}
textView = (TextView) convertView.findViewById(R.id.label);
textView.setTypeface(Util.setCustomFont(activity));
checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
textView.setText(data.get(position).selectGroupItems.getGroupName());
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.get(position).status = isChecked;
if(onItemCheckStatusChangedListener != null) {
onItemCheckStatusChangedListener.onItemCheckStatusChanged(data.get(position).selectGroupItems, data.get(position).status, position);
}
}
});
checkBox.setChecked((data.get(position).status));
return convertView;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
Set the check status change listener of your selectGroupAdapter instance. ie:
selectGroupAdaptor.setOnItemCheckStatusChangedListener(new SelectGroupAdaptor.OnItemCheckStatusChangedListener() {
#Override
public void onItemCheckStatusChanged(SelectGroupItems selectGroupItems, boolean checkStatus, int position) {
// handle check status change
}
});

Related

Disable buttons in recycler view after clicking

I have a recycler view, which consists of edittext and buttons for each view. I would like to have functionality in such a way that if I enter some text or attach an image for a view, then some of the buttons' functionality needs to be disabled in that view as soon as I click the button.
With the below code, I can attach images when ProofClick function is called via the interface, and then I set the button as disabled for the same position, but the button is not disabled, and I can attach images to the same view twice, which I do not want.
Adapter class:
// Check if the button is clicked and disable
private boolean clicked = false;
public InsStepsContentAdapter(List<InspectonScroll> scrollList,
ClickOnRecycle clickOnRecycle, String[] options) {
this.scrollList = scrollList;
this.clickOnRecycle = clickOnRecycle;
this.options = options;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recycler_steps, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setIsRecyclable(false);
holder.progressbar.setMax(scrollList.size());
holder.title.setText(scrollList.get(position).getSteps().get(position).getTitle());
holder.btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(clicked){
clicked = true;
clickOnRecycle.ProofClick(holder.getAdapterPosition());
holder.btnAttach.setEnabled(true);
} else{
holder.btnAttach.setEnabled(false);
}
}
});
}
public int getItemCount() {
return scrollList.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
public void updateList(List<ScrollList> scrollList){
this.scrollList = scrollList;
notifyDataSetChanged();
}
Model class:
public class InspectonScroll {
private List<Steps> Steps = new ArrayList<>();
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
}
ButtonAdapter
public class ButtonAdapter extends RecyclerView.Adapter<ButtonAdapter.ViewHolder> {
Activity activity;
ArrayList<ButtonModel> arrayList;
public ButtonAdapter(Activity activity, ArrayList<ButtonModel> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
}
#NonNull
#Override
public ButtonAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(activity.getLayoutInflater().inflate(R.layout.row_item,parent,false));
}
#Override
public void onBindViewHolder(#NonNull ButtonAdapter.ViewHolder holder, int position) {
holder.button.setText("item"+position);
ButtonModel item = arrayList.get(position);
holder.button.setEnabled(item.isEnabled);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(item.isEnabled){
item.isEnabled = false;
notifyDataSetChanged();
}
Toast.makeText(activity, "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
Button button;
public ViewHolder(#NonNull View itemView) {
super(itemView);
button = itemView.findViewById(R.id.button);
}
}
}
ButtonModel
public class ButtonModel {
boolean isEnabled = true;
}
one thing can be done here is maintaining the state of the button in the model as shown in the example and by using that state we can enable or disable the button in the onBindViewHolder method .

Cannot change the background color of selected items of recycler

I want to highlight the selected items in recyclerview. I can count the number of items selected.
I want the highlighting as
.....
I have tried this code.
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
if (isMultiSelect) {
multi_select(position);
selectedPositon = position;
} else{
Toast.makeText(getApplicationContext(), "Details Page", Toast.LENGTH_SHORT).show();
}
if (selectedPositon == position) {
view.setBackgroundColor(Color.parseColor("#e2a49e"));
} else {
view.setBackgroundColor(Color.parseColor("#f5f5f5"));
}
}
#Override
public void onItemLongClick(View view, int position) {
if (!isMultiSelect) {
selected_list = new ArrayList<AlertListItem>();
isMultiSelect = true;
selectedPositon = position;
if (mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
if (selectedPositon == position) {
view.setBackgroundColor(Color.parseColor("#e2a49e"));
} else {
view.setBackgroundColor(Color.parseColor("#f5f5f5"));
}
multi_select(position);
}
}));
}
can someone help me out.
if (btn.getBackground().getConstantState().equals(itemView.getResources().getDrawable(R.drawable.understand_clicked).getConstantState())) {
btn.setBackground(itemView.getResources().getDrawable(R.drawable.understand_not_clicked));
} else {
btn.setBackground(itemView.getResources().getDrawable(R.drawable.understand_clicked));
}
Do this code in a custom recyclerviewadapter, in View holder class. Use getConstantState for current state of image. You can also change color of selected raw.
you can use use below code
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.textView.setText(array[position]);
holder.row_linearlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
index=position;
notifyDataSetChanged();
}
});
if(index==position){
holder.layout.setBackgroundColor(Color.parseColor("#ff8569"));
holder.textView.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.layout.setBackgroundColor(Color.parseColor("#ffffff"));
holder.textView.setTextColor(Color.parseColor("#000000"));
}
}
HolderClass
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
LinearLayout layout;
RecyclerView recyclerView;
public ViewHolder(final View itemView) {
super(itemView);
textView=(TextView)itemView.findViewById(R.id.textView1);
layout=(LinearLayout)itemView.findViewById(R.id.layouot_linear);
recyclerView=(RecyclerView)itemView.findViewById(R.id.recycler);
}
}

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 get checkbox value from list view ... which is connected to Sqlite data base?

Help to get mobile number and get it in a edittext... i am gone...
help me to get the check box value and take the mobile number to some where. to send sms using Sms manager
Class name adapter... which contains row of the list view.
List list=new ArrayList();
Context context;
public Adapter(Context context, int resource)
{
super(context, resource);
this.context=context;
}
public void add(Product object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row=convertView;
final Holder holder;
if (row==null){
LayoutInflater layoutInflater= (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.rowlist,parent,false);
holder =new Holder();
holder.id=(TextView)row.findViewById(R.id.tsnoo);
holder.name=(TextView)row.findViewById(R.id.tname);
holder.birth=(TextView)row.findViewById(R.id.tbirth);
holder.email=(TextView)row.findViewById(R.id.temail);
holder.req=(TextView)row.findViewById(R.id.treq);
holder.mobile=(TextView)row.findViewById(R.id.tmobile);
holder.check=(CheckBox)row.findViewById(R.id.tcheck);
row.setTag(holder);
}else {
holder= (Holder) row.getTag();
}
Product product= (Product) getItem(position);
holder.id.setText(Integer.toString(product.getId()));
holder.name.setText(product.getName().toString());
holder.birth.setText(product.getBirth().toString());
holder.email.setText(product.getEmail().toString());
holder.req.setText(product.getReq().toString());
holder.mobile.setText(product.getMobile().toString());
holder.check.setChecked(false);
holder .check.setChecked(itemChecked[position]);
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
itemChecked[position]=isChecked;
}
});
return row;
}
private boolean[] itemChecked;
private void createCheckedHolder() {
itemChecked = new boolean[getCount()];
}
static class Holder{
TextView name,birth,email,req,mobile,id;
CheckBox check;
}
}
I have used AsyncTask to to Synchronize it...
Here i made my answer my self... with a simple meathod...
holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(holder.check.isChecked()){
View get=null;
for (int i=0;i<getCount();i++) {
if (position == i) {
get = getView(i, get, listView1);
holder.mobile = (TextView) get.findViewById(R.id.tmobile);
String last = holder.mobile.getText().toString();
String[] data;
Toast.makeText(getContext(), last, Toast.LENGTH_SHORT).show();
}
}
}
else
{
}
}
});

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