我有一个后台服务,它从服务器接收消息,并通过这些消息更新显示在 ListView 中的对象的内部属性。
我总是使用 runOnUiThread 方法来运行 listArrayAdapter.notifyOnDataSetChanged() 命令。
由于某种原因,有时 ListView 会刷新,它确实向我显示了属性更新,但有时却没有..
为了进行测试,我在我的 ListView 中添加了一个“刷新”按钮,当它按下时,会执行 listArrayAdapter.notifyOnDataSetChanged()。
每次单击按钮,视图都会完美刷新..
我真的不明白为什么在尝试从服务刷新时它并不总是有效,但我想我可能并不总是在 UIThread 上运行......
我真的很绝望,很高兴得到帮助..
我的代码
ServerConnectionManager.java - 扩展服务
//example of a command executed when a specific message received from the server:
//app is the Application variable
public void unFriend(int userId)
{
serverResponseManager.onUnFriend(app.getApplicationFriend(userId),false);
}
ServerResponseManager.java - 处理所有应用程序对服务器消息的响应的类:
public void onUnFriend(FacebookUser facebookUser, boolean isYouRemovedClient) {
//this is the property which will effect the ListView view when calling the
//arrayListAdataper.notifyOnDataSetChanged();
facebookUser.setApplicationFriend(false);
app.getApplicationFriends().remove(facebookUser);
app.getDatabaseManager().deleteApplicationFriend(facebookUser.getId());
//if the application is currently running in the UI (not on the background) it will run a method inside the BaseActivity
if (app.isApplicationInForeground())
{
app.getCurrentActivity().onUnFriend(facebookUser);
if (isYouRemovedClient)
app.showToast(facebookUser.getName() + " has removed from your friends", true);
else
app.showToast(facebookUser.getName() + " has removed you from friends", true);
}
}
BaseActivity.java - 为扩展它的所有活动设置所有默认配置的活动
//in this exemple the BaseActivity method does nothing but the ListViewActivity.java method override it
public void onUnFriend(FacebookUser facebookUser)
{
}
ListViewActivity.java - 扩展 BaseActivity 并在其中有一个 ListView,它应该反映在 ServerResponseManager 中的 public void onUnFriend(FacebookUser facebookUser, boolean isYouRemovedClient) 中所做的 FacebookUser 对象属性的更改。
@Override
public void onUnFriend(FacebookUser facebookUser)
{
updateView();
}
private void updateView()
{
runOnUiThread(updateViewRunnable());
}
private Runnable updateViewRunnable()
{
Runnable run = new Runnable() {
@Override
public void run() {
listArrayAdapter.notifyDataSetChanged();
}
};
return run;
}