Adding item to ListAdapter causes exception
I'm trying to use a list view, and when I add an item to the ArrayList of its ListAdapter and call notifyDataSetChanged, it throws an exception. Calling the addItem routine below will throw an exception.
The message says Source not Found, and then this: // Compiled from DataSetObservable.java (version 1.5 : 49.0, super bit) // Signature: Landroid/database/Observable; public class android.database.DataSetObservable extends android.database.Observable {
// Method descriptor #8 ()V // Stack: 3, Locals: 1 public DataSetObservable(); 0 aload_0 [this] 1 invokespecial android.database.Observable() [1] 4 new java.lang.RuntimeException [2] 7 dup 8 ldc [3] 10 invokespecial java.lang.RuntimeException(java.lang.String) [4] 13 athrow Line numbers: [pc: 0, line: 5] Local variable table: [pc: 0, pc: 14] local: this index: 0 type: android.database.DataSetObservable
My initialization code:
tickerList = (ListView)findViewById(R.id.ListView01);
tickerModel = new StockAdapter(stocks);
tickerList.setAdapter(tickerModel);
I've included my custom adapter class. (Modified from an online example)
private class StockAdapter extends BaseAdapter {
private ArrayList <Stockdata>mData = new ArrayList<Stockdata>();
private LayoutInflater mInflater;
public StockAdapter(ArrayList<Stockdata>rows) {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mData = rows;
}
public void addItem(Stockdata item) {
mData.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Stockdata getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("getView " + position + " " + convertView);
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.textView = (TextView)convertView.findViewById(R.id.SYMBOL_CELL);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.se开发者_StackOverflow社区tText(mData.get(position).getSymbol());
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
The problem was that I was calling notifyDataSetChanged from outside of the UI thread.
This fixed the problem.
runOnUiThread (new Runnable() { public void run() { tickerModel.notifyDataSetChanged(); } });
Thanks, Gerry
精彩评论