I am trying to populate a listView with two String ArrayLists. These ArrayLists are passed from another activity to the listView activity.
Activity with Listview
public class DecisionActivity extends AppCompatActivity {
ListView lv;
customDecisionAdapter decisionAdapter;
String[] array1, array2 ;
ArrayList<String> l1;
ArrayList<String> l2;
TextView t1,t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decision);
t1=(TextView) findViewById(R.id.textForl1);
t2=(TextView) findViewById(R.id.textForl2);
lv= (ListView) findViewById(R.id.listViewDecision);
Intent intent = getIntent();
array1=intent.getStringArrayExtra("List1");
array2=intent.getStringArrayExtra("List2");
l1=new ArrayList<>(Arrays.asList(array1));
l2=new ArrayList<>(Arrays.asList(array2));
decisionAdapter=new customDecisionAdapter(getApplicationContext(),l1,l2);
lv.setAdapter(decisionAdapter);
}
}
Custom Adapter
public class customDecisionAdapter extends BaseAdapter {
Context context;
private ArrayList<String> list1;
private ArrayList<String> list2;
public customDecisionAdapter(Context context, ArrayList<String>list1, ArrayList<String>list2) {
this.context= context;
this.list1= list1;
this.list2= list2;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View convertView = view;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customdecision,viewGroup,false);
}
TextView t1 = (TextView) convertView.findViewById(R.id.textDisease);
TextView t2 = (TextView) convertView.findViewById(R.id.textTotal);
t1.setText(list1.get(i));
t2.setText(list2.get(i));
return convertView;
}
@Override
public int getCount() {
return list1.size();
}
@Override
public Object getItem(int i) {
if (i>= list1.size())
return list2.get(i);
return list1.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
}
When I run the program, it crashes and provides the error of:
java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2
which point to the line:
t2.setText(list2.get(i));
I don't know what I'm doing wrong here.
"Invalid index 2, size is 2"means the size is 2, so valid index is only 0, and 1. And there is nothing at the index 2.ArrayList<YourCustomObject>instead of 2 ArrayList<String> ?