Guest User

ChatFragment

a guest
Feb 5th, 2015
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.24 KB | None | 0 0
  1. File ChatFragment.java
  2.  
  3. public class ChatFragment extends Fragment {
  4.  
  5.     // TODO: Rename parameter arguments, choose names that match
  6.     // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
  7.     private static final String ARG_PARAM1 = "param1";
  8.     private static final String ARG_PARAM2 = "param2";
  9.  
  10.     // TODO: Rename and change types of parameters
  11.     private String mParam1;
  12.     private String mParam2;
  13.  
  14.     private OnFragmentInteractionListener mListener;
  15.  
  16.     static ArrayList<Message> chatMsgList = new ArrayList<>();
  17.     ChatAdapter chatAdapter;
  18.     ListView lstViewChat;
  19.     private String temp;
  20.     private String groupId;
  21.     static String username;
  22.  
  23.     EditText editMsg;
  24.  
  25.  
  26.     /**
  27.      * Use this factory method to create a new instance of
  28.      * this fragment using the provided parameters.
  29.      *
  30.      * @param param1 Parameter 1.
  31.      * @param param2 Parameter 2.
  32.      * @return A new instance of fragment ChatFragment.
  33.      */
  34.     // TODO: Rename and change types and number of parameters
  35.     public static ChatFragment newInstance(String param1, String param2) {
  36.         ChatFragment fragment = new ChatFragment();
  37.         Bundle args = new Bundle();
  38.         args.putString(ARG_PARAM1, param1);
  39.         args.putString(ARG_PARAM2, param2);
  40.         fragment.setArguments(args);
  41.         return fragment;
  42.     }
  43.  
  44.     public ChatFragment() {
  45.         // Required empty public constructor
  46.     }
  47.  
  48.     @Override
  49.     public void onCreate(Bundle savedInstanceState) {
  50.         super.onCreate(savedInstanceState);
  51.         if (getArguments() != null) {
  52.             mParam1 = getArguments().getString(ARG_PARAM1);
  53.             mParam2 = getArguments().getString(ARG_PARAM2);
  54.         }
  55.     }
  56.  
  57.     @Override
  58.     public View onCreateView(LayoutInflater inflater, ViewGroup container,
  59.                              Bundle savedInstanceState) {
  60.         // Inflate the layout for this fragment
  61.         View view = inflater.inflate(R.layout.fragment_chat, container, false);
  62.  
  63.         editMsg = (EditText)  view.findViewById(R.id.txt_message_input);
  64.         Button  btnSend = (Button) view.findViewById(R.id.btnSend);
  65.         btnSend.setOnClickListener(new View.OnClickListener() {
  66.             @Override
  67.             public void onClick(View v) {
  68.                 String txtMsg = editMsg.getText().toString();
  69.                 if (!txtMsg.isEmpty()) {
  70.                     System.out.println("GOTO CreateNewMessage!");
  71.                     CreateNewMessage(txtMsg);
  72.                     editMsg.setText("");
  73.                 }
  74.             }
  75.         });
  76.  
  77.         ReadChatMessages();
  78.  
  79.         return view;
  80.     }
  81.  
  82.  
  83.  
  84.     public void  CreateNewMessage(String textMsg) {
  85.         Firebase firebaserootRef = new Firebase("https://luminous-heat-420.firebaseio.com");
  86.  
  87.         Map<String, Message> chatMessages = new HashMap<>();
  88.  
  89.         String msg = textMsg;
  90.         String from = username;
  91.         String time = TimeStamp();
  92.         String id = "";
  93.  
  94.         //Message
  95.         if (groupId != "") {
  96.             Firebase firebaseParentMsg = firebaserootRef.child(GetGroupId()).child("messages");
  97.             Firebase firebaseMsg = firebaseParentMsg.push();
  98.  
  99.             Message cm = new Message(id, from, msg, time);
  100.  
  101.             id = firebaseMsg.getKey();
  102.             firebaseMsg.child("from").setValue(cm.GetFrom());
  103.             firebaseMsg.child("message").setValue(cm.GetMsg());
  104.             firebaseMsg.child("time").setValue(cm.GetTime());
  105.  
  106.             chatMessages.put(id,cm);
  107.             System.out.println("Succesfully created a new message.");
  108.  
  109.             ReadChatMessages();
  110.         }
  111.     }
  112.  
  113.     public void ReadChatMessages() {
  114.         Firebase firebaserootRef = new Firebase("https://luminous-heat-420.firebaseio.com");
  115.         firebaserootRef.addChildEventListener(new ChildEventListener() {
  116.             @Override
  117.             public void onChildAdded(DataSnapshot snapshot, String s) {
  118.                 if (!(snapshot.child(GetGroupId()).child("messages").exists())) {
  119.                     for (DataSnapshot c : snapshot.child("messages").getChildren()) {
  120.                         if (snapshot.getKey().equals(GetGroupId())) {
  121.  
  122.                             Message newMessage = new Message();
  123.                             newMessage.SetFrom((String) c.child("from").getValue());
  124.                             newMessage.SetMsg((String) c.child("message").getValue());
  125.                             newMessage.SetTime((String) c.child("time").getValue());
  126.                             newMessage.SetId((String) c.getKey());
  127.  
  128.                             //Check if GetGroupId value has been changed.
  129.                             if (temp == GetGroupId()) {
  130.                                 AddToLstViewChat(newMessage);
  131.                             } else {
  132.                                 chatMsgList.clear();
  133.                                 temp = GetGroupId();
  134.                                 AddToLstViewChat(newMessage);
  135.                             }
  136.  
  137.                             //Automatic scrolls to last line in listView.
  138.                             lstViewChat.setSelection(chatAdapter.getCount() -1);
  139.                         }
  140.                     }
  141.                 }
  142.             }
  143.  
  144.             @Override
  145.             public void onChildChanged(DataSnapshot snapshot, String s) {
  146.             }
  147.  
  148.             @Override
  149.             public void onChildRemoved(DataSnapshot snapshot) {
  150.             }
  151.  
  152.             @Override
  153.             public void onChildMoved(DataSnapshot snapshot, String s) {
  154.             }
  155.  
  156.             @Override
  157.             public void onCancelled(FirebaseError firebaseError) {
  158.             }
  159.         });
  160.     }
  161.  
  162.     //Check if ArrayList contains the message.
  163.     public boolean ComapareId(Message msg, ArrayList<Message> lst) {
  164.         for (Message m : lst) {
  165.             if (msg.GetId() == m.GetId()) {
  166.                 return true;
  167.             }
  168.         }
  169.         return false;
  170.     }
  171.  
  172.     //Check who has sent the received message.
  173.     public boolean IsMsgFromMe(Message message) {
  174.         boolean isSenderMe = username.equals((CharSequence) message.GetFrom());
  175.         return isSenderMe;
  176.     }
  177.  
  178.     public void AddToLstViewChat(Message newMessage) {
  179.         if (newMessage != null) {
  180.             if (!ComapareId(newMessage, chatMsgList)) {
  181.                   chatMsgList.add(newMessage);
  182.             }
  183.  
  184.             if (chatAdapter == null) {
  185.                 chatAdapter = new ChatAdapter(getActivity(), chatMsgList);
  186.             }
  187.  
  188.             try {
  189.                   lstViewChat = (ListView) getView().findViewById(R.id.listView_chat);
  190.             } catch (NullPointerException e) {
  191.                 System.out.println("lstView_chat_message_me/others is null in method AddtoLstViewChat in ChatFragment class." + e.getMessage());
  192.             }
  193.  
  194.             lstViewChat.setAdapter(chatAdapter);
  195.             chatAdapter.notifyDataSetChanged();
  196.         }
  197.     }
  198.  
  199.     // TODO: Rename method, update argument and hook method into UI event
  200.     public void onButtonPressed(Uri uri) {
  201.         if (mListener != null) {
  202.             mListener.onFragmentInteraction(uri);
  203.         }
  204.     }
  205.  
  206.     @Override
  207.     public void onAttach(Activity activity) {
  208.         super.onAttach(activity);
  209.         try {
  210.             mListener = (OnFragmentInteractionListener) activity;
  211.         } catch (ClassCastException e) {
  212.             throw new ClassCastException(activity.toString()
  213.                     + " must implement OnFragmentInteractionListener");
  214.         }
  215.     }
  216.  
  217.     @Override
  218.     public void onDetach() {
  219.         super.onDetach();
  220.         mListener = null;
  221.     }
  222.  
  223.     public String GetGroupId() {
  224.         return groupId;
  225.     }
  226.  
  227.     //Receives the group id from ChatFragment (ChangeToChatFragment(String groupId)).
  228.     public void SetGroupID(String groupId) {
  229.         this.groupId = groupId;
  230.     }
  231.  
  232.     public void GetUsername(String username) {
  233.         this.username = username;
  234.     }
  235.  
  236.  
  237.     public interface OnFragmentInteractionListener {
  238.         // TODO: Update argument type and name
  239.         public void onFragmentInteraction(Uri uri);
  240.     }
  241.  
  242.     public String TimeStamp() {
  243.         String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
  244.         return timeStamp;
  245.     }
  246. }
Advertisement
Add Comment
Please, Sign In to add comment