Android:更新数据集,其中数据集是HashMaps

时间:2016-01-12 14:53:58

标签: java android arraylist adapter notifydatasetchanged

我最近开始研究Android项目,由于我对UI编程缺乏了解,当我尝试动态地向UI添加条目时,我发现自己处于修复状态。

我正在开发一个聊天应用程序,当收到新消息时,应该在底部添加。为此,我需要通知数据集已更改。当我直接调用数据集发生了变化时,我收到了一个错误。所以我在适配器上使用了本地广播接收器。

不幸的是,我不知道如何传递包含HashMap的ArrayList。我将发布适配器的代码以及我尝试通知数据已更改的位置。我希望有人可以帮助我。谢谢了很多..: - )

代码:

    public static void recieveUpdatedMessage(String channelName, Map<String, Object> input){

//The input here contains message from our PUSH system 

  Intent intent = new Intent();
                    HashMap<String, String> insertMap = new HashMap<>();
                    insertMap.put(chatText, String.valueOf(input.get("text")));
                    insertMap.put(firstName,String.valueOf("firstname"));
                    insertMap.put(groupChannel, "/service/chat" + String.valueOf(groupAccountId));

                    ArrayList<HashMap<String, String>> chatMessagesHashMapList = new ArrayList<HashMap<String, String>>();
                    chatMessagesHashMapList.add(insertMap);

// Below is where I am trying to send data.
                 //  intent.putExtra(chatMessagesHashMapList);//send any data to your adapter
                    intent.setAction("myaction");
                    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

适配器代码,它位于同一个java文件中:

public class ChatMessagesAdapter extends BaseAdapter {


private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent)
    {

        if(intent.getAction().equals("MYREFRESH"))
        {
            notifyDataSetChanged();
        }
    }
};

    private Activity activity = null;
    private ArrayList<HashMap<String, String>> data;
    private LayoutInflater inflater = null;


    public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("MYREFRESH");
        LocalBroadcastManager.getInstance(context).registerReceiver(broadcastReceiver, intentFilter);

        activity = a;
        data = d;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.chat_messages_row, parent, false);

        TextView chatText = (TextView) vi.findViewById(R.id.chatText);
        ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
        TextView firstName = (TextView) vi.findViewById(R.id.personName);

        HashMap<String, String> chatList = new HashMap<>();
        chatList = data.get(position);

        chatText.setText(chatList.get(ChatMessagesActivity.chatText));
        userImage.setImageBitmap(convertByteArrayToBitmap(chatList.get(ChatMessagesActivity.chatImage)));
        firstName.setText(chatList.get(ChatMessagesActivity.firstName));
        return vi;
    }

}

我希望我很清楚。如果有任何遗漏,请告诉我。如何告诉活动有新消息并将其放在底部。

2 个答案:

答案 0 :(得分:2)

您可以使用bundle将您使用HashMap创建数据的最新数据直接传递给intent。 &安培;从BroadCastReceiver的onReceive方法中检索它

如何传递数据检查下面的更新方法recieveUpdatedMessage recieveUpdatedMessage

public static void recieveUpdatedMessage(String channelName, Map<String, Object> input) {

//The input here contains message from our PUSH system

        Intent intent = new Intent();
        HashMap<String, String> insertMap = new HashMap<>();
        insertMap.put(chatText, String.valueOf(input.get("text")));
        insertMap.put(firstName, String.valueOf("firstname"));
        insertMap.put(groupChannel, "/service/chat" + String.valueOf(groupAccountId));

        ArrayList<HashMap<String, String>> chatMessagesHashMapList = new ArrayList<HashMap<String, String>>();
        // Added your map into Bundler as a Serializable
        Bundle bundle = new Bundle();
        bundle.putSerializable("chatMapKey", insertMap);
//        after adding map into bundle . bundle is added into Intent
        intent.putExtras(bundle);
// Below is where I am trying to send data.
        //  intent.putExtra(chatMessagesHashMapList);//send any data to your adapter
        intent.setAction("MYREFRESH");
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }

如何从捆绑包中检索数据在列表视图中更新它,请检查您的ChatMessagesAdapter更新代码。

<强> ChatMessagesAdapter

public class ChatMessagesAdapter extends BaseAdapter {


        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if (intent.getAction().equals("MYREFRESH")) {
                    Bundle bundle = intent.getExtras();
                    // Get the bundle from intent
                    if (bundle!=null && bundle.containsKey("chatMapKey")) {
//                        get the Serializable object which is pass as a broadcast from the Bundle
                        refreshChat((HashMap<String, String>) bundle.getSerializable("chatMapKey"));
                    }

                }
            }
        };

        private Activity activity = null;
        private ArrayList<HashMap<String, String>> data;
        private LayoutInflater inflater = null;
        private int size = 0;

        public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {

            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("MYREFRESH");
            LocalBroadcastManager.getInstance(context).registerReceiver(broadcastReceiver, intentFilter);

            activity = a;
            data = d;
            if (data != null)
                size = data.size();
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

        public void refreshChat(HashMap<String, String> newChatMap) {
            if (data == null) {// Added Condition for safe side you can remove it
                data = new ArrayList<HashMap<String, String>>();
            }
            data.add(newChatMap);
            size = data.size();
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return size;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {


            View vi = convertView;
            if (convertView == null)
                vi = inflater.inflate(R.layout.chat_messages_row, parent, false);

            TextView chatText = (TextView) vi.findViewById(R.id.chatText);
            ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
            TextView firstName = (TextView) vi.findViewById(R.id.personName);

            HashMap<String, String> chatList = new HashMap<>();
            chatList = data.get(position);

            chatText.setText(chatList.get(ChatMessagesActivity.chatText));
            userImage.setImageBitmap(convertByteArrayToBitmap(chatList.get(ChatMessagesActivity.chatImage)));
            firstName.setText(chatList.get(ChatMessagesActivity.firstName));
            return vi;
        }

    }

<强> 建议

  • 避免像使用过的那样使用广播接收器。注册 活动onReusme / onStart&amp;在onPause / onStop中取消注册 方法check this The visible lifetime

  • 尝试使用数据库维护数据,就像在消息时一样 接收将其插入数据库&amp;在刷新数据时获取 来自数据库的数据

答案 1 :(得分:2)

你真的不应该那样使用BroadcastReceiver。尝试向add添加Adapter方法,以便更轻松地添加项目并自动通知更改。

public void add(HashMap<String, String> item) {
    data.add(item);
    notifyDataSetChanged();
}

然后在recieveUpdatedMessage方法中,您可以执行与以下内容类似的操作。

public void recieveUpdatedMessage(String channelName, Map<String, Object> input) {
    HashMap<String, String> insertMap = new HashMap<>();
    insertMap.put(chatText, input.get("text").toString());
    insertMap.put(firstName, input.get("firstname").toString());
    insertMap.put(groupChannel, "/service/chat" + input.get("groupaccountid").toString());

    myAdapter.add(insertMap);
}

一些需要改进的注意事项

最好不要使用HashMap,而是创建一个类来为您保存数据。

由于您的BaseAdapter已使用List,因此您可以扩展ArrayAdapter,因为它已经有一个add方法,默认情况下也会调用notifyDataSetChanged()