Android : notifyDataSetChanged() causes IndexOutOfBoundsException

on Wednesday, March 18, 2015


Here's a shortened version of my code.



public class MainActivity extends ActionBarActivity {

private ArrayList<String> entry = new ArrayList<String>();
private String[] entryString = new String[11];
private ArrayAdapter<String> aa;
private ListView entryListView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
entryListView = (ListView) findViewById(R.id.listView1);
int listID = R.layout.entry_layout;
aa = new EntryAdapter(this, listID, entry);
entryListView.setAdapter(aa);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_add: {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent, 1);
break;
}
}
return super.onOptionsItemSelected(item);
}

@Override
public void onActivityResult(int rc, int resc, Intent i) {
super.onActivityResult(rc, resc, i);
entryString = i.getStringArrayExtra("Entry");
this.onNewItemAdded(entryString);
}

public void onNewItemAdded(String[] _entry){
String key = new
key = _entry[0];
entry.add(key);
aa.notifyDataSetChanged(); //Runs without crashing when this is removed.
}


The adapter class is,



@SuppressLint("Instantiatable")
public class EntryAdapter extends ArrayAdapter<String>{

private ArrayList<String> entries;
int count;
int resource;
public EntryAdapter(Context _context, int _resource, List<String> _entries){
//TODO Auto-generated constructor stub
super(_context, _resource, R.id.key, _entries);
this.resource = _resource;
this.entries = new ArrayList<String>(_entries);
this.count = 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;

if (convertView == null) {
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater) getContext().getSystemService(inflater);
row = li.inflate(resource, parent, false);
}

TextView keyView = (TextView) row.findViewById(R.id.key);
TextView siteView = (TextView) row.findViewById(R.id.site);

for(int c=0; c<11; c++){
while(!entries.get(c).toString().equals("")){
count++;
}
}

keyView.setText(entries.get(position));
siteView.setText(count + "sources");

return row;
}
}


By commenting the aa.notifyDataSetChanged() call in the MainActivity, the application runs without crashing but throws an



IndexOutOfBoundsException: Invalid index 0, size is 0



when it is not commented.


PS: The XML is perfectly fine.


0 comments:

Post a Comment