在我的应用中,我使用LinkedList支持ListView。我正在使用自定义ArrayAdapter来填充列表:
public class CustomArrayAdapter extends ArrayAdapter<Message> {
Context context;
int resource;
public CustomArrayAdapter(Context context, int resource, List<Message> messages) {
super(context, resource, messages);
this.context = context;
this.resource = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MessageHolder messageHolder = null;
if(row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(resource, parent, false);
messageHolder = new MessageHolder();
messageHolder.chat_information = (TextView) row.findViewById(R.id.chat_information);
messageHolder.chat_message = (TextView) row.findViewById(R.id.chat_message);
row.setTag(messageHolder);
} else {
messageHolder = (MessageHolder) row.getTag();
}
Message message = getItem(position);
messageHolder.chat_information.setText(message.getSenderName() + Constants.NEWLINE + message.getSendTime());
messageHolder.chat_message.setText(message.getMessageText());
return row;
}
private class MessageHolder {
TextView chat_information;
TextView chat_message;
}
}
但是,我意识到LinkedList不是线程安全的。我想使用ConcurrentLinkedQueue或LinkedBlockingDeque,但它们只返回数组,而适配器需要List。
有没有办法调整这个自定义ArrayAdapter以使用其中一个线程安全方法,还是需要迭代对象数组以填充要使用的List?
答案 0 :(得分:0)
java.util.Collections类可用于包装List,使其同步(即线程安全)。例如:
LinkedList<String> notThreadSafeList = new LinkedList<String>();
List<String> threadSafeList = Collections.synchronizedList(notThreadSafeList);
另见:
http://developer.android.com/reference/java/util/Collections.html#synchronizedList(java.util.List)
答案 1 :(得分:0)
我最终将列表转换为使用内部SQLite数据库,并使用SimpleCursorAdapter备份ListView。