/* * Author : ErVaLt / techwavedev.com * Description : TabLayout Andorid App */ package com.safemobile.dispatch; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.safemobile.adapters.ConversationGridViewAdapter; import com.safemobile.adapters.MessagesGridViewAdapter; import com.safemobile.lib.AppParams; import com.safemobile.lib.Msg; import com.safemobile.lib.OperationCodes; import com.safemobile.lib.SM; import com.safemobile.lib.SMS; import com.safemobile.lib.Vehicle; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Hashtable; import java.util.Locale; /** * fix import */ public class MessagesActivity extends Activity { /** Called when the activity is first created. */ private MessagesGridViewAdapter mAdapter; private ConversationGridViewAdapter convAdapter; private ArrayList listLastMessages = new ArrayList(); private ArrayList listSpecificConversation = new ArrayList(); private ArrayList dispatcher_positions = new ArrayList(); private GridView gridView; private Context context; private Activity activity; //private IconContextMenu iconContextMenu = null; private Hashtable> tableSMS = new Hashtable>(); private Hashtable seqIDSMSHash = new Hashtable(); // Need handler for callbacks to the UI thread private final Handler myHandler = new Handler(); /* Visual resources */ private LinearLayout layoutSend, layoutHeader, layoutHeaderConversation; private TextView textViewSelectedContact; private ImageView imageViewSelectedContact, imageBarcode; /* Buttons and EditBoxes */ private ImageButton imageButtonAdd, imageButtonBack; private Button imageButtonSend; private EditText editTextMsg; private TabLayoutActivity parentTab; /* Message args */ private int ACTION, MSGUpdate = 0; private ArrayList allVehicleNames = new ArrayList(); public ArrayList allVehicle = new ArrayList(); private Msg selectedVehicle; // tip of Messages and flag first load public boolean LASTMESSAGES = true; private boolean FIRST = true; // store selected sc_id and selected unit_type public long sc_id=0; public int unit_type=0; private String seqID; // store sms seqId to set to ACK in adapter public Bundle savedInstanceState; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.savedInstanceState = savedInstanceState; // get parentTab parentTab = (TabLayoutActivity)getParent(); context = this; activity = this; Locale locale = new Locale(AppParams.LANGUAGETMP); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); setContentView(R.layout.tabtext); // get LayoutSend and hide layoutSend = (LinearLayout) findViewById(R.id.layoutSendMsg); layoutSend.setVisibility(View.GONE); // get header layout layoutHeader = (LinearLayout) findViewById(R.id.layoutHeader); layoutHeaderConversation = (LinearLayout) findViewById(R.id.layoutHeaderConversation); // show only header layout layoutHeaderConversation.setVisibility(View.GONE); // get SelectedContact TextView and ImageView textViewSelectedContact = (TextView) findViewById(R.id.textViewSelectedContact); imageViewSelectedContact = (ImageView) findViewById(R.id.imageViewSelectedContact); imageBarcode = (ImageView) findViewById(R.id.imageBarcode); imageBarcode.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); // intent.putExtra("SCAN_MODE", "ONE_D_MODE"); startActivityForResult(intent, 0); } catch (Exception e) { showErrorDialog(getResources().getString(R.string.barcodeError)); //Log.d("Error",e.toString()); } } }); // change tab header fontface TextView textView1 = (TextView) findViewById(R.id.textView1); textView1.setTypeface(Typeface.createFromAsset(getAssets(), "Sketch_Block.ttf")); textView1.setTextSize(24); // prepared arraylist and passed it to the Adapter class //mAdapter = new GridviewAdapter(this,listFrom, listMessages, listReceived); mAdapter = new MessagesGridViewAdapter(this, listLastMessages, context); convAdapter = new ConversationGridViewAdapter(this, listSpecificConversation, context, sc_id, unit_type, dispatcher_positions, new ArrayList()); // Set custom adapter to gridview gridView = (GridView) findViewById(R.id.gridView1); gridView.setAdapter(mAdapter); // Implement On Item click listener gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) { //if (layoutHeader.getVisibility() == View.VISIBLE) if(LASTMESSAGES) { // get position Msg item = mAdapter.getItem(position); // get Specific Conversation sc_id = item.from.sc_id; SM.Debug("Selected sc_id: " + sc_id); // set Conversation type LASTMESSAGES = false; // call get SMS GetSMS4unit(sc_id); // create crt_Vehicle unit_type = (int)item.from.driver_id; // save selected vehicle selectedVehicle = item; } if(AppParams.DEMO) { // modify UI ACTION = MSGUpdate; updateResultsInUi(); } } }); // button create message imageButtonAdd = (ImageButton) findViewById(R.id.imageButtonAdd); imageButtonAdd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(); } }); // button send message imageButtonSend = (Button) findViewById(R.id.imageButtonSend); imageButtonSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //SM.Debug("SC ID:" + sc_id); SendSMS(sc_id, editTextMsg.getText().toString()); Toast.makeText(context, "Sending message...", 500).show(); /* // show busy indicator dialogHandler.handleMessage(new Message()); ACTION = SHOWLoading; myHandler.post(UpdateResults); */ // disable send button and editBox editTextMsg.setEnabled(false); imageButtonSend.setEnabled(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(500); myHandler.post(enableButtonRUN); //LASTMESSAGES = false; if(AppParams.DEMO) { Thread.sleep(5500); myHandler.post(demoReceveidSMSRUN); } } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }); // button back to conversations imageButtonBack = (ImageButton) findViewById(R.id.imageButtonBack); imageButtonBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // set LastMessage conversation type LASTMESSAGES = true; // refresh Grid GetLastSMS(); if(AppParams.DEMO) updateResultsInUi(); } }); // get Message editText editTextMsg = (EditText) findViewById(R.id.editTextMsg); gridView.setId(1); // id needed for IconContextMenu registerForContextMenu(gridView); parentTab.messageActivity = this; } // Create runnable for posting final Runnable demoReceveidSMSRUN = new Runnable() { public void run() { parentTab.setImei(sc_id + ""); parentTab.updateResultsInUi("realpha"); int timeGMT = (int) (System.currentTimeMillis() / 1000L); String SendSMSSeqID = "1."+timeGMT; // add mess to not ack list seqIDSMSHash.put(SendSMSSeqID, sc_id); // get sc_id conversation and add message ArrayList crtSMSlist = tableSMS.get(sc_id); SMS sms = new SMS(0, 0, timeGMT, "i got your sms", 0, sc_id); sms.seq_idx = SendSMSSeqID; crtSMSlist.add(sms); // add message to listLast boolean exists = false; for (Msg msg : listLastMessages) // if conversation exists in lastMessages if(msg.from.sc_id == sc_id) { exists = true; msg.message = "i got your sms"; msg.received = Calendar.getInstance().getTime(); } // if last messages doesn't contain this conversation if(!exists) { Vehicle sentVehicle = null; for(Vehicle veh : allVehicle) if(veh.sc_id == sc_id) sentVehicle = veh; listLastMessages.add(new Msg(sentVehicle, "i got your sms", Calendar.getInstance().getTime(), SendSMSSeqID)); } SM.Debug("time: " + timeGMT + " | " + Calendar.getInstance().getTime().toString() ); updateResultsInUi(); } }; @Override public void onBackPressed() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.exit)) .setCancelable(false) .setNeutralButton(getString(R.string.logout), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { parentTab.whenBackPressed(AppParams.ActivityResult.logout); } }) .setPositiveButton(getString(R.string.ext), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { parentTab.whenBackPressed(AppParams.ActivityResult.exit); } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } @Override public void onPause() { super.onPause(); SM.Debug("onPause"); } @Override public void onResume() { super.onResume(); if(parentTab.getTCPState() != null){ if(FIRST) { UpdateVehs(parentTab.getAllVehicle()); FIRST = false; if(LASTMESSAGES) parentTab.executeNetworkStuff(new String[] {OperationCodes.GetLastSMS + "", AppParams.USERID + ""}); } //GetLastSMS(); } SM.Debug("onResume"); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); editTextMsg.setText(editTextMsg.getText().toString() + contents); // Handle successful scan Toast.makeText(this, getResources().getString(R.string.barcodeContent) + ":"+contents+" with format:"+format, 6000).show(); } else if (resultCode == RESULT_CANCELED) { // Handle cancel //Toast.makeText(this, "TRY AGAIN", 6000).show(); } } } // Request SMS 4 Unit from AppServer private void GetSMS4UnitWithTime(long sc_id, long time) { if(!AppParams.DEMO) { parentTab.executeNetworkStuff(new String[] {OperationCodes.GetRecentSMSs + "", sc_id + "", time + ""}); SM.Debug(" #### GetSMS4uni:" + sc_id); } } private void GetSMS4unit(long sc_id) { if(!AppParams.DEMO) { SM.Debug("GetSMS4unit : " + sc_id); ArrayList listSMS = tableSMS.get(sc_id); long timeGMT = 0; if(!listSMS.isEmpty()) timeGMT = listSMS.get(listSMS.size()-1).timeGMT; // error in DB if(String.valueOf(timeGMT).contains(".")) { try { // remove the dot and the parse it to String timeGMT = Long.parseLong(String.valueOf(timeGMT).split(".")[1]); } catch (Exception e) { timeGMT = Long.parseLong(String.valueOf(timeGMT).replace(".","")); } } parentTab.executeNetworkStuff(new String[] {OperationCodes.GetRecentSMSs + "", sc_id + "", timeGMT + ""}); //parent.getRecentSMSs(sc_id, timeGMT); SM.Debug(" #### GetSMS4uni:" + sc_id); } } // Request Last SMS from AppServer public void GetLastSMS() { if(!AppParams.DEMO) { if(LASTMESSAGES) parentTab.executeNetworkStuff(new String[] {OperationCodes.GetLastSMS + "", AppParams.USERID + ""}); //parent.getLastSMSs(AppParams.USERID); else { ArrayList listSMS = tableSMS.get(sc_id); long timeGMT = 0; if(listSMS!= null && !listSMS.isEmpty()) timeGMT = listSMS.get(listSMS.size()-1).timeGMT; //parent.getRecentSMSs(sc_id, timeGMT); parentTab.executeNetworkStuff(new String[] {OperationCodes.GetRecentSMSs + "", sc_id + "", timeGMT + ""}); } } else updateResultsInUi(); } private void SendSMS(long sc_id, String txt) { if(!AppParams.DEMO) { int timeGMT = (int) (System.currentTimeMillis() / 1000L); String SendSMSSeqID = "1."+timeGMT; // add mess to not ack list seqIDSMSHash.put(SendSMSSeqID, sc_id); // get sc_id conversation and add message SMS sms = new SMS(0, 0, timeGMT, txt, sc_id, 0); sms.seq_idx = SendSMSSeqID; tableSMS.get(sc_id).add(sms); //parent.sendSMS(SendSMSSeqID,sc_id, txt); parentTab.executeNetworkStuff(new String[] {OperationCodes.SEND_TM + "", SendSMSSeqID, sc_id + "", txt}); updateResultsInUi(); } else { int timeGMT = (int) (System.currentTimeMillis() / 1000L); String SendSMSSeqID = "1."+timeGMT; // add mess to not ack list seqIDSMSHash.put(SendSMSSeqID, sc_id); // get sc_id conversation and add message ArrayList crtSMSlist = tableSMS.get(sc_id); SMS sms = new SMS(0, 0, timeGMT, txt, sc_id, 0); sms.seq_idx = SendSMSSeqID; crtSMSlist.add(sms); // add message to listLast boolean exists = false; for (Msg msg : listLastMessages) // if conversation exists in lastMessages if(msg.from.sc_id == sc_id) { exists = true; msg.message = txt; msg.received = Calendar.getInstance().getTime(); } // if last messages doesn't contain this conversation if(!exists) { Vehicle sentVehicle = null; for(Vehicle veh : allVehicle) if(veh.sc_id == sc_id) sentVehicle = veh; listLastMessages.add(new Msg(sentVehicle, txt, Calendar.getInstance().getTime(), SendSMSSeqID)); } SM.Debug("time: " + timeGMT + " | " + Calendar.getInstance().getTime().toString() ); LASTMESSAGES = false; updateResultsInUi(); } } // Update Vehicles received from AppServer public void UpdateVehs(ArrayList list) { SM.Debug("## UpdateVehs: " + list.size()); allVehicle = list; allVehicleNames = new ArrayList(); for(Vehicle v: allVehicle) allVehicleNames.add(v.name); if(tableSMS.size() == 0) { for(Vehicle veh: allVehicle) { ArrayList lista = new ArrayList(); // populate conversation list if demo if(AppParams.DEMO) lista = getDemoConversation(veh.sc_id); tableSMS.put(veh.sc_id, lista); } } } // gets DEMO conversations private ArrayList getDemoConversation(long sc_id) { ArrayList lista = new ArrayList(); if(sc_id == 101) lista.add(new SMS(1, 2, 1324016412, "Only one left", 101, 0)); else if (sc_id == 102) lista.add(new SMS(1, 2, 1328060100, "i'm at the train station", 0, 102)); else if (sc_id == 103) { lista.add(new SMS(1, 2, 1121016637, "Where are you now?", 103, 0)); lista.add(new SMS(2, 2, 1121016693, "Near Elementary School 81", 0, 103)); lista.add(new SMS(3, 2, 1121016693, "We have a client on Belmont Ave", 103, 0)); lista.add(new SMS(4, 2, 1121016724, "It's only 4 blocks away", 103, 0)); lista.add(new SMS(5, 2, 1121016693, "Can you take him?", 103, 0)); lista.add(new SMS(6, 2, 1121016818, "I'll be right there", 0, 103)); } else if (sc_id == 105) lista.add(new SMS(1, 2, 1328061660, "Thanks", 0, 105)); return lista; } public void UpdateSMS(ArrayList list) { SM.Debug("## UpdateSMS: " + list.size() + " [LASTMESSAGES:" + LASTMESSAGES + "]"); // populate listLastMessages if(LASTMESSAGES) { listLastMessages = new ArrayList(); for(SMS sms: list) { // get for sender long id_sender = sms.sc_id_dest; if (id_sender == 0) id_sender = sms.sc_id_sour; //SM.Debug(sms.toString()); // get vehicle with sender id Vehicle messageVeh= null; messageVeh = getVehicleById(id_sender); listLastMessages.add(0,new Msg(messageVeh, sms.mess, new Date((long)sms.timeGMT * 1000), sms.seq_idx)); } // update GridView //SM.Debug(" ########### " + parentTab.allVehicle.size() + " ||| " + listLastMessages.size()); mAdapter = new MessagesGridViewAdapter(activity, listLastMessages, context); //SM.Debug("list count : " + listLastMessages.size()); //gridView.setAdapter(mAdapter); //mAdapter.notifyDataSetChanged(); } else { // add new values to hashTable for key = sc_id ArrayList listScId = tableSMS.get(sc_id); if(list.size() != 0) for(SMS sms:list) { // compare last item in hashList with first elem in arrived list // protect is listSc_Id size = 0 if ((listScId.size()>0)&&(sms.sc_id_dest == listScId.get(listScId.size()-1).sc_id_dest && sms.sc_id_sour == listScId.get(listScId.size()-1).sc_id_sour && sms.mess == listScId.get(listScId.size()-1).mess)) // drop element ; else listScId.add(sms); } } // modify UI ACTION = MSGUpdate; myHandler.post(new Runnable() { @Override public void run() { updateResultsInUi(); } }); } // Confirmation for sending message public void ConfirmSMS(String data, final String seqID) { SM.Debug("ConfirmSMS"); if(data.equals("0")) { SM.Debug("Error on sending SMS"); showErrorDialog("Error on sending message."); } else { SM.Debug("ACK received for text message"); //get sc_id for crt message long sc_id = seqIDSMSHash.get(seqID); // get SMS list for crt sc_id ArrayList crtSMSList = tableSMS.get(sc_id); for(SMS sms: crtSMSList) { if(sms.seq_idx.equals(seqID)) { SM.Debug("######### AM SCHIMBAT STATUSUL pt: " + sms.mess + " | " + sc_id + " | " + seqID + " || " + sms.seq_idx); // set ACK sms.status = 2; } } // remove message from seqIDSMS Hash = don't wait confirmation for it seqIDSMSHash.remove(seqID); // refresh MSG List //GetSMS4unit(sc_id); /* // TODO -> this is a small bug fix, should talk with Bigu to change it // remove message from list because it will be brought back by GetSMS4Unit, and it will have different time ArrayList listWithTextMessage = tableSMS.get(sc_id); if(listWithTextMessage.size() > 0) listWithTextMessage.remove(listWithTextMessage.size() - 1); // remove last message */ // store sms seqId to set to ACK in adapter this.seqID = seqID; myHandler.post(new Runnable() { @Override public void run() { convAdapter.setACK(seqID); convAdapter.changeView(seqID); convAdapter.notifyDataSetChanged(); } }); myHandler.post(new Runnable() { @Override public void run() { // clear text editTextMsg.setText(""); } }); } } public void NewSMS(String imei, String message, final long time) { SM.Debug(" ## NewSMS: " + imei + " | " + message); if(!LASTMESSAGES) { // if received message from current conversation if(getVehicleByImei(imei).sc_id == sc_id) GetSMS4UnitWithTime(sc_id, time); // refresh MSG List //else // parentTab.myHandler.post(parentTab.showPopUpRUN); // show PopUp } else GetLastSMS(); // get last SMS } // Create runnable for posting final Runnable enableButtonRUN = new Runnable() { public void run() { updateEnableButtonsUI(); } }; // enable buttons in UI after 200ms from send private void updateEnableButtonsUI() { // enable buttons imageButtonSend.setEnabled(true); editTextMsg.setEnabled(true); editTextMsg.setText(""); } private void updateResultsInUi() { if(allVehicle == null) UpdateVehs(parentTab.getAllVehicle()); //SM.Debug("updateResultsInUi: " + ACTION); if(ACTION == MSGUpdate) { if(LASTMESSAGES) { // show Header Layout layoutHeader.setVisibility(View.VISIBLE); // hide Conversation Header Layout layoutHeaderConversation.setVisibility(View.GONE); // hide Send Layout layoutSend.setVisibility(View.GONE); // change GridView adapter gridView.setAdapter(mAdapter); gridView.invalidate(); } else { SM.Debug(" #### Modify adapter for SMS4unit"); // populate specific conversation listSpecificConversation = new ArrayList(); dispatcher_positions = new ArrayList(); ArrayList ackPosition = new ArrayList(); ArrayList list; list = tableSMS.get(sc_id); for(SMS sms: list) { // get for sender long id_sender = sms.sc_id_dest; if (id_sender == 0) id_sender = sms.sc_id_sour; // get vehicle with sender id Vehicle messageVeh= null; messageVeh = getVehicleById(id_sender); // flag dispatcher message when source is 0 dispatcher_positions.add(sms.sc_id_sour==0 ? true : false); if(sms.status == 2) ackPosition.add(true); else ackPosition.add(false); listSpecificConversation.add(new Msg(messageVeh, sms.mess, new Date((long)sms.timeGMT * 1000), sms.seq_idx)); } convAdapter = new ConversationGridViewAdapter(activity, listSpecificConversation, context, sc_id, unit_type, dispatcher_positions, ackPosition); gridView.setAdapter(convAdapter); if(listSpecificConversation.size() > 0) gridView.setSelection(listSpecificConversation.size()-1); // set unit name and image in Header Conversation textViewSelectedContact.setText(getVehicleBySc_Id(sc_id).name); imageViewSelectedContact.setImageResource(getVehicleBySc_Id(sc_id).getLargeIcon()); // clear editText editTextMsg.setText(""); // change layouts visibility layoutSend.setVisibility(View.VISIBLE); layoutHeader.setVisibility(View.GONE); layoutHeaderConversation.setVisibility(View.VISIBLE); } gridView.invalidate(); // hide dialog try { //dialogLoading.cancel(); } catch(Exception ex) { ; } } } // show new message after layoutNewMessage Click public void showSMS4unit(int sc_id) { // show dialog //dialogLoading = ProgressDialog.show(activity, "", "Loading messages. Please wait...", true); ACTION = MSGUpdate; LASTMESSAGES = false; GetSMS4unit(sc_id); } // gets Vehicle from id public Vehicle getVehicleById(long id_vehicle) { for(Vehicle vehicle: allVehicle) if(vehicle.sc_id == id_vehicle) return vehicle; return null; } // get Vehicle from imei public Vehicle getVehicleByImei(String imei) { for(Vehicle vehicle: allVehicle) if(vehicle.imei.equalsIgnoreCase(imei)) return vehicle; return null; } public Vehicle getVehicleBySc_Id(long sc_id) { for(Vehicle vehicle: allVehicle) if(vehicle.sc_id == sc_id) return vehicle; return null; } // show a dialog public void showDialog() { ArrayAdapter adapter = new ArrayAdapter(this, R.layout.template_simple_list_item, allVehicleNames); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(getString(R.string.selectVehicle)); builder.setAdapter(adapter , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // get position Vehicle item = allVehicle.get(which); // get Specific Conversation sc_id = item.sc_id; SM.Debug("Selected sc_id: " + sc_id); // set Conversation type LASTMESSAGES = false; // call get SMS GetSMS4unit(sc_id); // create crt_Vehicle unit_type = (int) item.driver_id; SM.Debug("AM SELECTAT: " + sc_id + " | " + item.name + " | " + unit_type + "\n\t " + item.toString()); selectedVehicle = new Msg(item, "", Calendar.getInstance().getTime(), ""); if(AppParams.DEMO) updateResultsInUi(); } }); AlertDialog alert = builder.create(); alert.show(); } public void showErrorDialog(String errorMsg) { Dialog dialog = new Dialog(context); dialog.setTitle(getString(R.string.sendingError)); dialog.setContentView(R.layout.dialog); dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); TextView text = (TextView) dialog.findViewById(R.id.text); ImageView image = (ImageView) dialog.findViewById(R.id.image); image.setImageResource(R.drawable.error); text.setText(errorMsg); dialog.show(); } }