Java tutorial
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yingke.shengtai.adapter; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.TextView.BufferType; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMChatRoom; import com.easemob.chat.EMConversation; import com.easemob.chat.EMConversation.EMConversationType; import com.easemob.chat.EMGroup; import com.easemob.chat.EMGroupManager; import com.easemob.chat.EMMessage; import com.easemob.chat.ImageMessageBody; import com.easemob.chat.TextMessageBody; import com.easemob.util.DateUtils; import com.easemob.util.EMLog; import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.yingke.shengtai.MyApplication; import com.yingke.shengtai.api.IApi; import com.yingke.shengtai.api.RequestListener; import com.yingke.shengtai.api.RequestManager; import com.yingke.shengtai.db.RobotUser; import com.yingke.shengtai.db.SmileUtils; import com.yingke.shengtai.db.User; import com.yingke.shengtai.moudle.ImidToNickNameData; import com.yingke.shengtai.moudle.UserDao; import com.yingke.shengtai.R; import com.yingke.shengtai.utils.Constant; import com.yingke.shengtai.utils.DemoHXSDKHelper; import com.yingke.shengtai.utils.HXSDKHelper; import com.yingke.shengtai.utils.JosnUtil; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * ?adpater * */ public class ChatAllHistoryAdapter extends ArrayAdapter<EMConversation> { private static final String TAG = "ChatAllHistoryAdapter"; private LayoutInflater inflater; private List<EMConversation> conversationList; private List<EMConversation> copyConversationList; private ConversationFilter conversationFilter; private boolean notiyfyByFilter; private Map<String, User> map; private Context context; private UserDao userDao; private String rootIMid; private View view; private ListView listView; Handler UIHandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); if (msg.what == 0) { notifyDataSetChanged(); } } }; public ChatAllHistoryAdapter(Context context, int textViewResourceId, List<EMConversation> objects, View view, ListView listView) { super(context, textViewResourceId, objects); this.conversationList = objects; copyConversationList = new ArrayList<EMConversation>(); copyConversationList.addAll(objects); inflater = LayoutInflater.from(context); userDao = new UserDao(context); this.view = view; this.context = context; this.listView = listView; } public void rootIimid(String rootIMid) { this.rootIMid = rootIMid; } public void notifys() { super.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.row_chat_history, parent, false); } ViewHolder holder = (ViewHolder) convertView.getTag(); if (holder == null) { holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.name); holder.unreadLabel = (TextView) convertView.findViewById(R.id.unread_msg_number); holder.message = (TextView) convertView.findViewById(R.id.message); holder.time = (TextView) convertView.findViewById(R.id.time); holder.avatar = (ImageView) convertView.findViewById(R.id.avatar); holder.msgState = convertView.findViewById(R.id.msg_state); holder.list_item_layout = (RelativeLayout) convertView.findViewById(R.id.list_item_layout); convertView.setTag(holder); } if (position == 0) { map = new UserDao(context).getContactMapss(); } // ?? EMConversation conversation = getItem(position); // ?username String username = conversation.getUserName(); if (conversation.getType() == EMConversationType.GroupChat) { // ???? holder.avatar.setImageResource(R.mipmap.group_icon); EMGroup group = EMGroupManager.getInstance().getGroup(username); holder.name.setText(group != null ? group.getGroupName() : username); } else if (conversation.getType() == EMConversationType.ChatRoom) { holder.avatar.setImageResource(R.mipmap.group_icon); EMChatRoom room = EMChatManager.getInstance().getChatRoom(username); holder.name.setText(room != null && !TextUtils.isEmpty(room.getName()) ? room.getName() : username); } else { // UserUtils.setUserAvatar(getContext(), username, holder.avatar); Map<String, RobotUser> robotMap = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotList(); if (robotMap != null && robotMap.containsKey(username)) { String nick = robotMap.get(username).getNick(); if (!TextUtils.isEmpty(nick)) { holder.name.setText(nick); } else { holder.name.setText(username); } } else { // UserUtils.setUserNick(username, holder.name); } } if (map == null || map.get(username) == null || TextUtils.isEmpty(map.get(username).getNick())) { // holder.name.setText(username); Map<String, String> map = new HashMap<String, String>(); map.put("imid", username); map.put("token", MyApplication.getInstance().getUserInfor().getUserdetail().getToken()); if (TextUtils.isEmpty(MyApplication.getInstance().getUserInfor().getUserdetail().getSid())) { map.put("sid", "0"); map.put("uid", MyApplication.getInstance().getUserInfor().getUserdetail().getUid()); } else { map.put("sid", MyApplication.getInstance().getUserInfor().getUserdetail().getSid()); map.put("uid", "0"); } holder.name.setText(""); postRequest(holder.name, username, map); } else { holder.name.setText(map.get(username).getNick()); } if (!(map == null || map.get(username) == null || TextUtils.isEmpty(map.get(username).getSex()))) { String sex = map.get(username).getSex(); if (TextUtils.equals("0", sex)) { holder.avatar.setImageResource(R.mipmap.male_yewu); } if (TextUtils.equals("1", sex)) { holder.avatar.setImageResource(R.mipmap.meal_yewu); } holder.avatar.setVisibility(View.VISIBLE); } else { holder.avatar.setVisibility(View.GONE); if ((map != null && map.get(username) != null) && !TextUtils.isEmpty(map.get(username).getNick())) { Map<String, String> map = new HashMap<String, String>(); map.put("imid", username); map.put("token", MyApplication.getInstance().getUserInfor().getUserdetail().getToken()); if (TextUtils.isEmpty(MyApplication.getInstance().getUserInfor().getUserdetail().getSid())) { map.put("sid", "0"); map.put("uid", MyApplication.getInstance().getUserInfor().getUserdetail().getUid()); } else { map.put("sid", MyApplication.getInstance().getUserInfor().getUserdetail().getSid()); map.put("uid", "0"); } postRequest(holder.name, username, map); } } if (conversation.getUnreadMsgCount() > 0) { // ? holder.unreadLabel.setText(String.valueOf(conversation.getUnreadMsgCount())); holder.unreadLabel.setVisibility(View.VISIBLE); } else { holder.unreadLabel.setVisibility(View.INVISIBLE); } if (conversation.getMsgCount() != 0) { // ???itemmessage EMMessage lastMessage = conversation.getLastMessage(); holder.message.setText( SmileUtils.getSmiledText(getContext(), getMessageDigest(lastMessage, (this.getContext()))), BufferType.SPANNABLE); holder.time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime()))); if (lastMessage.direct == EMMessage.Direct.SEND && lastMessage.status == EMMessage.Status.FAIL) { holder.msgState.setVisibility(View.VISIBLE); } else { holder.msgState.setVisibility(View.GONE); } } return convertView; } public void postRequest(final TextView text, final String userName, final Map<String, String> map) { FormEncodingBuilder builder = new FormEncodingBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } RequestBody formBody = builder.build(); Request request = new Request.Builder().url(IApi.URL_IMID_NAME).header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json").addHeader("Content-Type", "application/json;charset=utf-8") .addHeader("Content-Length", "length").post(formBody).build(); RequestManager.getOkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String json = response.body().string(); ImidToNickNameData data = JosnUtil.gson.fromJson(json, new TypeToken<ImidToNickNameData>() { }.getType()); if (data != null && TextUtils.equals("1", "1")) { try { User user = new User(); user.setNick(data.getDetaillist().get(0).getDisplayname()); user.setUsername(data.getDetaillist().get(0).getImid()); user.setSex(data.getDetaillist().get(0).getSex()); userDao.saveContactsss(user); UIHandler.sendEmptyMessage(0); } catch (Exception e) { } } } } }); } public String getName(String username) { if (map == null || map.get(username) == null || TextUtils.isEmpty(map.get(username).getNick())) { return username; } else { return map.get(username).getNick(); } } /** * ??????? * * @param message * @param context * @return */ private String getMessageDigest(EMMessage message, Context context) { String digest = ""; switch (message.getType()) { case LOCATION: // ?? if (message.direct == EMMessage.Direct.RECEIVE) { // sdk??ui???string // digest = EasyUtils.getAppResourceString(context, // "location_recv"); digest = getStrng(context, R.string.location_recv); digest = String.format(digest, message.getFrom()); return digest; } else { // digest = EasyUtils.getAppResourceString(context, // "location_prefix"); digest = getStrng(context, R.string.location_prefix); } break; case IMAGE: // ? ImageMessageBody imageBody = (ImageMessageBody) message.getBody(); digest = getStrng(context, R.string.picture) + imageBody.getFileName(); break; case VOICE:// ? digest = getStrng(context, R.string.voice); break; case VIDEO: // ? digest = getStrng(context, R.string.video); break; case TXT: // ? if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).isRobotMenuMessage(message)) { digest = ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getRobotMenuMessageDigest(message); } else if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = getStrng(context, R.string.voice_call) + txtBody.getMessage(); } else { TextMessageBody txtBody = (TextMessageBody) message.getBody(); digest = txtBody.getMessage(); } break; case FILE: // ? digest = getStrng(context, R.string.file); break; default: EMLog.e(TAG, "unknow type"); return ""; } return digest; } private static class ViewHolder { /** ?? */ TextView name; /** ? */ TextView unreadLabel; /** ??? */ TextView message; /** ??? */ TextView time; /** ? */ ImageView avatar; /** ?????? */ View msgState; /** list? */ RelativeLayout list_item_layout; } String getStrng(Context context, int resId) { return context.getResources().getString(resId); } @Override public Filter getFilter() { if (conversationFilter == null) { conversationFilter = new ConversationFilter(conversationList); } return conversationFilter; } private class ConversationFilter extends Filter { List<EMConversation> mOriginalValues = null; public ConversationFilter(List<EMConversation> mList) { mOriginalValues = mList; } @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); if (mOriginalValues == null) { mOriginalValues = new ArrayList<EMConversation>(); } if (prefix == null || prefix.length() == 0) { results.values = copyConversationList; results.count = copyConversationList.size(); } else { String prefixString = prefix.toString(); final int count = mOriginalValues.size(); final ArrayList<EMConversation> newValues = new ArrayList<EMConversation>(); for (int i = 0; i < count; i++) { final EMConversation value = mOriginalValues.get(i); String username = value.getUserName(); EMGroup group = EMGroupManager.getInstance().getGroup(username); if (group != null) { username = group.getGroupName(); } // First match against the whole ,non-splitted value if (username.startsWith(prefixString)) { newValues.add(value); } else { final String[] words = username.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { conversationList.clear(); conversationList.addAll((List<EMConversation>) results.values); if (results.count > 0) { notiyfyByFilter = true; notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); if (!notiyfyByFilter) { copyConversationList.clear(); copyConversationList.addAll(conversationList); notiyfyByFilter = false; } } }