来自Service的Android ListView notifyDataSetChanged()

Asa*_*evo 3 android listview android-arrayadapter

我有一个后台服务,它从服务器接收消息,并使用这些消息更新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);
    }
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

BaseActivity.java - 一个为所有扩展它的活动设置所有默认配置的活动

//in this exemple the BaseActivity method does nothing but the ListViewActivity.java method override it
public void onUnFriend(FacebookUser facebookUser)
{                   

}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

paw*_*eba 9

不要混淆业务逻辑.它看起来很复杂,难以阅读.

  1. 在您的服务中,使用有关更新的信息广播意图.
  2. Activity这里ListView是,创建并注册BroadcastReceiverIntentFilter您的更新事件.
  3. 在句柄更新事件的onReceive方法中BroadcastReceiver,例如更新列表.

  • 这也适用于Android支持包中提供的"LocalBroadcastManager",用于将"广播"仅保留在您的应用中.或者,试试Otto:http://square.github.com/otto/ (4认同)