Advertisement
Kvarz

notifydatasetchanged with threads problem

Sep 9th, 2015
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.37 KB | None | 0 0
  1. package com.gfl.linewise.chat.ui;
  2.  
  3. import android.content.BroadcastReceiver;
  4. import android.content.ComponentName;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.IntentFilter;
  8. import android.content.ServiceConnection;
  9. import android.os.Bundle;
  10. import android.os.IBinder;
  11. import android.support.v4.content.LocalBroadcastManager;
  12. import android.view.View;
  13. import android.widget.AdapterView;
  14. import android.widget.Button;
  15. import android.widget.EditText;
  16. import android.widget.ListView;
  17. import android.widget.Spinner;
  18. import android.widget.Toast;
  19.  
  20. import com.alshvets.core.structure.helpers.Dialogs;
  21. import com.alshvets.core.structure.helpers.Logger;
  22. import com.alshvets.core.structure.models.error.IError;
  23. import com.alshvets.core.structure.requests.mock.ICallback;
  24. import com.gfl.linewise.Constants;
  25. import com.gfl.linewise.R;
  26. import com.gfl.linewise.api.models.Session;
  27. import com.gfl.linewise.api.models.UserProfile;
  28. import com.gfl.linewise.api.models.responses.Profiles;
  29. import com.gfl.linewise.api.models.responses.UserInfo;
  30. import com.gfl.linewise.api.requests.GetAllUsersRequest;
  31. import com.gfl.linewise.api.requests.GetUserInfoRequest;
  32. import com.gfl.linewise.chat.ChatManager;
  33. import com.gfl.linewise.chat.ChatUsersSearch;
  34. import com.gfl.linewise.chat.MessageService;
  35. import com.gfl.linewise.chat.adapters.ListUsersAdapter;
  36. import com.gfl.linewise.chat.adapters.UserSpinnerAdapter;
  37. import com.gfl.linewise.chat.models.ChatUser;
  38. import com.gfl.linewise.chat.models.ChatUsers;
  39. import com.gfl.linewise.chat.models.Message;
  40. import com.gfl.linewise.chat.models.UserSpinner;
  41. import com.gfl.linewise.preferences.AppPreference;
  42. import com.gfl.linewise.ui.activities.CustomTitleActivity;
  43. import com.google.gson.Gson;
  44. import com.parse.FindCallback;
  45. import com.parse.GetCallback;
  46. import com.parse.ParseException;
  47. import com.parse.ParseObject;
  48. import com.parse.ParseQuery;
  49. import com.parse.ParseUser;
  50. import com.sinch.android.rtc.PushPair;
  51. import com.sinch.android.rtc.messaging.MessageClient;
  52. import com.sinch.android.rtc.messaging.MessageClientListener;
  53. import com.sinch.android.rtc.messaging.MessageDeliveryInfo;
  54. import com.sinch.android.rtc.messaging.MessageFailureInfo;
  55. import com.sinch.android.rtc.messaging.WritableMessage;
  56.  
  57. import java.util.ArrayList;
  58. import java.util.Arrays;
  59. import java.util.Collections;
  60. import java.util.Comparator;
  61. import java.util.Date;
  62. import java.util.HashMap;
  63. import java.util.Hashtable;
  64. import java.util.List;
  65. import java.util.Map;
  66. import java.util.Map.Entry;
  67. import java.util.Set;
  68.  
  69. import static android.text.TextUtils.isEmpty;
  70. import static com.alshvets.core.structure.helpers.Dialogs.showToast;
  71. import static com.gfl.linewise.helpers.Intents.startUserActivity;
  72.  
  73. public class ListUsersActivity extends CustomTitleActivity implements ListUsersAdapter.OnChatUserClickListener, View.OnClickListener {
  74.  
  75. private ListView usersListView;
  76.  
  77. private List<UserProfile> allUsersServerResponseList = new ArrayList<>();
  78. private List<UserProfile> allChatUsersList = Collections.synchronizedList(new ArrayList());
  79. private Hashtable<String, Message> firstUserMessages = new Hashtable<>();
  80. private ListUsersAdapter adapter;
  81.  
  82. private MessageService.MessageServiceInterface messageService;
  83. private ServiceConnection serviceConnection = new MyServiceConnection();
  84. private MessageClientListener messageClientListener = new MyMessageClientListener();
  85.  
  86. private HashMap<String, String> allChatUsers = new HashMap<>();
  87.  
  88. private UserSpinnerAdapter userSpinnerAdapter;
  89.  
  90. private ParseUser currentUser;
  91.  
  92. private String userObjectId;
  93. private String serverUserId;
  94.  
  95. private EditText editTextMessage;
  96.  
  97. private volatile List<UserProfile> allChatUsersListOrdered;
  98.  
  99.  
  100. @Override
  101. protected void onCreate(Bundle savedInstanceState) {
  102. super.onCreate(savedInstanceState);
  103. setContentView(R.layout.activity_list_users);
  104. Logger.debug(getClass(), "ListUsersActivity onCreate");
  105.  
  106.  
  107. currentUser = ParseUser.getCurrentUser();
  108. if (currentUser != null) {
  109. bindService(new Intent(this, MessageService.class), serviceConnection, BIND_AUTO_CREATE);
  110.  
  111. } else {
  112. Logger.debug(getClass(), "currentUser");
  113. }
  114. mProgressDialog.show();
  115. mProgressDialog.setCancelable(true);
  116.  
  117. registerBroadcastReceiver();
  118.  
  119. buttonBack = findViewById(R.id.button_back);
  120. buttonBack.setOnClickListener(this);
  121.  
  122. usersListView = (ListView) findViewById(R.id.usersListView);
  123.  
  124. adapter = new ListUsersAdapter(this, this, allChatUsersList, firstUserMessages);
  125. usersListView.setAdapter(adapter);
  126. usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  127. @Override
  128. public void onItemClick(AdapterView<?> a, View v, int i, long l) {
  129. // startChatWithUser();
  130. getPointsOfCurrentUser(allChatUsersList.get(i));
  131. }
  132. });
  133.  
  134. editTextMessage = (EditText) findViewById(R.id.editTextMessage);
  135. Button btnSendComment = (Button) findViewById(R.id.btnSendComment);
  136. btnSendComment.setOnClickListener(this);
  137.  
  138. getAllUsers();
  139. // ChatManager.getInstance().bindService(this);
  140. }
  141.  
  142. private void getPointsOfCurrentUser(final UserProfile userProfile) {
  143. Session session = new Session(AppPreference.getInstance().getSession());
  144.  
  145. new GetUserInfoRequest(session, new ICallback<UserInfo>() {
  146. @Override
  147. public void onSuccess(UserInfo userInfo) {
  148. Logger.debug(getClass(), "GetUserInfoRequest: OK");
  149. if (userInfo != null) {
  150. // updateUserInfo(userInfo);
  151. AppPreference.getInstance().setUserInfoResponse(new Gson().toJson(userInfo));
  152. startChatWithUser(userProfile);
  153. }
  154. }
  155.  
  156. @Override
  157. public void onError(IError error) {
  158. Logger.error(getClass(), "GetUserInfoRequest error");
  159. }
  160. }).execute();
  161. }
  162.  
  163. private void startChatWithUser(final UserProfile userProfile) {
  164. String username = userProfile.getEmail();
  165. ParseQuery<ParseUser> query = ParseUser.getQuery();
  166. query.setLimit(1000);
  167. query.whereEqualTo("username", username);
  168. query.findInBackground(new FindCallback<ParseUser>() {
  169.  
  170. @Override
  171. public void done(List<ParseUser> userList, ParseException e) {
  172. if (e == null) {
  173. //start the messaging activity
  174. Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
  175. intent.putExtra(MessagingActivity.RECIPIENT_ID, userList.get(0).getObjectId());
  176. intent.putExtra(MessagingActivity.USER_ID, userProfile.getId());
  177. // intent.putExtra(MessagingActivity.POINTS, points);
  178. intent.putExtra(MessagingActivity.PHOTO_URL, userProfile.getPhoto());
  179. startActivity(intent);
  180. } else {
  181. safeClose(mProgressDialog);
  182. Toast.makeText(getApplicationContext(),
  183. "Error loading user list",
  184. Toast.LENGTH_LONG).show();
  185. }
  186. }
  187. });
  188. }
  189.  
  190. @Override
  191. public void onResume() {
  192. super.onResume();
  193. setTitle(getString(R.string.title_activity_messaging));
  194. getAllUsers();
  195. }
  196.  
  197. private void registerBroadcastReceiver() {
  198. BroadcastReceiver receiver = new BroadcastReceiver() {
  199. @Override
  200. public void onReceive(Context context, Intent intent) {
  201. Boolean success = intent.getBooleanExtra("success", false);
  202. if (!success) {
  203. safeClose(mProgressDialog);
  204. Toast.makeText(getApplicationContext(), "Sorry, messaging service not working.",
  205. Toast.LENGTH_LONG).show();
  206. }
  207. }
  208. };
  209.  
  210. LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter
  211. ("com.gfl.linewise.chat.ui.ListUsersActivity"));
  212. }
  213.  
  214. public void getAllUsers() {
  215. Session session = new Session(AppPreference.getInstance().getSession());
  216.  
  217. new GetAllUsersRequest(session, new ICallback<Profiles>() {
  218. @Override
  219. public void onSuccess(Profiles profiles) {
  220. Logger.debug(getClass(), "GetAllUsersRequest: All users received");
  221.  
  222. if (profiles != null) {
  223. allUsersServerResponseList = profiles.getProfiles();
  224. if (allUsersServerResponseList != null) {
  225.  
  226. //to initialize send message layout
  227. getAllChatUsers();
  228.  
  229. if (currentUser != null) {
  230. ParseQuery<ParseObject> query = ParseQuery.getQuery(ChatManager.CHAT_USER_FRIENDS);
  231. query.getInBackground(currentUser.get("chatUserObjectId").toString(), new GetChatUserListCallback());
  232. } else {
  233. safeClose(mProgressDialog);
  234. Logger.debug(getClass(), "currentUser == null");
  235. }
  236. }
  237. }
  238.  
  239. }
  240.  
  241. @Override
  242. public void onError(IError error) {
  243. Logger.error(getClass(), "GetAllUsersRequest error");
  244. safeClose(mProgressDialog);
  245. showToast(ListUsersActivity.this, R.string.inet_problems);
  246. }
  247. }).execute();
  248. }
  249.  
  250. private void getAllChatUsers() {
  251. String currentUserId = "";
  252. if(ParseUser.getCurrentUser() != null) {
  253. currentUserId = ParseUser.getCurrentUser().getObjectId();
  254. } else {
  255. return;
  256. }
  257.  
  258. //don't include yourself in the list
  259. ParseQuery<ParseUser> query = ParseUser.getQuery();
  260. query.setLimit(1000);
  261. query.whereNotEqualTo("objectId", currentUserId);
  262. query.findInBackground(new FindCallback<ParseUser>() {
  263. public void done(List<ParseUser> userList, ParseException e) {
  264. if (e == null) {
  265. for (int i = 0; i < userList.size(); i++) {
  266. allChatUsers.put(userList.get(i).getUsername(), userList.get(i).getObjectId());
  267. }
  268. initializeSendMessageSection();
  269.  
  270. } else {
  271. Toast.makeText(getApplicationContext(),
  272. "Error loading user list",
  273. Toast.LENGTH_LONG).show();
  274. }
  275. }
  276. });
  277. }
  278.  
  279. private void initializeSendMessageSection() {
  280.  
  281. //convert allUsersServerResponseList into allUsersServerResponseMap <Email, UserProfile>
  282. Map<String, UserProfile> allUsersServerResponseMap = new HashMap<>();
  283. for (UserProfile i : allUsersServerResponseList) allUsersServerResponseMap.put(i.getEmail(), i);
  284.  
  285. //all server users that have chat account Map<chat Object id, UserSpinner>
  286. final List<UserSpinner> allUsersWithChat = new ArrayList<>();
  287.  
  288. for (Entry<String, UserProfile> entry : allUsersServerResponseMap.entrySet()) {
  289. String key = entry.getKey();
  290. UserProfile value = entry.getValue();
  291.  
  292. if(allChatUsers.containsKey(key)){
  293. String objectId = allChatUsers.get(key);
  294. UserSpinner userSpinner = new UserSpinner(objectId, key, value);
  295. allUsersWithChat.add(userSpinner);
  296. }
  297. }
  298.  
  299. Logger.debug(getClass(), "initializing spinner adapter");
  300. Spinner spinner = (Spinner) findViewById(R.id.usersSpinner);
  301. userSpinnerAdapter = new UserSpinnerAdapter(this, allUsersWithChat);
  302. spinner.setAdapter(userSpinnerAdapter);
  303. spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  304.  
  305. @Override
  306. public void onItemSelected(AdapterView<?> parent, View view,
  307. int pos, long id) {
  308. serverUserId = allUsersWithChat.get(pos).getUserProfile().getId();
  309. userObjectId = allUsersWithChat.get(pos).getObjectId();
  310. userSpinnerAdapter.notifyDataSetChanged();
  311. }
  312.  
  313. @Override
  314. public void onNothingSelected(AdapterView<?> arg0) {
  315. }
  316. });
  317.  
  318. }
  319.  
  320. private class GetChatUserListCallback implements GetCallback<ParseObject>, ChatUsersSearch.OnChatUsersFoundListener {
  321.  
  322. @Override
  323. public void done(ParseObject parseObject, ParseException e) {
  324. if (e == null) {
  325. Logger.debug(getClass(), "Chat: chat list object FOUND " + parseObject.getObjectId());
  326.  
  327. String jsonString = (String) parseObject.get("chatUsers");
  328. Logger.debug(getClass(), "chatUsers json! " + jsonString);
  329. ChatUsers chatUsers = new Gson().fromJson(jsonString, ChatUsers.class);
  330.  
  331. Logger.debug(getClass(), "CHAT FRIENDS SIZE: " + chatUsers.getChatUsers().size());
  332.  
  333. if (chatUsers.getChatUsers().size() > 0) {
  334. ChatUsersSearch chatUsersSearch = new ChatUsersSearch(this);
  335. chatUsersSearch.startSearch(chatUsers.getChatUsers());
  336. } else {
  337. safeClose(mProgressDialog);
  338. }
  339.  
  340. } else {
  341. if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
  342. Logger.error(getClass(), "Chat: ParseException.OBJECT_NOT_FOUND");
  343. safeClose(mProgressDialog);
  344. } else {
  345. Logger.error(getClass(), "Chat: unknown error, debug");
  346. }
  347. }
  348. }
  349.  
  350. @Override
  351. public void onChatUsersFound(Hashtable<String, ChatUser> chatUserFriends) {
  352. Logger.debug(getClass(), "ListUsersActivity onChatUsersFound");
  353. getChatUsersFromServerUsers(chatUserFriends);
  354. // ChatManager.getInstance().calculateUnreadMessages(chatUserFriends);
  355. }
  356. }
  357.  
  358. private void getChatUsersFromServerUsers(Hashtable<String, ChatUser> chatUserFriends) {
  359.  
  360. Logger.debug(getClass(), "getChatUsersFromServerUsers");
  361. Logger.debug(getClass(), "chatFriends size " + chatUserFriends.size());
  362.  
  363. Hashtable<String, ChatUser> chatFriends = chatUserFriends;
  364. for (Entry<String, ChatUser> entry : chatFriends.entrySet()) {
  365. String key = entry.getKey();
  366. ChatUser value = entry.getValue();
  367. Logger.debug(getClass(), "chatUser key" + key);
  368. Logger.debug(getClass(), "chatUser getSenderId: " + value.getSenderId());
  369. Logger.debug(getClass(), "chatUser getMessagesAmount: " + value.getMessagesAmount());
  370.  
  371. iterateAllChatUsers(key, chatUserFriends.size());
  372. }
  373. }
  374.  
  375. private void iterateAllChatUsers(final String senderId, final int friendsSize) {
  376. Logger.debug(getClass(), "iterateAllChatUsers");
  377.  
  378. for (Map.Entry<String, ChatUser> entry : ChatManager.getChatUsers().getChatUsers().entrySet()) {
  379. String key = entry.getKey();
  380. ChatUser value = entry.getValue();
  381. Logger.debug(getClass(), "chatUser key" + key);
  382. Logger.debug(getClass(), "chatUser getSenderId: " + value.getSenderId());
  383. Logger.debug(getClass(), "chatUser getMessagesAmount: " + value.getMessagesAmount());
  384.  
  385. Logger.debug(getClass(), "email of user! " + value.getUsername());
  386. for (UserProfile userProfile : allUsersServerResponseList) {
  387. if (userProfile.getEmail().equals(value.getUsername())) {
  388. allChatUsersList.add(userProfile);
  389. if (adapter != null) {
  390. adapter.notifyDataSetChanged();
  391. }
  392. getLastMessageByUser(key, userProfile.getId(), friendsSize);
  393. }
  394. }
  395. }
  396. }
  397.  
  398. private void getLastMessageByUser(final String senderId, final String userId, final int friendsSize) {
  399. Logger.debug(getClass(), "getLastMessageByUser");
  400. final String currentUserId = currentUser.getObjectId();
  401. String[] userIds = {currentUserId, senderId};
  402.  
  403. ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
  404. query.whereContainedIn("senderId", Arrays.asList(userIds));
  405. query.whereContainedIn("recipientId", Arrays.asList(userIds));
  406. query.orderByDescending("createdAt");
  407. query.setLimit(1);
  408. query.findInBackground(new FindCallback<ParseObject>() {
  409. @Override
  410. public void done(List<ParseObject> messageList, com.parse.ParseException e) {
  411. if (e == null) {
  412. WritableMessage message = new WritableMessage(messageList.get(0).get("recipientId").
  413. toString(), messageList.get(0).get("messageText").toString());
  414.  
  415. Date createdAt = messageList.get(0).getCreatedAt();
  416. long createdAtMilliseconds = createdAt.getTime();
  417.  
  418. Message messageObj = new Message(message.getTextBody(), createdAtMilliseconds);
  419. firstUserMessages.put(userId, messageObj);
  420.  
  421. if (friendsSize <= firstUserMessages.size()) {
  422. orderChatUsersByMessages();
  423. }
  424. }
  425. }
  426. });
  427. }
  428.  
  429. private void orderChatUsersByMessages() {
  430. Logger.debug(getClass(), "orderChatUsersByMessages");
  431. //create map with userId and Message object
  432. Map<String, Long> userMessageDateMap = new HashMap<>();
  433. for (Entry<String, Message> entry : firstUserMessages.entrySet()) {
  434. long createdMillis = entry.getValue().getCreatedAt();
  435. userMessageDateMap.put(entry.getKey(), createdMillis);
  436. }
  437. Set<Entry<String, Long>> userSet = userMessageDateMap.entrySet();
  438.  
  439. //get ordered list with user Id's by time of created message
  440. List<Entry<String, Long>> userList = new ArrayList<>(userSet);
  441. Collections.sort(userList, new Comparator<Entry<String, Long>>() {
  442. public int compare(Entry<String, Long> o1, Entry<String, Long> o2) {
  443. return (o2.getValue()).compareTo(o1.getValue());
  444. }
  445. });
  446.  
  447. //convert allChatUsersList into allChatUsersMap
  448. Map<String, UserProfile> allChatUsersMap = new HashMap<>();
  449. for (UserProfile i : allChatUsersList) allChatUsersMap.put(i.getId(), i);
  450.  
  451. //fill List with ordered users
  452. allChatUsersListOrdered = Collections.synchronizedList(new ArrayList());
  453. for (Entry<String, Long> entry : userList) {
  454. if (allChatUsersMap.containsKey(entry.getKey())) {
  455. allChatUsersListOrdered.add(allChatUsersMap.get(entry.getKey()));
  456. }
  457. }
  458.  
  459.  
  460.  
  461. Logger.debug(getClass(), "update adapter only now!");
  462. safeClose(mProgressDialog);
  463. // if (adapter != null) {
  464. // adapter.notifyDataSetChanged();
  465. // }
  466. ListUsersActivity.this.runOnUiThread(new Runnable() {
  467.  
  468. @Override
  469. public void run() {
  470. allChatUsersList.clear();
  471. allChatUsersList.addAll(allChatUsersListOrdered);
  472. if (adapter != null) {
  473. adapter.notifyDataSetChanged();
  474. }
  475. }
  476. });
  477.  
  478.  
  479. }
  480.  
  481. // private class ReceiverThread extends Thread {
  482. // @Override
  483. // public void run() {
  484. // ListUsersActivity.this.runOnUiThread(new Runnable() {
  485. //
  486. // @Override
  487. // public void run() {
  488. // adapter.notifyDataSetChanged();
  489. // }
  490. // });
  491. // }
  492.  
  493. @Override
  494. public void onChatUserClicked(String userId) {
  495. startUserActivity(this, userId);
  496. }
  497.  
  498. @Override
  499. public void onChatUserProfileClicked(String userId) {
  500.  
  501. }
  502.  
  503. @Override
  504. public void onClick(View v) {
  505. switch (v.getId()) {
  506. case R.id.button_back:
  507. onBackPressed();
  508. break;
  509. case R.id.btnSendComment:
  510. if(validateSendComment()){
  511. ChatManager.getInstance().sendMessage(userObjectId, editTextMessage.getText().toString());
  512. }
  513. break;
  514. }
  515. }
  516.  
  517. private boolean validateSendComment() {
  518. boolean result = false;
  519. boolean isTextWhitespace = editTextMessage.getText().toString().matches(Constants.WHITE_SPACES);
  520. if(userObjectId == null){
  521. Dialogs.showSingleButtonDialog(this, getString(R.string.pickUserError));
  522. } else if (isEmpty(editTextMessage.getText()) || isTextWhitespace) {
  523. Dialogs.showSingleButtonDialog(this, getString(R.string.emptyMessageError));
  524. } else {
  525. result = true;
  526. }
  527. return result;
  528. }
  529.  
  530. private class MyServiceConnection implements ServiceConnection {
  531. @Override
  532. public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  533. messageService = (MessageService.MessageServiceInterface) iBinder;
  534. messageService.addMessageClientListener(messageClientListener);
  535. }
  536.  
  537. @Override
  538. public void onServiceDisconnected(ComponentName componentName) {
  539. messageService = null;
  540. }
  541. }
  542.  
  543. private class MyMessageClientListener implements MessageClientListener {
  544. @Override
  545. public void onMessageFailed(MessageClient client, com.sinch.android.rtc.messaging.Message message,
  546. MessageFailureInfo failureInfo) {
  547. }
  548.  
  549. @Override
  550. public void onIncomingMessage(MessageClient client, com.sinch.android.rtc.messaging.Message message) {
  551. Logger.debug(getClass(), "onIncomingMessage");
  552. getAllUsers();
  553. }
  554.  
  555. @Override
  556. public void onMessageSent(MessageClient client, com.sinch.android.rtc.messaging.Message message, String recipientId) {
  557. Logger.debug(getClass(), "message to send: " + message.getTextBody());
  558. editTextMessage.setText("");
  559. for(UserProfile userProfile: allChatUsersList){
  560. if(userProfile.getId().equals(serverUserId)){
  561. getPointsOfCurrentUser(userProfile);
  562. }
  563. }
  564.  
  565. }
  566.  
  567. @Override
  568. public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {
  569. }
  570.  
  571. @Override
  572. public void onShouldSendPushData(MessageClient client, com.sinch.android.rtc.messaging.Message message, List<PushPair> pushPairs) {
  573. }
  574. }
  575.  
  576. @Override
  577. public void onDestroy() {
  578. if (messageService != null) {
  579. messageService.removeMessageClientListener(messageClientListener);
  580. }
  581. // if(serviceConnection!=null){
  582. if (currentUser != null) {
  583. unbindService(serviceConnection);
  584. }
  585. // }
  586. super.onDestroy();
  587. }
  588.  
  589. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement