[英]How can I make my list thread safe in order to use it with a custom ArrayAdapter?
In my app, I am backing a ListView with a LinkedList. 在我的应用程序中,我支持带有LinkedList的ListView。 I am using an custom ArrayAdapter in order to fill the list:
我正在使用自定义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;
}
}
I realized, however, that LinkedList is not thread safe. 但是,我意识到LinkedList不是线程安全的。 I would like to use ConcurrentLinkedQueue or LinkedBlockingDeque , but they only return arrays, and the adapter requires a List.
我想使用ConcurrentLinkedQueue或LinkedBlockingDeque ,但是它们仅返回数组,并且适配器需要一个List。
Is there any way to adapt this custom ArrayAdapter to use one of these thread safe methods or will I need to iterate over the array of objects in order to fill a List to use? 是否有任何方法可以使此自定义ArrayAdapter适应使用这些线程安全方法之一,或者我需要遍历对象数组以填充要使用的List?
The java.util.Collections class can be used to wrap a List, making it synchronized (ie thread safe). java.util.Collections类可用于包装List,使其同步(即线程安全)。 For example:
例如:
LinkedList<String> notThreadSafeList = new LinkedList<String>();
List<String> threadSafeList = Collections.synchronizedList(notThreadSafeList);
See also: 也可以看看:
http://developer.android.com/reference/java/util/Collections.html#synchronizedList(java.util.List ) http://developer.android.com/reference/java/util/Collections.html#synchronizedList(java.util.List )
我最终将列表转换为使用内部SQLite数据库,并使用SimpleCursorAdapter备份ListView。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.