[英]Android - Recycler View with GCM
I am using a RecyclerView
that show results that come from GCM
callbacks. 我正在使用显示来自GCM
回调的结果的RecyclerView
。 The RecyclerView
has a custom adapter a method add, there is also a progress bar that updates using an asynctask. RecyclerView
有一个添加方法的自定义适配器,还有一个进度条,可使用asynctask更新。
Message recieving over GCM
that works fine: 通过GCM
消息正常运行:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.add(new ResultRecord("asf", 89, 1000));
}
});
}
};
Add method in the custom adapter: 在自定义适配器中添加方法:
public void add(final ResultRecord result) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
results.add(0, result);
notifyItemInserted(0);
}
});
}
The problem is that the method add called and nothing happens on the UI. 问题是方法add被调用,UI上没有任何反应。 The method add called and then onBindViewHolder and the recycler view does not update. 先调用add方法再调用onBindViewHolder,然后回收站视图不会更新。 Only when the progress bar is finished the RecylcerView
is getting update with all the ViewHolder
s that has been added before. 仅当进度条完成时, RecylcerView
才会使用之前添加的所有ViewHolder
更新。
I have checked if the add method works from the onCreate
method and it worked fine. 我已经检查了add方法是否可以从onCreate
方法中正常工作。 Maybe this problem is related to threading. 也许这个问题与线程有关。
You have a Threading problem here. 您在这里遇到线程问题。
Your code is based on ArrayList, which isn't Thread-Safe. 您的代码基于不是线程安全的ArrayList。 You are calling the "Add" method from event, which called probably from multiple threads. 您正在从事件中调用“添加”方法,该方法可能是从多个线程中调用的。
You have to synchronize your code. 您必须同步您的代码。 Something like this: 像这样:
private final ReentrantLock lock = new ReentrantLock();
public void add(final ResultRecord result) {
lock.lock();
try {
AddNotThreadSafe(result); // Only one thread add in same time. Now is safe for executing.
} finally {
lock.unlock();
}
}
Now, move your original Add
code to separated method called AddNotThreadSafe
. 现在,将您原始的Add
代码移动到名为AddNotThreadSafe
单独方法中。
This should work. 这应该工作。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.