· 7 years ago · Jun 05, 2018, 07:46 AM
1package index.finance.faith;
2
3import java.io.ByteArrayOutputStream;
4import java.io.File;
5import java.io.FileInputStream;
6import java.io.FileNotFoundException;
7import java.io.FileOutputStream;
8import java.io.IOException;
9import java.io.UnsupportedEncodingException;
10import java.lang.reflect.InvocationTargetException;
11import java.lang.reflect.Method;
12import java.net.ServerSocket;
13import java.security.InvalidKeyException;
14import java.security.NoSuchAlgorithmException;
15import java.security.spec.InvalidKeySpecException;
16import java.text.DecimalFormat;
17import java.text.NumberFormat;
18import java.text.ParseException;
19import java.text.SimpleDateFormat;
20import java.util.ArrayList;
21import java.util.Calendar;
22import java.util.Date;
23import java.util.List;
24import java.util.Locale;
25
26import javax.crypto.BadPaddingException;
27import javax.crypto.Cipher;
28import javax.crypto.IllegalBlockSizeException;
29import javax.crypto.NoSuchPaddingException;
30import javax.crypto.SecretKey;
31import javax.crypto.SecretKeyFactory;
32import javax.crypto.spec.DESKeySpec;
33
34import org.apache.http.NameValuePair;
35import org.jpos.iso.ISOUtil;
36import org.ksoap2.SoapEnvelope;
37import org.ksoap2.SoapFault;
38import org.ksoap2.serialization.SoapObject;
39import org.ksoap2.serialization.SoapSerializationEnvelope;
40import org.ksoap2.transport.HttpTransportSE;
41
42//import com.google.android.gms.ads.formats.NativeAd;
43
44import com.cashlez.android.sdk.CLErrorResponse;
45import com.cashlez.android.sdk.CLPayment;
46import com.cashlez.android.sdk.bean.TransactionType;
47import com.cashlez.android.sdk.companion.printer.CLPrinterCompanion;
48import com.cashlez.android.sdk.companion.reader.CLReaderCompanion;
49import com.cashlez.android.sdk.model.CLPrintObject;
50import com.cashlez.android.sdk.payment.CLPaymentResponse;
51import com.cashlez.android.sdk.payment.CLTCashQRResponse;
52import com.cashlez.android.sdk.payment.CLTMoneyResponse;
53import com.cashlez.android.sdk.payment.noncash.CLPaymentHandler;
54import com.cashlez.android.sdk.payment.noncash.ICLPaymentHandler;
55import com.cashlez.android.sdk.payment.noncash.ICLPaymentService;
56import com.cashlez.android.sdk.printing.ICLPrinterService;
57import com.cashlez.android.sdk.service.CLPrintAlignEnum;
58import com.cashlez.android.sdk.service.CLPrintEnum;
59import com.google.android.gms.common.ConnectionResult;
60import com.google.android.gms.common.GooglePlayServicesUtil;
61import com.google.android.gms.common.api.GoogleApiClient;
62import com.google.android.gms.location.LocationRequest;
63import com.google.android.gms.location.LocationServices;
64import com.google.android.gms.maps.CameraUpdate;
65import com.google.android.gms.maps.CameraUpdateFactory;
66import com.google.android.gms.maps.GoogleMap;
67import com.google.android.gms.maps.MapFragment;
68import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
69import com.google.android.gms.maps.OnMapReadyCallback;
70import com.google.android.gms.maps.model.BitmapDescriptorFactory;
71import com.google.android.gms.maps.model.CameraPosition;
72import com.google.android.gms.maps.model.LatLng;
73import com.google.android.gms.maps.model.Marker;
74import com.google.android.gms.maps.model.MarkerOptions;
75import com.google.android.gms.maps.model.Polyline;
76import com.google.android.gms.maps.model.PolylineOptions;
77//import com.google.android.gms.vision.barcode.Barcode;
78//import com.google.android.gms.vision.text.Line;
79
80import android.*;
81import android.Manifest;
82import android.app.Activity;
83import android.app.AlertDialog;
84import android.app.DatePickerDialog;
85import android.app.Dialog;
86import android.app.ProgressDialog;
87import android.bluetooth.BluetoothAdapter;
88import android.content.BroadcastReceiver;
89import android.content.ContentValues;
90import android.content.Context;
91import android.content.DialogInterface;
92import android.content.Intent;
93import android.content.SharedPreferences;
94import android.content.pm.PackageManager;
95import android.database.Cursor;
96import android.database.sqlite.SQLiteDatabase;
97import android.graphics.Bitmap;
98import android.graphics.BitmapFactory;
99import android.graphics.Canvas;
100import android.graphics.Color;
101import android.graphics.Matrix;
102import android.graphics.Paint;
103import android.graphics.Typeface;
104import android.location.Address;
105import android.location.Criteria;
106import android.location.Geocoder;
107import android.location.Location;
108import android.location.LocationListener;
109import android.location.LocationManager;
110import android.net.Uri;
111import android.net.wifi.WifiManager;
112import android.os.AsyncTask;
113import android.os.Build;
114import android.os.Bundle;
115import android.os.Environment;
116import android.os.Handler;
117import android.os.PowerManager;
118import android.os.PowerManager.WakeLock;
119import android.os.SystemClock;
120import android.preference.PreferenceManager;
121import android.provider.MediaStore;
122import android.provider.Settings;
123import android.support.annotation.NonNull;
124import android.support.annotation.Nullable;
125import android.support.design.widget.CoordinatorLayout;
126import android.support.design.widget.FloatingActionButton;
127import android.support.design.widget.Snackbar;
128import android.support.v4.app.ActivityCompat;
129import android.support.v4.app.NavUtils;
130import android.support.v4.content.ContextCompat;
131import android.text.InputType;
132import android.util.Base64;
133import android.util.Log;
134import android.util.TypedValue;
135import android.view.View;
136import android.view.View.OnClickListener;
137import android.view.ViewGroup;
138import android.widget.Button;
139import android.widget.DatePicker;
140import android.widget.EditText;
141import android.widget.ImageButton;
142import android.widget.ImageView;
143import android.widget.LinearLayout;
144import android.widget.RadioButton;
145import android.widget.RadioGroup;
146import android.widget.RelativeLayout;
147import android.widget.ScrollView;
148import android.widget.TabHost;
149import android.widget.Toast;
150import android.widget.LinearLayout.LayoutParams;
151import android.widget.TabHost.TabSpec;
152import android.widget.TableLayout;
153import android.widget.TableRow;
154import android.widget.TextView;
155
156import cn.pedant.SweetAlert.SweetAlertDialog;
157import index.finance.faith.Interface.GPSTracker;
158import index.finance.faith.Interface.Utility;
159import index.finance.faith.Model.Model_Customer;
160import index.finance.faith.Module.DirectionFinder;
161import index.finance.faith.Module.DirectionFinderListener;
162import index.finance.faith.Module.Route;
163
164
165public class CollectionActivity extends DashBoardActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
166 GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback,DirectionFinderListener {
167 private String contractNo;
168 private String custName;
169 private String custNamePrint;
170 private String custAddress;
171 private String dueDate;
172 private String taskDate;
173 private String insNo;
174 private String insAmount;
175 private String inOverdue;
176 private String OS;
177
178 private String latiaja;
179 private String longiaja;
180 private String collInitial = "";
181 private String receiptNo = "";
182 private String licensePlate = "";
183
184 private String branchName = "";
185 private String branchAddress = "";
186 private String branchPhone = "";
187
188
189 private Context mContext;
190
191 private TabHost tabHost = null;
192 private LazyAdapterImage adapter;
193 private Exception e = null;
194
195 private ArrayList<String> label = new ArrayList<String>();
196 private ArrayList<String> info = new ArrayList<String>();
197
198 private DataSource datasource;
199 private SQLiteDatabase db;
200 private Form theForm;
201 private String addressText = "";
202
203 private Button btnCheckIn;
204 private Button btnMyLocation;
205
206
207 private LocationManager locationManager;
208 boolean gps_enabled = false;
209 boolean network_enabled = false;
210
211 private String latLongString = "";
212 private String latString = "";
213 private String lngString = "";
214
215 private SharedPreferences generalPrefs;
216 private boolean flag = false;
217 private Dialog dialog;
218 private SharedPreferences.Editor prefsEditor;
219 private boolean isMapImageValid = false;
220 private RadioGroup radiogroup;
221
222 private ImageView gambarfoto;
223 private ImageView hasilfoto;
224 private GoogleMap googleMap;
225 private GoogleMap Nmap;
226 private MapFragment mapFragment;
227 private String moduleid;
228 ServerSocket serverSocket;
229 private WakeLock wl;
230 private static final int CAMERA_REQUEST = 1888;
231 private static final int SELECT_PICTURE = 0;
232 Uri selectedImageUri;
233 private String selectedImagePath;
234 static final LatLng Menteng = new LatLng(-6.19772, 106.8233113);
235 Location currentLocation = new Location("current");
236 Marker cloc;
237 Marker dloc;
238 LocationRequest locationRequest;
239 private GoogleApiClient googleApiClient;
240 private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
241 private String userchoosen;
242 GPSTracker gps;
243 Double clongitude;
244 Double clatitude;
245 String TAG = "CollectionActivity";
246 private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
247 private String alamat_customer = "", kota = "", state = "", negara = "";
248 private String posisi_collector ="";
249 private List<Marker> originMarkers = new ArrayList<>();
250 private List<Marker> destinationMarkers = new ArrayList<>();
251 private List<Polyline> polylinePaths = new ArrayList<>();
252 private ProgressDialog progressDialog;
253 private String originText = "";
254 LinearLayout linearLayout;
255 private String tableImageCollection;
256 Double Lat_Customer;
257 Double Lon_customer;
258 private FloatingActionButton btnGetDirection;
259 private RelativeLayout relative;
260 String baru;
261 String strTotal = "0";
262 double total = 0.0;
263 String fieldValue = "";
264 private DataLocal datalocal;
265 private String userID;
266 private String paidBy;
267 private String tableName;
268 private Button submit;
269 private String lasttransaction="";
270 private String tanggalbayar="";
271 private String tanggalbayar2="";
272 private Uri imageUri;
273 private boolean deleteFlag5 = false;
274 private int buttonId5;
275 ImageButton imageButton;
276 private static int Action_Code = 0;
277 private int flag2;
278 private Intent datax;
279 private String image_str = "", latinya2 = "", longinya2 = "";
280 private String image_str_coll = "";
281 private boolean isgambarValid = false;
282 private String status = "";
283 private Dialog dialog2;
284 private SimpleDateFormat dateFormatter;
285 private EditText searchText;
286 private DatePickerDialog fromDatePickerDialog,datePickerDialog;
287 private String result_submit="";
288 String jumlahbaru ="";
289 String temp_jumlah = "";
290 private int satu = 1;
291 int i = 1;
292 int ii = 2;
293 private String userChoosenTask;
294 String strTotal2 = "0";
295 private BluetoothAdapter bluetoothAdapter;
296 DataService service = new DataService();
297 BroadcastReceiver mReceiver;
298
299 ICLPaymentService paymentService;
300 ICLPaymentHandler paymentHandler;
301 ICLPrinterService printerService;
302 CLPayment clPayment;
303 String strtotal2;
304 Activity activity;
305 Bundle extra;
306
307 public void onCreate(Bundle savedInstanceState) {
308 super.onCreate(savedInstanceState);
309 mContext = CollectionActivity.this;
310 datalocal = new DataLocal();
311 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
312 wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
313 wl.acquire();
314
315 bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
316
317 generalPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
318 prefsEditor = generalPrefs.edit();
319 dialog = new Dialog(mContext, R.style.lightbox_dialog);
320 dialog.setContentView(R.layout.lightbox_dialog);
321 ((TextView) dialog.findViewById(R.id.dialogText)).setText("Loading...");
322 dialog.setCancelable(false);
323 paymentHandler = new CLPaymentHandler(this, extra);
324 paymentService = new ICLPaymentService() {
325 @Override
326 public void onReaderSuccess(CLReaderCompanion clReaderCompanion) {
327 clReaderCompanion.getSerialNumber();
328 clReaderCompanion.getBtAddress();
329
330 }
331
332 @Override
333 public void onReaderError(CLErrorResponse clErrorResponse) {
334
335 }
336
337 @Override
338 public void onPrinterSuccess(CLPrinterCompanion clPrinterCompanion) {
339
340 }
341
342 @Override
343 public void onPrinterError(CLErrorResponse clErrorResponse) {
344
345 }
346
347 @Override
348 public void onInsertCreditCard(CLPaymentResponse clPaymentResponse) {
349
350 }
351
352 @Override
353 public void onInsertOrSwipeDebitCard(CLPaymentResponse clPaymentResponse) {
354
355 }
356
357 @Override
358 public void onCashPaymentSuccess(CLPaymentResponse clPaymentResponse) {
359 String nama = clPaymentResponse.getUserName();
360 String amout = clPaymentResponse.getAmount();
361 Log.d(TAG, "onCashPaymentSuccess: nama " + nama);
362 Log.d(TAG, "onCashPaymentSuccess: amount " + amout);
363 }
364
365 @Override
366 public void onCashPaymentError(CLErrorResponse clErrorResponse) {
367 String error = clErrorResponse.getErrorMessage();
368 Log.d(TAG, "onCashPaymentError: "+ error);
369
370 }
371
372 @Override
373 public void onPaymentSuccess(CLPaymentResponse clPaymentResponse) {
374
375 }
376
377 @Override
378 public void onRemoveCard(String s) {
379
380 }
381
382 @Override
383 public void onProvideSignatureRequest(CLPaymentResponse clPaymentResponse) {
384
385 }
386
387 @Override
388 public void onPaymentError(CLErrorResponse clErrorResponse, String s) {
389
390 }
391
392 @Override
393 public void onProvideSignatureError(CLErrorResponse clErrorResponse) {
394
395 }
396
397 @Override
398 public void onTCashQRSuccess(CLTCashQRResponse cltCashQRResponse) {
399
400 }
401
402 @Override
403 public void onTCashQRError(CLErrorResponse clErrorResponse) {
404
405 }
406
407 @Override
408 public void onCheckTCashQRStatusSuccess(CLTCashQRResponse cltCashQRResponse) {
409
410 }
411
412 @Override
413 public void onCheckTCashQRStatusError(CLErrorResponse clErrorResponse) {
414
415 }
416
417 @Override
418 public void onTMoneySuccess(CLTMoneyResponse cltMoneyResponse) {
419
420 }
421
422 @Override
423 public void onTMoneyError(CLErrorResponse clErrorResponse) {
424
425 }
426
427 @Override
428 public void onCheckTMoneyStatusSuccess(CLTMoneyResponse cltMoneyResponse) {
429
430 }
431
432 @Override
433 public void onCheckTMoneyStatusError(CLErrorResponse clErrorResponse) {
434
435 }
436
437 @Override
438 public void onCancelTMoneySuccess(CLTMoneyResponse cltMoneyResponse) {
439
440 }
441
442 @Override
443 public void onCancelTMoneyError(CLErrorResponse clErrorResponse) {
444
445 }
446 };
447 printerService = new ICLPrinterService() {
448 @Override
449 public void onPrintingSuccess(CLPrinterCompanion clPrinterCompanion) {
450 String nama = clPrinterCompanion.getMessage();
451 Log.d(TAG, "onCashPaymentSuccess: nama " + nama);
452
453 }
454
455 @Override
456 public void onPrintingError(CLErrorResponse clErrorResponse) {
457 String nama = clErrorResponse.getErrorMessage();
458 int amout = clErrorResponse.getErrorCode();
459 Log.d(TAG, "onCashPaymentSuccess: nama " + nama);
460 Log.d(TAG, "onCashPaymentSuccess: amount " + amout);
461 }
462 };
463
464
465 try {
466 String sessionStart;
467 String now;
468 String timeOut;
469 long diffInMin = 0;
470
471 Calendar c = Calendar.getInstance();
472 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
473 now = df.format(c.getTime());
474
475 timeOut = generalPrefs.getString("timeOut", null);
476 sessionStart = generalPrefs.getString("sessionStart", null);
477
478 Date dateStart = df.parse(sessionStart);
479 Date dateEnd = df.parse(now);
480
481 diffInMin = (dateEnd.getTime() / 60000) - (dateStart.getTime() / 60000);
482
483 if ((int) diffInMin > Integer.valueOf(timeOut)
484 || (int) diffInMin < 0) {
485 prefsEditor.putBoolean("finish", true).commit();
486
487 finish();
488 Intent myintent = new Intent(mContext, HomeActivity.class);
489 myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
490 startActivity(myintent);
491 return;
492 }
493
494 } catch (ParseException e) {
495 e.printStackTrace();
496 }
497
498 flag = true;
499 moduleid = generalPrefs.getString("moduleid", null);
500 branchName = generalPrefs.getString("branchName", null);
501 branchAddress = generalPrefs.getString("branchAddress", null);
502 branchPhone = generalPrefs.getString("branchPhone", null);
503 userID = generalPrefs.getString("userID", null);
504
505 Log.d(TAG, "onCreate: "+ mReceiver);
506
507 datasource = new DataSource(mContext);
508 db = datasource.getWritableDatabase();
509 tableName = "printcash";
510
511
512 tableImageCollection = "imagecollection";
513 imageButton = (ImageButton) findViewById(R.id.button5);
514
515 Bundle b = getIntent().getExtras();
516 contractNo = b.getString("contractNo");
517 custName = b.getString("custName");
518 custNamePrint = b.getString("custName");
519 custAddress = b.getString("custAddress");
520 dueDate = b.getString("dueDate");
521 taskDate = b.getString("taskDate");
522 insNo = b.getString("insNo");
523 insAmount = b.getString("insAmount");
524 latiaja = b.getString("latitudenya");
525 longiaja = b.getString("longitudenya");
526 inOverdue = b.getString("OD");
527
528
529
530 //ceklatlongcustomer();
531
532 Log.d(TAG, "onCreate: amount " + insAmount);
533 Log.d(TAG, "onCreate: duedate " + dueDate);
534 Log.d(TAG, "onCreate: no contract: "+contractNo);
535 Log.d(TAG, "onCreate: userIDnya berapa : " + userID);
536 Log.d(TAG, "onCreate: latitudenya berapa : " + latiaja);
537 Log.d(TAG, "onCreate: longitudenya berapa : " + longiaja);
538
539
540 dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
541
542 if (custNamePrint.length() > 18) {
543 custNamePrint = custNamePrint.substring(0, 18);
544 }
545
546 try{
547 if(latiaja.equals("") || longiaja.equals("")){
548 Toast.makeText(mContext,"Koordinat Customer Tidak Ada",Toast.LENGTH_SHORT).show();
549 } else{
550 model_customer.setLat(latiaja);
551 model_customer.setLon(longiaja);
552 Log.d(TAG, "onCreate: adalah model_customer "
553 +"latiaja : "+latiaja+"\n"
554 +"longiaja : " + longiaja);
555
556 Lat_Customer = Double.parseDouble(latiaja);
557 Lon_customer = Double.parseDouble(longiaja);
558
559 /*model_customer.setLat(Lat_Customer);
560 model_customer.setLon(Lon_customer);*/
561
562 Log.d(TAG, "onCreate: adalah "
563 +"Lat_Customer : "+Lat_Customer+"\n"
564 +"Lon_Customer : " + Lon_customer);
565
566 //Toast.makeText(mContext,"Koordinat posisi Customer Ada",Toast.LENGTH_LONG).show();
567 }
568
569
570
571 }catch (Exception e){
572 e.printStackTrace();
573
574 }
575
576 setContentView(R.layout.tabs);
577 setHeader(getString(R.string.CollectionActivityTitle), true);
578
579 tabHost = (TabHost) findViewById(R.id.tabhost);
580 tabHost.setup();
581
582 new createTabs().execute();
583
584
585 }
586
587 private class createTabs extends AsyncTask<Void, Void, String> {
588
589 @Override
590 protected void onPreExecute() {
591 dialog.show();
592 }
593
594 @Override
595 protected String doInBackground(Void... arg0) {
596 try {
597
598 Cursor c = db.rawQuery(
599 "SELECT infolabel, infotext FROM infodetail where moduleid = '" + moduleid +
600 "' and idx = '" + contractNo + "'", null);
601
602 try {
603 while (c.moveToNext()) {
604 label.add(c.getString(0));
605 info.add(c.getString(1));
606 }
607 } finally {
608 c.close();
609 }
610
611 Cursor cr1 = db.rawQuery("SELECT collInitial, receiptno, licenseplate FROM collectionlist where contractno = '"
612 + contractNo + "' and insno = '" + insNo + "'", null);
613
614 try {
615 if (cr1.moveToFirst()) {
616 collInitial = cr1.getString(0);
617 receiptNo = cr1.getString(1);
618 licensePlate = cr1.getString(2);
619 //Log.d(TAG, "doInBackground: dapetin dari sqlite"+collInitial+receiptNo+licensePlate);
620 }
621 } finally {
622 cr1.close();
623 }
624
625 } catch (Exception e) {
626 CollectionActivity.this.e = e;
627 } finally {
628 db.close();
629 }
630
631 return "";
632 }
633
634 protected void onPostExecute(String sResponse) {
635 if (e == null) {
636
637 TabSpec infoSpec = tabHost.newTabSpec("Info");
638 infoSpec.setIndicator("Info", null);
639 infoSpec.setContent(new TabHost.TabContentFactory() {
640 public View createTabContent(String tag) {
641 final float SCALE = getBaseContext().getResources().getDisplayMetrics().density;
642 float valueDips = 5.0f;
643 int valuePixels = (int) (valueDips * SCALE + 0.5f); // 0.5f for rounding
644
645 ScrollView sv = new ScrollView(mContext);
646 LinearLayout panel = new LinearLayout(mContext);
647 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
648 LayoutParams.MATCH_PARENT,
649 LayoutParams.WRAP_CONTENT);
650
651 panel.setLayoutParams(params);
652 panel.setOrientation(android.widget.LinearLayout.VERTICAL);
653 panel.setPadding(valuePixels, 0, valuePixels, 0);
654
655 TextView tvHeader = new TextView(mContext);
656 tvHeader.setText(custName);
657 tvHeader.setLayoutParams(params);
658 tvHeader.setTextColor(mContext.getResources().getColor(R.color.label_color));
659 tvHeader.setTypeface(null, Typeface.BOLD);
660 tvHeader.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
661 tvHeader.setSingleLine(true);
662 tvHeader.setPadding(0, 10, 0, 0);
663
664 TextView tvContractNo = new TextView(mContext);
665 tvContractNo.setText(contractNo);
666 tvContractNo.setLayoutParams(params);
667 tvContractNo.setTextColor(mContext.getResources().getColor(R.color.label_color));
668 tvContractNo.setTypeface(null, Typeface.ITALIC);
669 tvContractNo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
670 tvContractNo.setSingleLine(true);
671
672 TextView tvAddress = new TextView(mContext);
673 tvAddress.setText(custAddress);
674 tvAddress.setLayoutParams(params);
675 tvAddress.setTextColor(mContext.getResources().getColor(R.color.label_color));
676 tvAddress.setTypeface(null, Typeface.ITALIC);
677 tvAddress.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
678 tvAddress.setMaxLines(2);
679 tvAddress.setPadding(0, 0, 0, 10);
680
681 panel.addView(tvHeader);
682 panel.addView(tvContractNo);
683 panel.addView(tvAddress);
684
685 TableLayout tl = new TableLayout(mContext);
686 tl.setLayoutParams(params);
687 TableRow row;
688
689 //int dip = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
690 // (float) 1, getResources().getDisplayMetrics());
691
692 for (int i = 0; i < label.size(); i++) {
693 row = new TableRow(mContext);
694
695 TextView t1 = new TextView(mContext);
696 t1.setTextColor(getResources().getColor(R.color.label_color));
697 TextView t2 = new TextView(mContext);
698 t2.setTextColor(getResources().getColor(R.color.label_color));
699 TextView t3 = new TextView(mContext);
700 t3.setTextColor(getResources().getColor(R.color.label_color));
701
702 t1.setPadding(0, 0, 0, 3);
703 t2.setPadding(1, 0, 1, 3);
704 t3.setPadding(0, 0, 0, 3);
705
706 t1.setText(label.get(i));
707 t2.setText(" : ");
708 t3.setText(info.get(i).trim());
709
710 t1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
711 t2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
712 t3.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
713
714 row.addView(t1);
715 row.addView(t2);
716 row.addView(t3);
717
718 tl.addView(row, params);
719 }
720
721 tl.setPadding(0, 0, 0, 10);
722 panel.addView(tl);
723
724
725
726 final Button btnPrint = new Button(mContext, null, android.R.attr.buttonStyleSmall);
727 btnPrint.setText("Print");
728 btnPrint.setLayoutParams(params);
729 btnPrint.setVisibility(View.GONE);
730
731 btnPrint.setOnClickListener(new Button.OnClickListener() {
732 public void onClick(View v) {
733
734 WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
735 Method[] wmMethods = wifi.getClass().getDeclaredMethods();
736 for (Method method : wmMethods) {
737 if (method.getName().equals("isWifiApEnabled")) {
738 try {
739
740 if ((Boolean) method.invoke(wifi)) {
741 new PrintInfo().execute();
742 } else {
743 Intent tetherSettings = new Intent();
744 tetherSettings.setClassName("com.android.settings", "com.android.settings.TetherSettings");
745 startActivity(tetherSettings);
746
747 Toast.makeText(mContext, "Please turn on portable Wi-Fi hotspot", Toast.LENGTH_LONG).show();
748 return;
749 }
750
751 } catch (IllegalArgumentException e) {
752 e.printStackTrace();
753 } catch (IllegalAccessException e) {
754 e.printStackTrace();
755 } catch (InvocationTargetException e) {
756 e.printStackTrace();
757 }
758 }
759 }
760
761 }
762 });
763
764
765 panel.addView(btnPrint);
766
767 sv.addView(panel);
768
769 return sv;
770 }
771 });
772
773 // Tab for Map
774 TabSpec mapSpec = tabHost.newTabSpec("Map");
775 mapSpec.setIndicator("Map", null);
776 mapSpec.setContent(new TabHost.TabContentFactory() {
777 public View createTabContent(String tag) {
778 final RelativeLayout panel = new RelativeLayout(mContext);
779 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
780 LayoutParams.MATCH_PARENT,
781 LayoutParams.WRAP_CONTENT);
782
783 panel.setLayoutParams(params);
784
785 //loadinfo();
786
787 View view = View.inflate(mContext, R.layout.map, null);
788 panel.addView(view);
789 //CheckGpsStatus();
790 connectGmapApiClient();
791
792
793
794
795 btnMyLocation = new Button(mContext, null, android.R.attr.buttonStyleSmall);
796 btnMyLocation.setText("My Location");
797 btnMyLocation.setLayoutParams(params);
798 btnMyLocation.setPadding(0, 0, 0, 0);
799 btnMyLocation.setTypeface(null, Typeface.BOLD);
800 btnMyLocation.setBackgroundColor(ContextCompat.getColor(mContext,(R.color.md_white_12)));
801 btnMyLocation.setTextColor(getResources().getColor(R.color.white));
802 btnMyLocation.setVisibility(View.VISIBLE);
803 btnMyLocation.setOnClickListener(new OnClickListener() {
804 @Override
805 public void onClick(View v) {
806
807 currentlocation();
808 //moveMap();
809 }
810 });
811 //btnMyLocation.setOnClickListener(myLocationOnClickListener);
812 ((ViewGroup) view).addView(btnMyLocation);
813
814 btnCheckIn = new Button(mContext, null, android.R.attr.buttonStyleSmall);
815 btnCheckIn.setText("Check In");
816 btnCheckIn.setLayoutParams(params);
817 btnCheckIn.setPadding(0, 0, 0, 0);
818 btnCheckIn.setTypeface(null, Typeface.BOLD);
819 btnCheckIn.setBackgroundColor(ContextCompat.getColor(mContext,(R.color.md_white_12)));
820 btnCheckIn.setTextColor(getResources().getColor(R.color.white));
821 btnCheckIn.setOnClickListener(new OnClickListener() {
822 @Override
823 public void onClick(View v) {
824 CheckInPosition();
825 }
826 });
827 //btnCheckIn.setOnClickListener(checkInOnClickListener);
828 btnCheckIn.setVisibility(View.GONE);
829 ((ViewGroup) view).addView(btnCheckIn);
830
831 try {
832 initiliazeMap();
833
834 } catch (Exception e) {
835 e.printStackTrace();
836 }
837
838
839 return panel;
840 }
841 });
842
843 // Tab for Form
844 TabSpec formSpec = tabHost.newTabSpec("AddData");
845 formSpec.setIndicator("Add Data", null);
846 formSpec.setContent(new TabHost.TabContentFactory() {
847 public View createTabContent(final String tag) {
848 final float SCALE = getBaseContext().getResources().getDisplayMetrics().density;
849 float valueDips = 5.0f;
850 int valuePixels = (int) (valueDips * SCALE + 0.5f); // 0.5f for rounding
851
852 ScrollView sv = new ScrollView(mContext);
853
854 final LinearLayout panel = new LinearLayout(mContext);
855 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
856 LayoutParams.MATCH_PARENT,
857 LayoutParams.WRAP_CONTENT);
858
859 panel.setLayoutParams(params);
860 panel.setOrientation(android.widget.LinearLayout.VERTICAL);
861 panel.setPadding(valuePixels, 0, valuePixels, 0);
862
863 sv.setBackgroundColor(mContext.getResources().getColor(R.color.all_background));
864
865 setDateTimeField();
866 loadPhoto();
867
868 TextView tv = new TextView(mContext);
869 tv.setTextColor(getResources().getColor(R.color.label_color));
870
871 tv.setPadding(5, 5, 0, 0);
872 tv.setText("Final Result");
873 panel.addView(tv);
874
875
876 TextView tv2 = new TextView(mContext);
877 tv2.setTextColor(getResources().getColor(R.color.label_color));
878
879 tv2.setPadding(10, 10, 0, 0);
880 tv2.setText("Take Photo");
881 panel.addView(tv2);
882
883 gambarfoto = new ImageView(mContext);
884 gambarfoto.setImageResource(R.drawable.gallery);
885 gambarfoto.setOnClickListener(new OnClickListener() {
886 @Override
887 public void onClick(View v) {
888 startCamera2();
889
890 }
891 });
892 gambarfoto.setOnLongClickListener(new View.OnLongClickListener() {
893 @Override
894 public boolean onLongClick(View v) {
895 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
896 builder.setIcon(android.R.drawable.ic_dialog_info);
897 builder.setTitle("Information");
898 builder.setMessage("Apakah Anda Ingin Menghapus Fotonya ?")
899 .setCancelable(false)
900 .setNegativeButton("No", new DialogInterface.OnClickListener() {
901 @Override
902 public void onClick(DialogInterface dialog, int which) {
903 dialog.dismiss();
904 }
905 })
906 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
907 public void onClick(final DialogInterface dialog, final int id) {
908 hapusfoto();
909 gambarfoto.setImageBitmap(null);
910 gambarfoto.setImageResource(R.drawable.gallery);
911 dialog.dismiss();
912 Toast.makeText(mContext, "Picture has been removed", Toast.LENGTH_SHORT).show();
913 isgambarValid = false;
914 return;
915 }
916 });
917
918 final AlertDialog alert = builder.create();
919 alert.show();
920
921
922 return true;
923 }
924 });
925 panel.addView(gambarfoto);
926
927
928 //panel.addView(View.inflate(mContext, R.layout.take_photo, null));
929
930 radiogroup = new RadioGroup(mContext);
931 radiogroup.setOrientation(RadioGroup.HORIZONTAL);
932
933 RadioButton[] rbtResult = new RadioButton[3];
934 rbtResult[0] = new RadioButton(mContext);
935 rbtResult[0].setText("Cash ");
936 rbtResult[0].setId(0);
937 rbtResult[0].setTextColor(getResources().getColor(R.color.label_color));
938 radiogroup.addView(rbtResult[0]);
939
940 rbtResult[1] = new RadioButton(mContext);
941 rbtResult[1].setText("EDC ");
942 //rbtResult[1].setId(1);
943 rbtResult[1].setId(R.id.kedua);
944 rbtResult[1].setTextColor(getResources().getColor(R.color.label_color));
945 radiogroup.addView(rbtResult[1]);
946
947 rbtResult[2] = new RadioButton(mContext);
948 rbtResult[2].setText("Not Paid ");
949 //rbtResult[2].setId(2);
950 rbtResult[2].setId(R.id.ketiga);
951 rbtResult[2].setTextColor(getResources().getColor(R.color.label_color));
952 radiogroup.addView(rbtResult[2]);
953
954 radiogroup.check(0);
955
956 panel.addView(radiogroup);
957
958
959 final Button btnNext = new Button(mContext, null, android.R.attr.buttonStyleSmall);
960 btnNext.setText("Next");
961 btnNext.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
962 panel.addView(btnNext);
963
964 btnNext.setOnClickListener(new Button.OnClickListener() {
965 public void onClick(View v) {
966
967 disableRadioButton();
968 btnNext.setVisibility(View.GONE);
969
970 if (getValue().equals("Cash") || getValue().equals("EDC")) {
971
972 try {
973
974 db = datasource.getWritableDatabase();
975
976
977 TextView TanggalBayar = new TextView(mContext);
978 TanggalBayar.setTextColor(getResources().getColor(R.color.label_color));
979
980 TanggalBayar.setPadding(10, 10, 0, 0);
981 TanggalBayar.setText("Tanggal Bayar");
982 panel.addView(TanggalBayar);
983
984
985
986 searchText = new EditText(mContext);
987 searchText.setHint("Input Tanggal Bayar");
988 //searchText.setInputType(InputType.TYPE_NULL);
989 searchText.requestFocus();
990 //searchText.setInputType( InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE);
991 searchText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
992 LinearLayout.LayoutParams.WRAP_CONTENT, 1));
993 searchText.setOnClickListener(new OnClickListener() {
994 @Override
995 public void onClick(View v) {
996 //fromDatePickerDialog.show();
997 datepicker();
998 }
999 });
1000 panel.addView(searchText);
1001
1002
1003
1004 theForm = new Form();
1005
1006 Cursor c = db.rawQuery("SELECT name, label, type, required, optionsname, " +
1007 "optionsid, hint, errmsg, maxlength, issearchable FROM form where moduleid = '" + moduleid + "'", null);
1008
1009 try {
1010 while (c.moveToNext()) {
1011
1012 FormField tempField = new FormField();
1013 tempField.setName(c.getString(0));
1014 tempField.setLabel(c.getString(1));
1015 tempField.setType(c.getString(2));
1016
1017 if (c.getString(3).equals("Y"))
1018 tempField.setRequired(true);
1019 else
1020 tempField.setRequired(false);
1021
1022 tempField.setOptionsName(c.getString(4));
1023 tempField.setOptionsID(c.getString(5));
1024 tempField.setHint(c.getString(6));
1025 tempField.setErrmsg(c.getString(7));
1026 tempField.setMaxLength(c.getString(8));
1027
1028 if (c.getString(9).equals("Y"))
1029 tempField.setIsSearchable(true);
1030 else
1031 tempField.setIsSearchable(false);
1032
1033 theForm.getFields().add(tempField);
1034 }
1035 } finally {
1036 c.close();
1037 db.close();
1038 }
1039
1040 } catch (Exception e) {
1041 Log.e(tag, "Error occurred in GetFormDataFromLocal : " + e.getMessage());
1042 e.printStackTrace();
1043 }
1044
1045 int i;
1046 String initialText;
1047
1048
1049 for (i = 0; i < theForm.fields.size(); i++) {
1050
1051 initialText = "";
1052
1053
1054
1055 if (theForm.fields.elementAt(i).getName().equals("InstallmentAmount"))
1056 initialText = insAmount;
1057 Log.d(TAG, "onClick: initialText "+initialText);
1058
1059 if (theForm.fields.elementAt(i).getType().equals("text")) {
1060 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), initialText, theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1061 ((EditBox) theForm.fields.elementAt(i).obj).makeChar();
1062 panel.addView((View) theForm.fields.elementAt(i).obj);
1063 } else if (theForm.fields.elementAt(i).getType().equals("number")) {
1064 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), initialText, theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1065 ((EditBox) theForm.fields.elementAt(i).obj).makeNumber();
1066 panel.addView((View) theForm.fields.elementAt(i).obj);
1067 } else if (theForm.fields.elementAt(i).getType().equals("decimal")) {
1068 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), initialText, theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1069 ((EditBox) theForm.fields.elementAt(i).obj).makeDecimal();
1070 panel.addView((View) theForm.fields.elementAt(i).obj);
1071 } else if (theForm.fields.elementAt(i).getType().equals("multiline")) {
1072 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), initialText, theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1073 ((EditBox) theForm.fields.elementAt(i).obj).makeMultiLine();
1074 panel.addView((View) theForm.fields.elementAt(i).obj);
1075 } else if (theForm.fields.elementAt(i).getType().equals("pickone")) {
1076 theForm.fields.elementAt(i).obj = new PickOne(mContext, (" " + theForm.fields.elementAt(i).getLabel()), theForm.fields.elementAt(i).getOptionsName(), theForm.fields.elementAt(i).getOptionsID(), theForm.fields.elementAt(i).getIsSearchable());
1077 panel.addView((View) theForm.fields.elementAt(i).obj);
1078 } else if (theForm.fields.elementAt(i).getType().equals("pickonechoice")) {
1079 theForm.fields.elementAt(i).obj = new PickOneChoice(mContext, (" " + theForm.fields.elementAt(i).getLabel()));
1080 panel.addView((View) theForm.fields.elementAt(i).obj);
1081 } else if (theForm.fields.elementAt(i).getType().equals("radiobutton")) {
1082 theForm.fields.elementAt(i).obj = new RadioBtn(mContext, (" " + theForm.fields.elementAt(i).getLabel()), theForm.fields.elementAt(i).getOptionsName(), theForm.fields.elementAt(i).getOptionsID());
1083 panel.addView((View) theForm.fields.elementAt(i).obj);
1084 } else if (theForm.fields.elementAt(i).getType().equals("date")) {
1085 theForm.fields.elementAt(i).obj = new PickDate(mContext, (" " + theForm.fields.elementAt(i).getLabel()));
1086 panel.addView((View) theForm.fields.elementAt(i).obj);
1087 } else if (theForm.fields.elementAt(i).getType().equals("pickonesupplier")) {
1088 theForm.fields.elementAt(i).obj = new PickOneSupplier(mContext, (" " + theForm.fields.elementAt(i).getLabel()), "supplier", "suppliername", "supplierid");
1089 panel.addView((View) theForm.fields.elementAt(i).obj);
1090 }
1091 }
1092
1093 /*Button btn = new Button(mContext, null, android.R.attr.buttonStyleSmall);
1094 btn.setText("Submit");
1095 btn.setLayoutParams(new LayoutParams(
1096 ViewGroup.LayoutParams.MATCH_PARENT,
1097 ViewGroup.LayoutParams.WRAP_CONTENT));*/
1098
1099 submit = new Button(mContext, null, android.R.attr.buttonStyleSmall);
1100 submit.setText("Submit");
1101 submit.setLayoutParams(new LayoutParams(
1102 ViewGroup.LayoutParams.MATCH_PARENT,
1103 ViewGroup.LayoutParams.WRAP_CONTENT));
1104
1105
1106
1107 submit.setOnClickListener(new Button.OnClickListener() {
1108 public void onClick(View v) {
1109 boolean check;
1110 boolean cekgambar;
1111 boolean isEnabled = bluetoothAdapter.isEnabled();
1112 int i = 1;
1113
1114 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
1115
1116 if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
1117 buildLocationAlert();
1118 return;
1119 }
1120
1121 if (isMapImageValid == false) {
1122 Toast.makeText(mContext, "Please check in first", Toast.LENGTH_SHORT).show();
1123 return;
1124 }
1125
1126 if (isgambarValid == false){
1127 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
1128 builder.setIcon(android.R.drawable.ic_dialog_info);
1129 builder.setTitle("Information");
1130 builder.setMessage(R.string.information2)
1131 .setCancelable(false)
1132 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
1133 public void onClick(final DialogInterface dialog, final int id) {
1134 dialog.dismiss();
1135 return;
1136 }
1137 });
1138
1139 final AlertDialog alert = builder.create();
1140 alert.show();
1141 return;
1142 }
1143
1144
1145 cekgambar = checkgambar2();
1146 check = CheckForm();
1147
1148
1149 if (!cekgambar) {
1150 Toast.makeText(mContext, "Take Photo FIRST !!! ", Toast.LENGTH_SHORT).show();
1151 return;
1152 }
1153
1154 if (!check) {
1155 Toast.makeText(mContext, "Enter all required (!) fields", Toast.LENGTH_SHORT).show();
1156 return;
1157 }
1158
1159 //buildAlertSave();
1160
1161 if(bluetoothAdapter == null){
1162 Toast.makeText(mContext,"BlueTooth adapter not found",Toast.LENGTH_SHORT).show();
1163 }
1164 else {
1165 if (!isEnabled) {
1166 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
1167 startActivityForResult(intent,1);
1168 }else if (isEnabled){
1169 Toast.makeText(mContext,"Blutut udah nyala",Toast.LENGTH_SHORT).show();
1170 }
1171 }
1172
1173 buildAlertSave();
1174
1175
1176// WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
1177// Method[] wmMethods = wifi.getClass().getDeclaredMethods();
1178// for (Method method : wmMethods) {
1179// if (method.getName().equals("isWifiApEnabled")) {
1180// try {
1181//
1182// if ((Boolean) method.invoke(wifi)) {
1183// buildAlertSave();
1184// } else {
1185// Intent tetherSettings = new Intent();
1186// tetherSettings.setClassName("com.android.settings", "com.android.settings.TetherSettings");
1187// startActivity(tetherSettings);
1188// Toast.makeText(mContext, "Please turn on portable Wi-Fi hotspot", Toast.LENGTH_LONG).show();
1189// return;
1190// }
1191//
1192// } catch (IllegalArgumentException e) {
1193// e.printStackTrace();
1194// } catch (IllegalAccessException e) {
1195// e.printStackTrace();
1196// } catch (InvocationTargetException e) {
1197// e.printStackTrace();
1198// }
1199// }
1200// }
1201
1202
1203 }
1204 });
1205 panel.addView(submit);
1206 //panel.addView(btn);
1207 } else {
1208 try {
1209 //not paid
1210
1211 theForm = new Form();
1212
1213 db = datasource.getWritableDatabase();
1214
1215
1216
1217 //moduleid = 99
1218 Cursor c = db.rawQuery("SELECT name, label, type, required, " +
1219 "optionsname, optionsid, hint, errmsg, maxlength, issearchable FROM form where moduleid = '99'", null);
1220
1221 try {
1222 while (c.moveToNext()) {
1223
1224 FormField tempField = new FormField();
1225 tempField.setName(c.getString(0));
1226 tempField.setLabel(c.getString(1));
1227 tempField.setType(c.getString(2));
1228
1229 if (c.getString(3).equals("Y"))
1230 tempField.setRequired(true);
1231 else
1232 tempField.setRequired(false);
1233
1234 tempField.setOptionsName(c.getString(4));
1235 tempField.setOptionsID(c.getString(5));
1236 tempField.setHint(c.getString(6));
1237 tempField.setErrmsg(c.getString(7));
1238 tempField.setMaxLength(c.getString(8));
1239
1240 if (c.getString(9).equals("Y"))
1241 tempField.setIsSearchable(true);
1242 else
1243 tempField.setIsSearchable(false);
1244
1245 theForm.getFields().add(tempField);
1246 }
1247 } finally {
1248 c.close();
1249 db.close();
1250 }
1251
1252 } catch (Exception e) {
1253 Log.e(tag, "Error occurred in GetFormDataFromLocal : " + e.getMessage());
1254 e.printStackTrace();
1255 }
1256
1257 int i;
1258
1259 for (i = 0; i < theForm.fields.size(); i++) {
1260
1261 if (theForm.fields.elementAt(i).getType().equals("text")) {
1262 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), "", theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1263 ((EditBox) theForm.fields.elementAt(i).obj).makeChar();
1264 panel.addView((View) theForm.fields.elementAt(i).obj);
1265 } else if (theForm.fields.elementAt(i).getType().equals("number")) {
1266 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), "", theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1267 ((EditBox) theForm.fields.elementAt(i).obj).makeNumber();
1268 panel.addView((View) theForm.fields.elementAt(i).obj);
1269 } else if (theForm.fields.elementAt(i).getType().equals("decimal")) {
1270 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), "", theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1271 ((EditBox) theForm.fields.elementAt(i).obj).makeDecimal();
1272 panel.addView((View) theForm.fields.elementAt(i).obj);
1273 } else if (theForm.fields.elementAt(i).getType().equals("multiline")) {
1274 theForm.fields.elementAt(i).obj = new EditBox(mContext, " " + theForm.fields.elementAt(i).getLabel(), "", theForm.fields.elementAt(i).getHint(), theForm.fields.elementAt(i).getMaxLength());
1275 ((EditBox) theForm.fields.elementAt(i).obj).makeMultiLine();
1276 panel.addView((View) theForm.fields.elementAt(i).obj);
1277 } else if (theForm.fields.elementAt(i).getType().equals("pickone")) {
1278 theForm.fields.elementAt(i).obj = new PickOne(mContext, (" " + theForm.fields.elementAt(i).getLabel()), theForm.fields.elementAt(i).getOptionsName(), theForm.fields.elementAt(i).getOptionsID(), theForm.fields.elementAt(i).getIsSearchable());
1279 panel.addView((View) theForm.fields.elementAt(i).obj);
1280 } else if (theForm.fields.elementAt(i).getType().equals("pickonechoice")) {
1281 theForm.fields.elementAt(i).obj = new PickOneChoice(mContext, (" " + theForm.fields.elementAt(i).getLabel()));
1282 panel.addView((View) theForm.fields.elementAt(i).obj);
1283 } else if (theForm.fields.elementAt(i).getType().equals("radiobutton")) {
1284 theForm.fields.elementAt(i).obj = new RadioBtn(mContext, (" " + theForm.fields.elementAt(i).getLabel()), theForm.fields.elementAt(i).getOptionsName(), theForm.fields.elementAt(i).getOptionsID());
1285 panel.addView((View) theForm.fields.elementAt(i).obj);
1286 } else if (theForm.fields.elementAt(i).getType().equals("date")) {
1287 theForm.fields.elementAt(i).obj = new PickDate(mContext, (" " + theForm.fields.elementAt(i).getLabel()));
1288 panel.addView((View) theForm.fields.elementAt(i).obj);
1289 } else if (theForm.fields.elementAt(i).getType().equals("pickonesupplier")) {
1290 theForm.fields.elementAt(i).obj = new PickOneSupplier(mContext, (" " + theForm.fields.elementAt(i).getLabel()), "supplier", "suppliername", "supplierid");
1291 panel.addView((View) theForm.fields.elementAt(i).obj);
1292 }
1293 }
1294
1295 Button btn = new Button(mContext, null, android.R.attr.buttonStyleSmall);
1296 btn.setText("Submit");
1297 btn.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
1298
1299 btn.setOnClickListener(new Button.OnClickListener() {
1300 public void onClick(View v) {
1301 boolean check;
1302 boolean cekgambar;
1303
1304 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
1305
1306 if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
1307 buildLocationAlert();
1308 return;
1309 }
1310
1311 if (isMapImageValid == false) {
1312 Toast.makeText(mContext, "Please check in first", Toast.LENGTH_SHORT).show();
1313 return;
1314 }
1315
1316
1317
1318
1319 if (isgambarValid == false){
1320 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
1321 builder.setIcon(android.R.drawable.ic_dialog_info);
1322 builder.setTitle("Information");
1323 builder.setMessage(R.string.information2)
1324 .setCancelable(false)
1325 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
1326 public void onClick(final DialogInterface dialog, final int id) {
1327 dialog.dismiss();
1328 return;
1329 }
1330 });
1331
1332 final AlertDialog alert = builder.create();
1333 alert.show();
1334 return;
1335 }
1336
1337
1338 cekgambar = checkgambar2();
1339
1340 if (!cekgambar) {
1341 Toast.makeText(mContext, "Take Photo FIRST !!! ", Toast.LENGTH_SHORT).show();
1342 return;
1343 }
1344
1345
1346 check = CheckForm();
1347
1348
1349
1350 if (!check) {
1351 Toast.makeText(mContext, "Enter all required (!) fields", Toast.LENGTH_SHORT).show();
1352 return;
1353
1354
1355 } else {
1356 new PostData2().execute();
1357 }
1358
1359 }
1360 });
1361
1362 panel.addView(btn);
1363 }
1364
1365 }
1366 });
1367
1368 sv.addView(panel);
1369 return sv;
1370 }
1371 });
1372
1373 tabHost.addTab(infoSpec);
1374 tabHost.addTab(mapSpec);
1375 tabHost.addTab(formSpec);
1376
1377 //tabHost.getTabWidget().getChildAt(0).getLayoutParams().height = 30;
1378 //tabHost.getTabWidget().getChildAt(1).getLayoutParams().height = 30;
1379 //tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = 30;
1380 tabHost.getTabWidget().setCurrentTab(0);
1381
1382 dialog.dismiss();
1383 } else {
1384 dialog.dismiss();
1385
1386 Toast.makeText(mContext, "Connection time out", Toast.LENGTH_SHORT).show();
1387 finish();
1388 Intent intent = new Intent(mContext, ListCollectionActivity.class);
1389 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
1390 intent.putExtra("flagUpdate", "N");
1391 startActivity(intent);
1392 }
1393
1394 }
1395 }
1396
1397
1398 ///------BAGIAN UNTUK TAB ADD DATA ( TAKE PHOTO ) -----------///////
1399 private void loadPhoto() {
1400
1401 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
1402 != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission
1403 .READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) {
1404 requestReadPhoneStatePermission();
1405 } else {
1406 Toast.makeText(mContext, "Take Photo First...!!!", Toast.LENGTH_SHORT).show();
1407 //startcamera();
1408 }
1409 }
1410 private void requestReadPhoneStatePermission() {
1411 if (ActivityCompat.shouldShowRequestPermissionRationale(this,
1412 android.Manifest.permission.CAMERA)) {
1413 new AlertDialog.Builder(CollectionActivity.this)
1414 .setTitle("Permission Request")
1415 .setMessage("Check permission")
1416 .setCancelable(false)
1417 .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
1418 public void onClick(DialogInterface dialog, int which) {
1419 //re-request
1420 ActivityCompat.requestPermissions(CollectionActivity.this,
1421 new String[]{
1422 android.Manifest.permission.CAMERA,
1423 android.Manifest.permission.READ_EXTERNAL_STORAGE},
1424 MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
1425 }
1426 })
1427 .show();
1428 } else {
1429 ActivityCompat.requestPermissions(this, new String[]{
1430 android.Manifest.permission.CAMERA,
1431 android.Manifest.permission.READ_EXTERNAL_STORAGE},
1432 MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
1433 }
1434 }
1435 @Override
1436 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
1437
1438 if (requestCode == MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE) {
1439 // Received permission result for READ_PHONE_STATE permission.est.");
1440 // Check if the only required permission has been granted
1441 if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
1442 Toast.makeText(getApplicationContext(), "Permission IMEI HAVE BEEN GRANTED", Toast.LENGTH_SHORT).show();
1443 //startcamera();
1444// if (userchoosen.equals("Take Photo")) {
1445// cameraIntent();
1446// } else if (userchoosen.equals("Choose from library")) {
1447// galleryintent();
1448// }
1449 }
1450
1451 } else {
1452 Toast.makeText(getApplicationContext(), "permission gagal", Toast.LENGTH_SHORT).show();
1453
1454 }
1455 }
1456 @Override
1457 public void onActivityResult(int requestCode, int resultCode, Intent data) {
1458 super.onActivityResult(requestCode, resultCode, data);
1459
1460
1461// if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
1462// if (requestCode == SELECT_PICTURE) {
1463//
1464// selectedImageUri = data.getData();
1465// selectedImagePath = getPath(selectedImageUri);
1466// gambarfoto.setTag(selectedImagePath);
1467//
1468// if (!selectedImageUri.toString().toLowerCase()
1469// .startsWith("content://media/")) {
1470// Toast.makeText(CollectionActivity.this,
1471// "Please Select Image From Local Storage",
1472// Toast.LENGTH_SHORT).show();
1473// Log.d("ambil", "onActivityResult: " + selectedImagePath);
1474// } else {
1475//
1476// File folder = new File(
1477// Environment.getExternalStorageDirectory()
1478// + File.separator
1479// + CollectionActivity.this
1480// .getString(R.string.app_name)
1481// + File.separator + "Collection_Photo");
1482//
1483// Bitmap asli = BitmapFactory.decodeFile(gambarfoto
1484// .getTag().toString());
1485// Bitmap thumbnail = scaleDown(asli, 256, true);
1486//
1487// ByteArrayOutputStream bytes = new ByteArrayOutputStream();
1488// thumbnail.compress(Bitmap.CompressFormat.JPEG, 80,
1489// bytes);
1490//
1491//
1492// Log.d("ambil_2", "onActivityResult: " + selectedImagePath);
1493//
1494//
1495// }
1496//
1497// }
1498// Bitmap photo = (Bitmap) data.getExtras().get("data");
1499// gambarfoto.setImageBitmap(photo);
1500//
1501// }
1502
1503 if (requestCode == CAMERA_REQUEST) {
1504
1505 if (resultCode == RESULT_OK){
1506 datax = data;
1507
1508 if(dialog != null && dialog.isShowing())
1509 dialog.dismiss();
1510
1511 new PictureProcessing2().execute();
1512 }
1513 else if (resultCode == RESULT_CANCELED) {
1514
1515 if (flag2 ==0){
1516
1517 File imageFile = new File(getPath(imageUri));
1518
1519 if(imageFile.exists()) {
1520
1521 if (Build.VERSION.SDK_INT >= 4.4) {
1522 Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1523 Uri contentUri = Uri.fromFile(imageFile);
1524 mediaScanIntent.setData(contentUri);
1525 this.sendBroadcast(mediaScanIntent);
1526
1527 try {
1528 getContentResolver() .delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1529 MediaStore.Images.Media.DATA
1530 + "='"
1531 + imageFile.getPath()
1532 + "'", null);
1533 } catch (Exception e) {
1534 e.printStackTrace();
1535 }
1536 }else{
1537 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
1538 Uri.parse("file://" + Environment.getExternalStorageDirectory())));
1539
1540 try {
1541 getContentResolver() .delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1542 MediaStore.Images.Media.DATA
1543 + "='"
1544 + imageFile.getPath()
1545 + "'", null);
1546 } catch (Exception e) {
1547 e.printStackTrace();
1548 }
1549 }
1550
1551 }
1552 }
1553
1554 Toast.makeText(mContext, "Picture not attached", Toast.LENGTH_SHORT).show();
1555 }
1556 else {
1557 if (flag2 ==0){
1558
1559 File imageFile = new File(getPath(imageUri));
1560
1561 if(imageFile.exists()) {
1562 if (Build.VERSION.SDK_INT >= 4.4) {
1563 Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1564 Uri contentUri = Uri.fromFile(imageFile);
1565 mediaScanIntent.setData(contentUri);
1566 this.sendBroadcast(mediaScanIntent);
1567
1568 try {
1569 getContentResolver() .delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1570 MediaStore.Images.Media.DATA
1571 + "='"
1572 + imageFile.getPath()
1573 + "'", null);
1574 } catch (Exception e) {
1575 e.printStackTrace();
1576 }
1577 }else{
1578 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
1579
1580 try {
1581 getContentResolver() .delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
1582 MediaStore.Images.Media.DATA
1583 + "='"
1584 + imageFile.getPath()
1585 + "'", null);
1586 } catch (Exception e) {
1587 e.printStackTrace();
1588 }
1589 }
1590 }
1591 }
1592
1593 Toast.makeText(mContext, "Picture not attached", Toast.LENGTH_SHORT).show();
1594 }
1595 }
1596 }
1597
1598
1599 ///--------IMAGE COLLECTION----------------\\\
1600
1601
1602
1603
1604
1605 private void startCamera2(){
1606 if(dialog != null && dialog.isShowing())
1607 dialog.dismiss();
1608
1609 //String fileName = "photoCollection.jpg";
1610 String fileName = "photoCollection";
1611
1612 ContentValues values = new ContentValues();
1613
1614 values.put(MediaStore.Images.Media.TITLE, fileName);
1615 values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
1616
1617 imageUri = getContentResolver().insert(
1618 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
1619
1620 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
1621 intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
1622
1623 startActivityForResult(intent, CAMERA_REQUEST);
1624 }
1625 void loadcustomer(){
1626 latinya2 = model_customer.getLat();
1627 longinya2 = model_customer.getLon();
1628 Log.d(TAG, "loadcustomer: latlongnya "+latinya2 +"dan"+longinya2);
1629
1630 }
1631 private class PictureProcessing2 extends AsyncTask<Void, Void, String> {
1632
1633 @Override
1634 protected void onPreExecute() {
1635 if(dialog != null && dialog.isShowing())
1636 dialog.dismiss();
1637
1638 dialog2 = ProgressDialog.show(mContext, "", "Attach Picture...", true);
1639 }
1640
1641 @Override
1642 protected String doInBackground(Void... params) {
1643 String result = "";
1644
1645 try{
1646
1647 if(flag2 == 0 && imageUri != null) {
1648 loadcustomer();
1649 PictureAttach2();
1650 }
1651 else if(flag2 != 0) {
1652 loadcustomer();
1653 PictureAttach2();
1654
1655 }
1656 else
1657 result = "imageUri = null";
1658
1659
1660 SystemClock.sleep(2000);
1661
1662
1663
1664 }catch (Exception e) {
1665 CollectionActivity.this.e = e;
1666 result = e.getMessage();
1667 }
1668
1669 return result;
1670 }
1671
1672 @Override
1673 protected void onPostExecute(String sResponse) {
1674 if(dialog2 != null && dialog2.isShowing())
1675 dialog2.dismiss();
1676
1677 if (e==null && sResponse.length()==0){
1678
1679 if(gambarfoto!=null)
1680 gambarfoto.setImageBitmap(null);
1681
1682
1683
1684 File cacheDir = getBaseContext().getCacheDir();
1685 File f = new File(cacheDir, "picCollection");
1686
1687// File folder = new File(
1688// Environment.getExternalStorageDirectory()
1689// + File.separator
1690// + CollectionActivity.this
1691// .getString(R.string.app_name)
1692// + File.separator + "Collection");
1693// File file = new File(folder.getAbsolutePath()
1694// + File.separator + contractNo + ".jpg"); // tambahan 2 - 10 - 2017
1695
1696 FileInputStream fis = null;
1697
1698 try {
1699 //fis = new FileInputStream(file); // tambahan 2 - 10 - 2017
1700 fis = new FileInputStream(f);
1701 } catch (FileNotFoundException e) {
1702 e.printStackTrace();
1703 }
1704 Bitmap bitmap = BitmapFactory.decodeStream(fis);
1705 bitmap = Bitmap.createScaledBitmap(bitmap, 350, 350, false);
1706 //bitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, false);
1707
1708
1709
1710 if(bitmap!=null && gambarfoto!=null) {
1711 gambarfoto.setImageBitmap(bitmap);
1712 }
1713 isgambarValid = true;
1714 try {
1715 fis.close();
1716 cacheDir.delete();
1717 } catch (IOException e1) {
1718 e1.printStackTrace();
1719 }
1720 System.gc();
1721 }else
1722 Toast.makeText(mContext, sResponse, Toast.LENGTH_SHORT).show();
1723 }
1724 }
1725 private void PictureAttach2(){
1726
1727 try{
1728 db = datasource.getWritableDatabase();
1729 String picturePath = "";
1730 int exifOrientation;
1731 final int reqWidth = 320;
1732 final int reqHeight = 240;
1733 int scale = 2;
1734 ByteArrayOutputStream bos = null;
1735 image_str_coll = "";
1736 String latinya22 = "";
1737 String longinya22 = "";
1738 //Bitmap bitmap = null;
1739
1740 if (flag2 ==0){
1741 picturePath = getPath(imageUri);
1742 exifOrientation = getCameraPhotoOrientation(mContext,imageUri,picturePath);
1743 }
1744 else{
1745 picturePath = getPath(datax.getData());
1746 exifOrientation = getCameraPhotoOrientation(mContext,datax.getData(),picturePath);
1747 }
1748
1749 BitmapFactory.Options o = new BitmapFactory.Options();
1750 o.inJustDecodeBounds = true;
1751 BitmapFactory.decodeFile(picturePath, o);
1752
1753 if (o.outHeight > reqHeight || o.outWidth > reqWidth) {
1754 if (o.outWidth > o.outHeight) {
1755 scale = Math.round((float)o.outHeight / (float)reqHeight);
1756 } else {
1757 scale = Math.round((float)o.outWidth / (float)reqWidth);
1758 }
1759 }
1760
1761 System.gc();
1762
1763 Matrix matrix = new Matrix();
1764 matrix.postRotate(exifOrientation);
1765
1766 o.inJustDecodeBounds = false;
1767 o.inSampleSize = scale;
1768 BitmapFactory.decodeFile(picturePath, o);
1769
1770
1771
1772 System.gc();
1773
1774 Bitmap bitmap2 = null;
1775
1776 bitmap2 = Bitmap.createBitmap(BitmapFactory.decodeFile(picturePath,o) , 0, 0,
1777 o.outWidth, o.outHeight, matrix, true);
1778
1779 bos = new ByteArrayOutputStream();
1780 //bitmap2 = getResizedBitmap2(bitmap2,200); // tambahan 2 - 10 - 2017
1781 //bitmap2.compress(Bitmap.CompressFormat.JPEG, 50, bos); // tambahan 2 - 10 - 2017
1782 bitmap2.compress(Bitmap.CompressFormat.JPEG, 80, bos);
1783
1784
1785 File cacheDir = getBaseContext().getCacheDir();
1786 File f = new File(cacheDir, "picCollection");
1787//
1788// File folder = new File(
1789// Environment.getExternalStorageDirectory()
1790// + File.separator
1791// + CollectionActivity.this
1792// .getString(R.string.app_name)
1793// + File.separator + "Collection");
1794// File file = new File(folder.getAbsolutePath()
1795// + File.separator + contractNo + ".jpg"); // tambahan 2 - 10 - 2017
1796
1797
1798 try {
1799 FileOutputStream out = new FileOutputStream(f);
1800 //FileOutputStream oout = new FileOutputStream(file);// tambahan 2 - 10 - 2017
1801
1802 bitmap2.compress(Bitmap.CompressFormat.JPEG, 40, out);
1803 //
1804
1805 out.flush();
1806 out.close();
1807
1808 //timestampItAndSave2(file.getAbsolutePath());
1809 timestampItAndSave2(f.getAbsolutePath());
1810 } catch (FileNotFoundException e) {
1811 e.printStackTrace();
1812 } catch (IOException e) {
1813 e.printStackTrace();
1814 }
1815
1816 bitmap2.recycle();
1817 bitmap2 = null;
1818 matrix.reset();
1819 matrix = null;
1820
1821 System.gc();
1822
1823 byte[] byt = bos.toByteArray();
1824 if (image_str_coll != null){
1825 image_str_coll = Base64.encodeToString(byt,Base64.DEFAULT);
1826 }else{
1827 image_str_coll = "";
1828
1829 }
1830 if(latinya2==null || longinya2==null){
1831 latinya22 = "";
1832 longinya22 = "";
1833 }else {
1834 latinya22 = latinya2;
1835 longinya22 = longinya2;
1836 }
1837
1838// latinya22 = latinya2;
1839// longinya22 = longinya2;
1840
1841
1842 bos.flush();
1843 bos.close();
1844 System.gc();
1845
1846 Cursor cursor = db.rawQuery("SELECT id FROM " + tableImageCollection + " WHERE buttonId = '" + Integer.toString(Action_Code) +"'", null);
1847
1848 if(cursor.moveToFirst())
1849 {
1850 ContentValues cv = new ContentValues();
1851 cv.put("imageStr", image_str_coll);
1852 datasource.updateData(db,cv,tableImageCollection," buttonId = '" + Action_Code + "'");
1853 cv.clear();
1854 }else{
1855 ContentValues cv = new ContentValues();
1856
1857 if (Action_Code == buttonId5){
1858 deleteFlag5 = true;
1859 }
1860
1861 cv.put("imageStr", image_str_coll);
1862 cv.put("buttonId", Action_Code);
1863 cv.put("lat", latinya22);
1864 cv.put("lng", longinya22);
1865 Log.d(TAG, "PictureAttach2: cek latitudenya customer " + latinya22+" dan longitudenya customer " + longinya22);
1866 Log.d(TAG, "PictureAttach2: "+image_str_coll);
1867 datasource.generateData(db,cv,tableImageCollection);
1868
1869 cv.clear();
1870 cursor.close();
1871
1872 }
1873 }
1874 catch (Exception e) {
1875 throw new RuntimeException(e);
1876 }
1877 finally{
1878 System.gc();
1879 }
1880 }
1881 private boolean checkgambar2() {
1882
1883 try {
1884 boolean good = true;
1885
1886 if (isgambarValid == false){
1887 Toast.makeText(mContext,"Take Picture Please.",Toast.LENGTH_SHORT).show();
1888
1889 }else if (isgambarValid == true){
1890 Toast.makeText(mContext,"Picture Have Beed Added.",Toast.LENGTH_SHORT).show();
1891 }
1892
1893
1894 return good;
1895 } catch (Exception e) {
1896 Log.e("DashBoardActivity", "Error in checkgambar2() : " + e.getMessage());
1897 e.printStackTrace();
1898 return false;
1899 }
1900
1901 }
1902 private void hapusfoto(){
1903 try{
1904 db = datasource.getWritableDatabase();
1905 datasource.deleteData(db, " buttonId = '" + Action_Code + "'", tableImageCollection);
1906 db.close();
1907 }catch (Exception e){
1908 e.printStackTrace();
1909 }
1910
1911 }
1912 void cekdatagmabar(){
1913 db = datasource.getWritableDatabase();
1914 Cursor cr2 = db.rawQuery("Select * from imagecollection",null);
1915 int cnt = cr2.getCount();
1916 Log.d(TAG, "onClick: cek count row1 " + cnt);
1917 if (cnt==0){
1918 final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
1919 builder.setIcon(android.R.drawable.ic_dialog_info);
1920 builder.setTitle("Information");
1921 builder.setMessage(R.string.information2).
1922 setCancelable(false).setPositiveButton("Yes",
1923 new DialogInterface.OnClickListener() {
1924 public void onClick(final DialogInterface dialog, final int id) {
1925 dialog.dismiss();
1926 }
1927 });
1928 final AlertDialog alert = builder.create();
1929 alert.show();
1930 cr2.close();
1931 }
1932 }
1933
1934 public String getStringImage(Bitmap xxx){
1935 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1936
1937 xxx = getResizedBitmap(xxx,190,190);
1938 xxx.compress(Bitmap.CompressFormat.JPEG, 70, baos);
1939 byte[] imageBytes = baos.toByteArray();
1940
1941 String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
1942
1943 return encodedImage;
1944 }
1945
1946 public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
1947
1948 int width = bm.getWidth();
1949
1950 int height = bm.getHeight();
1951
1952 float scaleWidth = ((float) newWidth) / width;
1953
1954 float scaleHeight = ((float) newHeight) / height;
1955 Matrix matrix = new Matrix();
1956 matrix.postScale(scaleWidth, scaleHeight);
1957
1958 Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
1959
1960 return resizedBitmap;
1961
1962 }
1963
1964
1965
1966
1967///--------IMAGE COLLECTION----------------\\\
1968
1969
1970
1971 ///------BAGIAN UNTUK TAB MAP ( PETA ) -----------///////
1972
1973 private void loadinfo(){
1974 AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
1975 builder.setIcon(android.R.drawable.ic_dialog_info);
1976 builder.setTitle("Information");
1977 builder.setMessage(R.string.information)
1978 .setCancelable(false)
1979 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
1980 public void onClick(final DialogInterface dialog, final int id) {
1981 dialog.dismiss();
1982 return;
1983 }
1984 });
1985
1986 final AlertDialog alert = builder.create();
1987 alert.show();
1988 }
1989
1990 private void initiliazeMap() {
1991 if (mapFragment == null) {
1992 //googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
1993 mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
1994 mapFragment.getMapAsync(this);
1995 if (mapFragment == null) {
1996 Toast.makeText(getApplicationContext(), "mapnya gak muncul", Toast.LENGTH_SHORT).show();
1997 }
1998// googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
1999// googleMap.getUiSettings().setMyLocationButtonEnabled(false);
2000// googleMap.setMyLocationEnabled(true);
2001//
2002// googleMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
2003// @Override
2004// public void onMyLocationChange(Location point) {
2005// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(point.getLatitude(), point.getLongitude()), 8);
2006// googleMap.animateCamera(cameraUpdate);
2007// googleMap.setMyLocationEnabled(false);
2008// googleMap.setOnMyLocationChangeListener(null);
2009// }
2010// });
2011 }
2012 }
2013
2014 @Override
2015 public void onMapReady(final GoogleMap googleMap) {
2016 Nmap = googleMap;
2017 Nmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2018
2019 CheckGpsStatus();
2020 if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
2021 != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
2022 android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
2023
2024 return;
2025 }
2026
2027 Nmap.setMyLocationEnabled(true);
2028 }
2029
2030 public void CheckGpsStatus() {
2031
2032 int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
2033 locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
2034 boolean enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
2035 //GpsStatus = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
2036
2037 if (enabled) {
2038 if (status == ConnectionResult.SUCCESS) {
2039 //Toast.makeText(getApplicationContext(), "petanya muncul", Toast.LENGTH_SHORT).show();
2040 //posisicustomer();
2041 //currentlocation();
2042 //connectGmapApiClient();
2043 } else {
2044 GooglePlayServicesUtil.getErrorDialog(status, this, status);
2045
2046
2047 }
2048 } else {
2049
2050 new SweetAlertDialog(CollectionActivity.this, SweetAlertDialog.WARNING_TYPE)
2051 .setTitleText("GPS anda tidak aktif")
2052 .setContentText("Aktipkan GPS Anda Terlebih Dahulu")
2053 .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
2054 @Override
2055 public void onClick(SweetAlertDialog sweetAlertDialog) {
2056
2057 Intent pindah = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
2058 startActivity(pindah);
2059 finish();
2060 }
2061 }).show();
2062
2063 }
2064
2065 }
2066
2067 private synchronized void connectGmapApiClient() {
2068 googleApiClient = new GoogleApiClient.Builder(this)
2069 .addConnectionCallbacks(this)
2070 .addOnConnectionFailedListener(this)
2071 .addApi(LocationServices.API)
2072 .build();
2073 }
2074
2075 void currentlocation() {
2076
2077 gps = new GPSTracker(mContext);
2078 isMapImageValid = false;
2079 handlelocation();
2080
2081 if (gps.canGetLocation()) {
2082
2083 double latitude = gps.getLatitude();
2084 double longitude = gps.getLongitude();
2085 clatitude = latitude;
2086 clongitude =longitude;
2087 Log.d(TAG, "currentlocation: clatitude " + clatitude + "\n" + " clongitude = " + clongitude);
2088
2089
2090 } else {
2091 gps.showSettingsAlert();
2092 }
2093
2094 tampilketerangan();
2095 moveMap();
2096
2097 }
2098
2099 private void tampilketerangan(){
2100
2101 btnGetDirection = (FloatingActionButton) findViewById(R.id.btn_direction);
2102 relative = (RelativeLayout) findViewById(R.id.lay_info);
2103
2104 if (latiaja.equals("") || longiaja.equals("")){
2105 Log.d(TAG, "tampilketerangan: longinya kosong");
2106 Toast.makeText(mContext," Koordinat Customer Tidak Ada",Toast.LENGTH_SHORT).show();
2107 btnGetDirection.setVisibility(View.GONE);
2108 relative.setVisibility(View.GONE);
2109
2110 }else {
2111 btnGetDirection.setVisibility(View.VISIBLE);
2112 relative.setVisibility(View.VISIBLE);
2113 btnGetDirection.setEnabled(false);
2114 }
2115
2116 }
2117
2118 private void moveMap() {
2119 tampilketerangan();
2120 LatLng latLng = new LatLng(clatitude,clongitude);
2121 Log.d(TAG, "moveMap: latLng " + latLng);
2122 //Adding marker to map
2123 MarkerOptions mO = new MarkerOptions();
2124
2125 mO.position(latLng) //setting position
2126 .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
2127 .title("Posisi Saya");
2128 cloc = Nmap.addMarker(mO);
2129 cloc.showInfoWindow();
2130 Nmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
2131 Nmap.animateCamera(CameraUpdateFactory.zoomTo(12));
2132
2133
2134
2135
2136 btnMyLocation.setVisibility(View.GONE);
2137 btnCheckIn.setVisibility(View.VISIBLE);
2138
2139
2140
2141
2142 }
2143
2144 private void CheckInPosition(){
2145
2146 if (latLongString.length() == 0) {
2147 Log.d(TAG, "CheckInPosition: latLongString " + latLongString);
2148 Toast.makeText(mContext, "Location not found, please wait..", Toast.LENGTH_SHORT).show();
2149 handlelocation();
2150 } else {
2151
2152 isMapImageValid = true;
2153 btnCheckIn.setVisibility(View.GONE);
2154// btnGetDirection.setVisibility(View.VISIBLE);
2155// btnGetDirection.setEnabled(true);
2156// RelativeLayout relativ = (RelativeLayout) findViewById(R.id.lay_info);
2157// relativ.setVisibility(View.VISIBLE);
2158// Toast.makeText(mContext,"Tombol Direction Sudah Aktif",Toast.LENGTH_SHORT).show();
2159// btnGetDirection.setOnClickListener(new OnClickListener() {
2160// @Override
2161// public void onClick(View v) {
2162// //Toast.makeText(mContext,"wadw",Toast.LENGTH_SHORT).show();
2163// sendRequest(originText);
2164// }
2165// });
2166 if (addressText.length() > 0) {
2167 Log.d(TAG, "CheckInPosition: addressText " + addressText);
2168 originText = addressText;
2169
2170 Toast.makeText(mContext, "You have check in at : \n" + addressText, Toast.LENGTH_SHORT).show();
2171 } else {
2172 Toast.makeText(mContext, "You have check in at : \n" + latLongString, Toast.LENGTH_SHORT).show();
2173 }
2174 }
2175 }
2176
2177 private void posisicustomer() {
2178 Log.d(TAG, "posisicustomer: "+"Latitudenya adalah : "+ Lat_Customer +" DAN " + " longitudenya adalah : " + Lon_customer);
2179 //Geocoder geocoder = new Geocoder(mContext);
2180 List<Address> addresses;
2181
2182 try {
2183 Geocoder gc = new Geocoder(this, Locale.getDefault());
2184 StringBuilder sb = new StringBuilder();
2185 addresses = gc.getFromLocation(Lat_Customer,Lon_customer,1);
2186 Log.d(TAG, "posisicustomer: addresses " + addresses);
2187
2188 if (addresses.size() > 0) {
2189 Log.d(TAG, "posisicustomer: "+ addresses.size());
2190 Address address = addresses.get(0);
2191 for(int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
2192 Log.d(TAG, "posisicustomer: addressFragments "+ address.getMaxAddressLineIndex());
2193 if (i == 0){
2194 sb.append(address.getAddressLine(i));
2195 }else {
2196 sb.append("," + address.getAddressLine(i));
2197 }
2198 }
2199
2200 if (sb.toString().length() > 1) {
2201 alamat_customer = sb.toString();
2202 Log.d(TAG, "posisicustomer: alamat_customer "+ alamat_customer);
2203 originText = addressText;
2204 Log.d(TAG, "posisicustomer: originText "+ originText);
2205
2206 } else {
2207 addressText = "";
2208 }
2209 }
2210
2211 try{
2212 model_customer.setAlamat(alamat_customer);
2213
2214 }catch (Exception e){
2215 e.printStackTrace();
2216 }
2217 LatLng latlong = new LatLng(Lat_Customer, Lon_customer);
2218
2219 MarkerOptions marker = new MarkerOptions().position(new LatLng(Lat_Customer,Lon_customer));
2220 marker.title(alamat_customer);
2221 marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
2222 Nmap.addMarker(marker);
2223 Nmap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 12));
2224 Nmap.getUiSettings().setMapToolbarEnabled(false);
2225
2226
2227 } catch (IOException e) {
2228 e.printStackTrace();
2229 }
2230
2231
2232
2233 }
2234
2235 private void handlelocation() {
2236
2237 if (locationManager == null) {
2238 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
2239 }
2240
2241 latLongString = "";
2242 Log.d(TAG, "handlelocation: latLongString " + latLongString);
2243 latString = "";
2244 lngString = "";
2245
2246 //exceptions will be thrown if provider is not permitted.
2247 try {
2248 gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
2249 } catch (Exception ex) {
2250 }
2251
2252 try {
2253 network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
2254 } catch (Exception ex) {
2255 }
2256
2257 //don't start listeners if no provider is enabled
2258 if (!gps_enabled && !network_enabled)
2259 return;
2260
2261 if (gps_enabled) {
2262 if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
2263 != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
2264 android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
2265
2266 return;
2267 }
2268 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
2269 } else {
2270 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
2271 }
2272
2273 Toast.makeText(mContext, "Waiting for location..", Toast.LENGTH_LONG).show();
2274 }
2275
2276 LocationListener locationListenerGps = new LocationListener() {
2277 @Override
2278 public void onLocationChanged(Location location) {
2279 updateWithNewLocation(location);
2280 //sendRequest();
2281 if (ActivityCompat.checkSelfPermission(getApplicationContext(),
2282 android.Manifest.permission.ACCESS_FINE_LOCATION) !=
2283 PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
2284 (getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
2285 PackageManager.PERMISSION_GRANTED) {
2286 }
2287 locationManager.removeUpdates(this);
2288 locationManager.removeUpdates(locationListenerNetwork);
2289 }
2290
2291 @Override
2292 public void onProviderDisabled(String provider) {
2293 Toast.makeText(mContext, "Provider disabled, GPS turned off", Toast.LENGTH_SHORT).show();
2294 }
2295
2296 @Override
2297 public void onProviderEnabled(String provider) {
2298 Toast.makeText(mContext, "Provider enabled, GPS turned on", Toast.LENGTH_SHORT).show();
2299 }
2300
2301 @Override
2302 public void onStatusChanged(String provider, int status, Bundle extras) {
2303 Toast.makeText(mContext, "Provider status changed", Toast.LENGTH_SHORT).show();
2304 }
2305 };
2306
2307 LocationListener locationListenerNetwork = new LocationListener() {
2308 @Override
2309 public void onLocationChanged(Location location) {
2310 updateWithNewLocation(location);
2311 //sendRequest();
2312 if (ActivityCompat.checkSelfPermission(getApplicationContext(),
2313 android.Manifest.permission.ACCESS_FINE_LOCATION) !=
2314 PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(),
2315 android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
2316 return;
2317 }
2318 locationManager.removeUpdates(this);
2319 locationManager.removeUpdates(locationListenerGps);
2320 }
2321
2322 @Override
2323 public void onProviderDisabled(String provider) {
2324 Toast.makeText(mContext, "Provider disabled, GPS turned off", Toast.LENGTH_SHORT).show();
2325 }
2326
2327 @Override
2328 public void onProviderEnabled(String provider) {
2329 Toast.makeText(mContext, "Provider enabled, GPS turned on", Toast.LENGTH_SHORT).show();
2330 }
2331
2332 @Override
2333 public void onStatusChanged(String provider, int status, Bundle extras) {
2334 Toast.makeText(mContext, "Provider status changed", Toast.LENGTH_SHORT).show();
2335 }
2336 };
2337
2338 private void updateWithNewLocation(Location newLocation) {
2339
2340 double latitude = newLocation.getLatitude();
2341 double longtitude = newLocation.getLongitude();
2342
2343 latLongString = "Latitude : " + latitude + ", Longtitude : " + longtitude;
2344 latString = Double.toString(latitude);
2345 lngString = Double.toString(longtitude);
2346 List<Address> addresses;
2347
2348 try {
2349 Geocoder gc = new Geocoder(this, Locale.getDefault());
2350 StringBuilder sb = new StringBuilder();
2351 addresses = gc.getFromLocation(latitude, longtitude, 1);
2352 Log.d(TAG, "updateWithNewLocation: addresses " + addresses);
2353 if (addresses.size() > 0) {
2354 Log.d(TAG, "updateWithNewLocation: "+ addresses.size());
2355 Address address = addresses.get(0);
2356 ArrayList<String> addressFragments = new ArrayList<String>();
2357
2358
2359 for(int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
2360 //addressFragments.add(address.getAddressLine(i));
2361 Log.d(TAG, "updateWithNewLocation: addressFragments "+ address.getMaxAddressLineIndex());
2362 if (i == 0){
2363 sb.append(address.getAddressLine(i));
2364 }else {
2365 sb.append("," + address.getAddressLine(i));
2366 }
2367 }
2368
2369 if (sb.toString().length() > 1) {
2370 addressText = sb.toString();
2371 Log.d(TAG, "updateWithNewLocation: addressText "+ addressText);
2372 originText = addressText;
2373
2374 } else {
2375 addressText = "";
2376
2377 }
2378
2379 String longicuy = longiaja + latiaja;
2380
2381 if (longicuy.equals("")){
2382 btnGetDirection.setVisibility(View.GONE);
2383 Toast.makeText(mContext,"Tombol Direction Tidak Aktif",Toast.LENGTH_SHORT).show();
2384 }else {
2385 btnGetDirection.setEnabled(true);
2386 Toast.makeText(mContext,"Tombol Direction Sudah Aktif",Toast.LENGTH_SHORT).show();
2387 }
2388
2389 btnGetDirection.setOnClickListener(new OnClickListener() {
2390 @Override
2391 public void onClick(View v) {
2392 posisicustomer();
2393 sendRequest(originText);
2394 Log.d(TAG, "onClick: "+originText);
2395 }
2396 });
2397
2398 }
2399
2400 } catch (IOException e) {
2401 e.printStackTrace();
2402 }
2403
2404 Nmap.clear();
2405 MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longtitude));
2406 marker.title(addressText);
2407 Log.d(TAG, "updateWithNewLocation: marker.title(addressText) " + addressText);
2408 marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
2409 Nmap.addMarker(marker).showInfoWindow();
2410
2411
2412
2413 }
2414
2415 private void sendRequest(String origin2) {
2416 String origin = origin2;
2417 Log.d(TAG, "sendRequest: "+origin);
2418 String destination = alamat_customer+kota+state+negara;
2419 //String destination = alamat_customer;
2420 Log.d(TAG, "sendRequest: alamat_customer "+ alamat_customer);
2421
2422 if (origin ==null && destination ==null){
2423 progressDialog.dismiss();
2424 } else {
2425 try {
2426 new DirectionFinder(this, origin, destination).execute();
2427 } catch (UnsupportedEncodingException e) {
2428 e.printStackTrace();
2429 }
2430 }
2431
2432
2433 }
2434
2435 @Override
2436 public void onDirectionFinderStart() {
2437 progressDialog = ProgressDialog.show(this, "Please wait.",
2438 "Finding direction..!", true);
2439
2440 if (polylinePaths != null) {
2441 for (Polyline polyline:polylinePaths ) {
2442 polyline.remove();
2443 }
2444 }
2445 }
2446
2447 @Override
2448 public void onDirectionFinderSearch() {
2449
2450 }
2451
2452 @Override
2453 public void onDirectionFinderSuccess(List<Route> routes) {
2454 progressDialog.dismiss();
2455 polylinePaths = new ArrayList<>();
2456 //originMarkers = new ArrayList<>();
2457 //destinationMarkers = new ArrayList<>();
2458
2459 for (Route route : routes) {
2460 Nmap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 16));
2461
2462
2463 ((TextView) findViewById(R.id.text_durasi)).setText("( " + route.duration.text +" )");
2464 ((TextView) findViewById(R.id.text_jarak)).setText(route.distance.text);
2465 ((TextView) findViewById(R.id.text_start)).setText("Melalui : "+route.startAddress);
2466
2467
2468 PolylineOptions polylineOptions = new PolylineOptions().
2469 geodesic(true).
2470 color(Color.BLUE).
2471 width(7);
2472
2473 for (int i = 0; i < route.points.size(); i++)
2474 polylineOptions.add(route.points.get(i));
2475
2476 polylinePaths.add(Nmap.addPolyline(polylineOptions));
2477 }
2478 }
2479
2480
2481 private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
2482 String strAdd = "";
2483 Geocoder geocoder = new Geocoder(this, Locale.getDefault());
2484 try {
2485 List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
2486 if (addresses != null) {
2487 Address returnedAddress = addresses.get(0);
2488 StringBuilder strReturnedAddress = new StringBuilder("");
2489
2490 for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
2491 strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
2492 }
2493 strAdd = strReturnedAddress.toString();
2494 addressText = strAdd;
2495 originText = addressText;
2496 Log.d(TAG, "getCompleteAddressString: strAdd "+ strAdd);
2497 Log.d(TAG, "getCompleteAddressString: strReturnedAddress.toString() "+ strReturnedAddress.toString());
2498 } else {
2499 Log.d(TAG, "getCompleteAddressString: My Current loction address ,No Address returned!");
2500 }
2501 } catch (Exception e) {
2502 e.printStackTrace();
2503 Log.d(TAG, "getCompleteAddressString: My Current loction address ,Canont get Address!");
2504
2505 }
2506 return strAdd;
2507 }
2508
2509 ///------BAGIAN UNTUK TAB MAP ( PETA ) -----------///////
2510
2511
2512
2513 private boolean isNumeric(String str) {
2514 try {
2515 double d = Double.parseDouble(str);
2516 System.out.println(d);
2517 } catch (NumberFormatException nfe) {
2518 return false;
2519 }
2520 return true;
2521 }
2522
2523 private void buildLocationAlert() {
2524 Intent myintent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
2525 mContext.startActivity(myintent);
2526 Toast.makeText(mContext, "Please turn on location service", Toast.LENGTH_LONG).show();
2527 }
2528
2529 private void buildAlertSave() {
2530 int i;
2531 NumberFormat formatter = new DecimalFormat("###,###,###");
2532
2533 for (i = 0; i < theForm.fields.size(); i++) {
2534 fieldValue = (String) theForm.fields.elementAt(i).getData();
2535 Log.d(TAG, "buildAlertSave: fieldValue "+fieldValue);
2536
2537
2538 if (fieldValue.trim().length() > 0) {
2539 //total = total + Double.valueOf(fieldValue); //yg lama
2540 total = total + Double.parseDouble(fieldValue); //editandwi
2541 Log.d(TAG, "buildAlertSave: total " +total);
2542 }
2543 }
2544 strTotal = formatter.format(total);
2545
2546 Log.d(TAG, "buildAlertSave: strTotal "+ strTotal);
2547
2548 if (result_submit.equals("Gagal")){
2549 temp_jumlah = strTotal;
2550 Log.d(TAG, "buildAlertSave: temp_jumlah " + temp_jumlah);
2551 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
2552 builder.setIcon(android.R.drawable.ic_dialog_info);
2553 builder.setTitle("Confirmation");
2554 builder.setMessage("Total amount to be received is : \n" + "Rp " + temp_jumlah.replace(",", ".") + " are you sure ?")
2555 .setCancelable(false).setPositiveButton("Yes",
2556 new DialogInterface.OnClickListener() {
2557 public void onClick(final DialogInterface dialog, final int id) {
2558 if (getValue().equals("EDC")) {
2559 new PrintReceiptEDC().execute();
2560 } else {
2561 new SubmitkeServer().execute();
2562 }
2563
2564 }
2565 })
2566 .setNegativeButton("No", new DialogInterface.OnClickListener() {
2567 public void onClick(final DialogInterface dialog, final int id) {
2568 total = 0.0;
2569 Log.d(TAG, "onClick: "+total);
2570 dialog.cancel();
2571
2572 return;
2573 }
2574 });
2575 final AlertDialog alert = builder.create();
2576 alert.show();
2577 }else {
2578 Log.d(TAG, "buildAlertSave: else strTotal " + strTotal);
2579 final AlertDialog.Builder builder = new AlertDialog.Builder(this);
2580 builder.setIcon(android.R.drawable.ic_dialog_info);
2581 builder.setTitle("Confirmation");
2582 builder.setMessage("Total amount to be received is : \n" + "Rp " + strTotal.replace(",", ".") + " are you sure ?")
2583 .setCancelable(false).setPositiveButton("Yes",
2584 new DialogInterface.OnClickListener() {
2585 public void onClick(final DialogInterface dialog, final int id) {
2586 if (getValue().equals("EDC")) {
2587 new PrintReceiptEDC().execute();
2588 } else {
2589 new SubmitkeServer().execute();
2590 }
2591
2592 }
2593 })
2594 .setNegativeButton("No", new DialogInterface.OnClickListener() {
2595 public void onClick(final DialogInterface dialog, final int id) {
2596 total = 0.0;
2597 Log.d(TAG, "onClick: "+total);
2598 dialog.cancel();
2599 return;
2600 }
2601 });
2602 final AlertDialog alert = builder.create();
2603 alert.show();
2604 }
2605 }
2606
2607
2608
2609 private void ceklatlongcustomer(){
2610 if (latiaja.equals("") || longiaja.equals("")){
2611 Toast.makeText(mContext,"latitudenya dan longitudenya Customer tidak ada",Toast.LENGTH_LONG).show();
2612 Log.d(TAG, "onCreate: cek longi "+ longiaja + latiaja);
2613 }
2614
2615 }
2616
2617
2618 ///--------------------SUBMIT KE SERVER--------------------\\
2619 private class SubmitkeServer extends AsyncTask<String, Void, String> {
2620 String SOAP_ACTION = "http://layanan.mobilefin/simpanhasil3";
2621 String NAMESPACE = "http://layanan.mobilefin/";
2622 String METHOD_NAME = "simpanhasil3";
2623 String URLsumbitkeserver= getString(R.string.urlmtf);
2624 String outputresult;
2625 String custtype="";
2626 //ContentValues cv = new ContentValues();
2627 String[] data = theForm.getEncodedData();
2628
2629 String tanggal_bayar = searchText.getText().toString();
2630
2631 @Override
2632 protected void onPreExecute() {
2633 dialog.show();
2634 }
2635
2636 @Override
2637 protected String doInBackground(String... params) {
2638
2639 try {
2640 db = datasource.getWritableDatabase();
2641 int cnt = 0;
2642 String image_str = null;
2643 String image_lat_str = null;
2644 String image_lng_str = null;
2645
2646
2647 Calendar cl = Calendar.getInstance();
2648 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
2649 SimpleDateFormat df22 = new SimpleDateFormat("dd-MM-yyyy");
2650 String myTime = df.format(cl.getTime());
2651 String tgl2 = df22.format(cl.getTime());
2652
2653
2654 prefsEditor.putString("lastransaction", String.valueOf(myTime)).commit();
2655 lasttransaction = myTime;
2656 //tanggalbayar = tanggal_bayar;
2657 String theKey = datalocal.encrypt(myTime, getString(R.string.Key));
2658 Log.d(TAG, "doInBackground: theKey1 "+theKey);
2659
2660 Cursor c = db.rawQuery("SELECT imageStr, lat, lng FROM " + tableImageCollection, null);
2661 try {
2662 while (c.moveToNext()) {
2663 cnt++;
2664 if (image_str == null) {
2665 image_str = (c.getString(0));
2666 image_lat_str = c.getString(1);
2667 image_lng_str = c.getString(2);
2668 //Log.d(TAG, "doInBackground: "+image_lat_str+image_lng_str);
2669 } else {
2670 image_str = image_str + "split" + (c.getString(0));
2671 image_lat_str = image_lat_str + ";" + c.getString(1);
2672 image_lng_str = image_lng_str + ";" + c.getString(2);
2673 //Log.d(TAG, "doInBackground: "+image_lat_str+image_lng_str);
2674 }
2675 }
2676 } finally {
2677 c.close();
2678 }
2679
2680
2681 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
2682 Log.d(TAG, "doInBackground: request "+request.toString());
2683 ///proses submit ke server
2684 request.addProperty("a",data[0]
2685 + "duedate;taskdate;installmentno;paidby");
2686 request.addProperty("b",data[1]
2687 + "'" + dueDate + "';'" + taskDate + "';'" + insNo + "';'" + getValue().trim() + "'");
2688 request.addProperty("c",image_str);
2689 request.addProperty("d",String.valueOf(cnt));
2690 request.addProperty("e",moduleid);
2691 request.addProperty("f",contractNo);
2692 request.addProperty("g",latString);
2693 request.addProperty("h",lngString);
2694 request.addProperty("i",myTime);
2695 request.addProperty("j",generalPrefs.getString("userID", null));
2696 request.addProperty("k",image_lat_str);
2697 request.addProperty("l",image_lng_str);
2698 request.addProperty("m",theKey);
2699 request.addProperty("n",custtype);
2700 //tambahan untuk tanggal bayar
2701 request.addProperty("o",tanggal_bayar);
2702
2703
2704
2705 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
2706 envelope.dotNet = true;
2707 envelope.setOutputSoapObject(request);
2708
2709
2710 HttpTransportSE androidHttpTransport = new HttpTransportSE(URLsumbitkeserver,120000);
2711 androidHttpTransport.debug = true;
2712
2713 try {
2714 androidHttpTransport.call(SOAP_ACTION, envelope);
2715
2716 if (envelope.bodyIn instanceof SoapFault) {
2717 outputresult = ((SoapFault) envelope.bodyIn).faultstring;
2718
2719
2720
2721 } else {
2722 SoapObject response = (SoapObject) envelope.bodyIn;
2723 outputresult = response.getProperty(0).toString();
2724
2725
2726 }
2727
2728 }
2729 catch (Exception e) {
2730 outputresult = e.getMessage();
2731
2732
2733 }
2734 System.out.println("outputresult saveresult : SubmitkeServer " + outputresult);
2735
2736
2737 c.close();
2738 System.gc();
2739
2740
2741 } catch (Exception e) {
2742 e.printStackTrace();
2743 CollectionActivity.this.e = e;
2744
2745 }
2746
2747
2748
2749 return null;
2750 }
2751
2752 @Override
2753 protected void onPostExecute(String aVoid) {
2754 super.onPostExecute(aVoid);
2755 Log.d("jstring dapat", "onPostExecute: SubmitkeServer " + aVoid);
2756 Log.d("jstring dapat", "onPostExecute: SubmitkeServer2 " + outputresult);
2757
2758
2759 if (outputresult.equals("Success")){
2760 Log.d(TAG, "onPostExecute: yangkedua" +outputresult);
2761 Toast.makeText(mContext,"Data Berhasil Tersimpan Di Server",Toast.LENGTH_SHORT).show();
2762 if (getValue().equals("EDC")) {
2763 //Savekelocal();
2764 new PrintReceiptEDC().execute();
2765 } else {
2766 Savekelocal();
2767 new doPayCash().execute();
2768 //new PrintReceiptCash().execute();
2769 }
2770
2771 } else{
2772 result_submit = "Gagal";
2773 Log.d(TAG, "onPostExecute: "+result_submit);
2774 //datasource.deleteData(db, "userid = '" + userID + "'", "printcash");
2775 Toast.makeText(mContext,"Data Gagal Terkirim. Harap Diulang !!",Toast.LENGTH_LONG).show();
2776 dialog.dismiss();
2777 }
2778
2779 //dialog.dismiss();
2780 }
2781
2782
2783 }
2784
2785 public class PrintReceiptEDC extends AsyncTask<Void, Void, String> {
2786
2787 String tgl_bayar = searchText.getText().toString();
2788
2789 @Override
2790 protected void onPreExecute() {
2791 dialog.show();
2792 }
2793
2794 @Override
2795 protected String doInBackground(Void... arg0) {
2796 boolean threadDone = false;
2797 StringBuilder receiptPrint = new StringBuilder();
2798 StringBuilder infoEDC = new StringBuilder();
2799 int serverPort = 48200;
2800 int timeout = 300000;
2801 String isTimeOut = "";
2802 String EDCKey = "A142AD52C246 8087";
2803
2804 String now;
2805 String sekarang;
2806 Calendar cl = Calendar.getInstance();
2807 SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
2808 SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
2809 now = df.format(cl.getTime());
2810 sekarang = df2.format(cl.getTime());
2811 lasttransaction = now;
2812 //tanggalbayar2 = sekarang;
2813 tanggalbayar2 = tgl_bayar;
2814 Log.d(TAG, "doInBackground: tgl_bayar " + tgl_bayar);
2815 String strDueDate;
2816
2817 strDueDate = dueDate.substring(6, 8) + "/" + dueDate.substring(4, 6) + "/" + dueDate.substring(0, 4);
2818
2819 receiptPrint.append("2_|C|B|KWITANSI PEMBAYARAN TRANSFER_ _");
2820
2821 receiptPrint.append("C|N|" + branchName + "_");
2822 receiptPrint.append("C|N|" + branchAddress + "_");
2823 receiptPrint.append("C|N|" + branchPhone + "_ _");
2824
2825 receiptPrint.append("L|N|" + String.valueOf(now).trim() + " - " + collInitial + "_ _");
2826
2827 receiptPrint.append("L|N|" + "No : " + receiptNo.trim() + "_");
2828 receiptPrint.append("L|N|" + "Nama : " + custNamePrint + "_");
2829 receiptPrint.append("L|N|" + "No Kontrak : " + contractNo + "_");
2830 receiptPrint.append("L|N|" + "Angsuran ke : " + insNo + "_");
2831 receiptPrint.append("L|N|" + "Tgl Jt Tempo: " + strDueDate + "_");
2832 receiptPrint.append("L|N|" + "No Plat : " + licensePlate.trim() + "_ _");
2833
2834 int i;
2835 String space = "";
2836 String space2 = "";
2837 double total = 0.0;
2838 NumberFormat formatter = new DecimalFormat("###,###,###");
2839
2840 for (i = 0; i < theForm.fields.size(); i++) {
2841 String fieldLabel = (String) theForm.fields.elementAt(i).getDataLabel();
2842 String fieldValue = (String) theForm.fields.elementAt(i).getData();
2843
2844 fieldValue = fieldValue.replace(" ", "").replace(",", "").replace(".00", "");
2845
2846 if (isNumeric(fieldValue) && fieldValue.length() > 2) {
2847 space = new String(new char[(15 - fieldLabel.trim().length())]).replace('\0', ' ');
2848 space2 = new String(new char[(11 - formatter.format(Double.valueOf(fieldValue)).length())]).replace('\0', ' ');
2849
2850 receiptPrint.append("L|N|" + fieldLabel.trim() + space + "Rp" + space2 + formatter.format(Double.valueOf(fieldValue)).replace(",", ".") + "_");
2851
2852 total = total + Double.valueOf(fieldValue);
2853 }
2854 }
2855
2856 space = new String(new char[8]).replace('\0', ' ');
2857 space2 = new String(new char[(11 - formatter.format(total).length())]).replace('\0', ' ');
2858
2859 receiptPrint.append("L|B|" + "Total" + space + "Rp" + space2 + formatter.format(total).replace(",", ".") + "_ _ _");
2860
2861 receiptPrint.append("C|N|" + "Mohon Simpan Kwitansi ini" + "_");
2862 receiptPrint.append("C|N|" + "Sebagai Bukti Pembayaran anda" + "_");
2863 receiptPrint.append("C|N|" + "Terima Kasih" + "_");
2864
2865 String kodeBank = generalPrefs.getString("kodeBank", null) + "FFFFFFFFFFFFFFFF";
2866 String noRek = generalPrefs.getString("noRek", null) + "FFFFFFFFFFFFFFFF";
2867 String noReff = contractNo.replace("AG", "") + insNo + "FFFFFFFFFFFFFFFF";
2868 String amountReceive = String.valueOf(total).replace(".0", "");
2869 StringBuilder amountReceiveClean = new StringBuilder();
2870 int length = amountReceive.length();
2871 int diff = 16 - length;
2872
2873 for (int j = 0; j < diff; j++) {
2874 amountReceiveClean.append("0");
2875 }
2876
2877 amountReceiveClean.append(amountReceive);
2878
2879 infoEDC.append(encryptSingleDES(kodeBank.substring(0, 16), EDCKey) + "_");
2880 infoEDC.append(encryptSingleDES(noRek.substring(0, 16), EDCKey) + "_");
2881 infoEDC.append(encryptSingleDES(amountReceiveClean.toString(), EDCKey) + "_");
2882 infoEDC.append(encryptSingleDES(noReff.substring(0, 16), EDCKey) + "_");
2883 infoEDC.append(receiptPrint.toString());
2884
2885 Log.d(TAG, "doInBackground: cek semua infoEDC = " + infoEDC.toString());
2886 try{
2887 String infoedc = infoEDC.toString();
2888 Log.d(TAG, "doInBackground: infoedc "+infoedc);
2889 prefsEditor.putString("infoedc", String.valueOf(infoedc)).commit();
2890 }catch (Exception e){
2891 e.printStackTrace();
2892 }
2893
2894 try {
2895 serverSocket = new ServerSocket(serverPort);
2896 serverSocket.setSoTimeout(timeout);
2897
2898 while (!threadDone) {
2899 new MultiThread(serverSocket.accept(), infoEDC.toString()).start();
2900 threadDone = true;
2901 }
2902
2903 serverSocket.close();
2904 threadDone = false;
2905
2906 serverSocket = new ServerSocket(serverPort);
2907 serverSocket.setSoTimeout(timeout);
2908
2909 while (!threadDone) {
2910 new MultiThreadReceive(serverSocket.accept()).start();
2911 threadDone = true;
2912 }
2913 serverSocket.close();
2914 } catch (Exception e) {
2915 e.printStackTrace();
2916
2917 try {
2918 serverSocket.close();
2919 } catch (IOException e1) {
2920 e1.printStackTrace();
2921 }
2922
2923 isTimeOut = "Transaction timeout, please try again..";
2924 }
2925
2926 return isTimeOut;
2927 }
2928
2929 @Override
2930 protected void onPostExecute(String sResponse) {
2931 Log.d(TAG, "onPostExecute: printEDC "+sResponse);
2932 boolean ada = true;
2933
2934 if (sResponse.contentEquals("")) {
2935 if (GlobalVariable.getResult() != "")
2936 ada = false;
2937
2938 while (ada) {
2939 if (GlobalVariable.getResult() != "")
2940 ada = false;
2941 }
2942
2943 if (GlobalVariable.getResult().equals("1")) {
2944 GlobalVariable.setResult("");
2945 //tambahin savekelokal untuk ketika re-print ke table yg sama
2946 Savekelocal();
2947 new PostData().execute();
2948 } else {
2949 Toast.makeText(mContext, "Transaction failed, please try again..", Toast.LENGTH_LONG).show();
2950 dialog.dismiss();
2951 GlobalVariable.setResult("");
2952 return;
2953 }
2954
2955 } else {
2956 Toast.makeText(mContext, sResponse, Toast.LENGTH_LONG).show();
2957 dialog.dismiss();
2958
2959 }
2960
2961 }
2962
2963 }
2964
2965 public class PrintReceiptCash extends AsyncTask<Void, Void, String> {
2966
2967 @Override
2968 protected void onPreExecute() {
2969 //dialog.show();
2970 }
2971
2972 @Override
2973 protected String doInBackground(Void... arg0) {
2974 boolean threadDone = false;
2975 StringBuilder receiptPrint = new StringBuilder();
2976 int serverPort = 48200;
2977 //int timeout = 30000;
2978 int timeout = 60000; // 1 menit
2979 String isTimeOut = "";
2980
2981 String now;
2982 Calendar cl = Calendar.getInstance();
2983 SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
2984 now = df.format(cl.getTime());
2985 String strDueDate;
2986
2987 strDueDate = dueDate.substring(6, 8) + "/" + dueDate.substring(4, 6) + "/" + dueDate.substring(0, 4);
2988
2989 receiptPrint.append("2_|C|B|KWITANSI PEMBAYARAN CASH_ _");
2990
2991 receiptPrint.append("C|N|" + branchName + "_");
2992 receiptPrint.append("C|N|" + branchAddress + "_");
2993 receiptPrint.append("C|N|" + branchPhone + "_ _");
2994
2995 receiptPrint.append("L|N|" + String.valueOf(now).trim() + " - " + collInitial + "_ _");
2996
2997 receiptPrint.append("L|N|" + "No : " + receiptNo.trim() + "_");
2998 receiptPrint.append("L|N|" + "Nama : " + custNamePrint + "_");
2999 receiptPrint.append("L|N|" + "No Kontrak : " + contractNo + "_");
3000 receiptPrint.append("L|N|" + "Angsuran ke : " + insNo + "_");
3001 receiptPrint.append("L|N|" + "Tgl Jt Tempo: " + strDueDate + "_");
3002 receiptPrint.append("L|N|" + "No Plat : " + licensePlate.trim() + "_ _");
3003
3004 int i;
3005 String space = "";
3006 String space2 = "";
3007 double total = 0.0;
3008 NumberFormat formatter = new DecimalFormat("###,###,###");
3009
3010 for (i = 0; i < theForm.fields.size(); i++) {
3011 String fieldLabel = (String) theForm.fields.elementAt(i).getDataLabel();
3012 String fieldValue = (String) theForm.fields.elementAt(i).getData();
3013
3014 fieldValue = fieldValue.replace(" ", "").replace(",", "").replace(".00", "");
3015
3016 if (isNumeric(fieldValue) && fieldValue.length() > 2) {
3017 space = new String(new char[(15 - fieldLabel.trim().length())]).replace('\0', ' ');
3018 space2 = new String(new char[(11 - formatter.format(Double.valueOf(fieldValue)).length())]).replace('\0', ' ');
3019
3020 receiptPrint.append("L|N|" + fieldLabel.trim() + space + "Rp" + space2 + formatter.format(Double.valueOf(fieldValue)).replace(",", ".") + "_");
3021
3022 total = total + Double.valueOf(fieldValue);
3023 }
3024 }
3025
3026 space = new String(new char[8]).replace('\0', ' ');
3027 space2 = new String(new char[(11 - formatter.format(total).length())]).replace('\0', ' ');
3028
3029 receiptPrint.append("L|B|" + "Total" + space + "Rp" + space2 + formatter.format(total).replace(",", ".") + "_ _ _");
3030
3031 receiptPrint.append("C|N|" + "Mohon Simpan Kwitansi ini" + "_");
3032 receiptPrint.append("C|N|" + "Sebagai Bukti Pembayaran anda" + "_");
3033 receiptPrint.append("C|N|" + "Terima Kasih" + "_");
3034
3035 Log.d(TAG, "doInBackground: cek semua receiptprintnya = " + receiptPrint.toString());
3036 try{
3037 String coba = receiptPrint.toString();
3038 Log.d(TAG, "doInBackground: PrintReceiptCash "+coba);
3039 prefsEditor.putString("prinan", String.valueOf(coba)).commit();
3040 }catch (Exception e){
3041 e.printStackTrace();
3042 }
3043
3044 try {
3045 serverSocket = new ServerSocket(serverPort);
3046 serverSocket.setSoTimeout(timeout);
3047
3048 while (!threadDone) {
3049 new MultiThread(serverSocket.accept(), receiptPrint.toString()).start();
3050 threadDone = true;
3051 }
3052
3053 serverSocket.close();
3054 } catch (Exception e) {
3055 e.printStackTrace();
3056 try {
3057 serverSocket.close();
3058 } catch (IOException e1) {
3059 e1.printStackTrace();
3060 }
3061
3062 isTimeOut = "Print Receipt Timeout";
3063 }
3064
3065 return isTimeOut;
3066 }
3067
3068 @Override
3069 protected void onPostExecute(String sResponse) {
3070 Log.d(TAG, "onPostExecute: 123"+sResponse);
3071
3072 if (sResponse.contentEquals("")) {
3073 Log.d(TAG, "onPostExecute: sResponse "+sResponse);
3074 hapusfoto();
3075 finish();
3076 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3077 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3078 intent.putExtra("flagUpdate", "U");
3079 startActivity(intent);
3080 Toast.makeText(mContext, "Data has been Print", Toast.LENGTH_LONG).show();
3081 //new PostData().execute();
3082 } else {
3083 Toast.makeText(mContext, sResponse, Toast.LENGTH_LONG).show();
3084 Toast.makeText(mContext, "Anda harus melakukan Re-Print !!", Toast.LENGTH_LONG).show();
3085 try{
3086 ContentValues cv = new ContentValues();
3087 cv.put("status", sResponse);
3088 prefsEditor.putString("status", sResponse).commit();
3089 //datasource.updateData(db,cv,tableName," userid = '" + userID + "'");
3090 datasource.updateData(db,cv,tableName," userid = '" + userID + "' and paidBy = '"+ paidBy + "'");
3091 cv.clear();
3092 }catch (Exception e){
3093 e.printStackTrace();
3094 }
3095 finish();
3096 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3097 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3098 intent.putExtra("flagUpdate", "U");
3099 startActivity(intent);
3100 dialog.dismiss();
3101 }
3102
3103 }
3104
3105 }
3106
3107 private void Savekelocal(){
3108 db = datasource.getWritableDatabase();
3109 ContentValues cv = new ContentValues();
3110 String[] data = theForm.getEncodedData();
3111
3112 datasource.deleteData(db, "userid = '" + userID + "'", "printcash");
3113 try{
3114 cv.put("fieldname", data[0]);
3115 cv.put("fieldvalue", data[1]);
3116 cv.put("moduleid", moduleid);
3117 cv.put("key", contractNo);
3118 cv.put("userid", userID);
3119 cv.put("lasttransaction",lasttransaction);
3120 cv.put("receiptNo",receiptNo);
3121 cv.put("insNo",insNo);
3122 cv.put("dueDate",dueDate);
3123 cv.put("custNamePrint",custNamePrint);
3124 cv.put("collInitial",collInitial);
3125 cv.put("licensePlate",licensePlate);
3126 cv.put("status", "");
3127 cv.put("strTotal", strTotal);
3128 cv.put("paidBy", getValue().trim());
3129 cv.put("counter", 0);
3130 //cv.put("paiddate",tanggalbayar);
3131 cv.put("paiddate",searchText.getText().toString());
3132
3133 datasource.generateData(db, cv, "printcash");
3134
3135 cv.clear();
3136
3137 datasource.deleteData(db, "contractno = '" + contractNo + "'", "collectionlist");
3138 datasource.deleteData(db, "moduleid = '" + moduleid + "' and idx = '" + contractNo + "'", "infodetail");
3139
3140 Log.d(TAG, "Savekelocal: "
3141 +"\n"+ "module idnya : " + moduleid
3142 +"\n"+ "user idnya : " + generalPrefs.getString("userID", null)
3143 +"\n"+ "no kontraknya : " + contractNo
3144 +"\n"+ " userid : " + userID
3145 +"\n"+ " moduleid : " + moduleid
3146 +"\n"+ " strTotal : " + strTotal
3147 +"\n"+ " receiptNo : " + receiptNo
3148 +"\n"+ " insNo : " + insNo
3149 +"\n"+ " dueDate : " + dueDate
3150 +"\n"+ " licensePlate : " + licensePlate
3151 +"\n"+ " custNamePrint : " + custNamePrint
3152 +"\n"+ " lasttransaction : " + lasttransaction
3153 +"\n"+ " collInitial : " + collInitial
3154 +"\n"+ "fieldname yg di edit dwi : " + data[0]
3155 +"\n"+ "fieldvalue yg di edit dwi : " + data[1]
3156 +"\n"+ "paidBy : " + getValue().trim()
3157 +"\n"+ "counter :"+0
3158 +"\n"+ "tanggalBayar :"+ searchText.getText().toString() );
3159
3160 }catch (Exception e){
3161 e.printStackTrace();
3162 }finally {
3163 db.close();
3164 }
3165 }
3166
3167 public class doPayCash extends AsyncTask<Void, Void, String> {
3168
3169 @Override
3170 protected void onPreExecute() {
3171
3172 }
3173
3174 @Override
3175 protected String doInBackground(Void... arg0) {
3176 String isTimeOut = "";
3177 String now;
3178 Calendar cl = Calendar.getInstance();
3179 SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
3180 now = df.format(cl.getTime());
3181 String strDueDate;
3182 strDueDate = dueDate.substring(6, 8) + "/" + dueDate.substring(4, 6) + "/" + dueDate.substring(0, 4);
3183 Log.d(TAG, "doInBackground: strDueDate " + strDueDate);
3184
3185 int i;
3186 String space = "";
3187 String space2 = "";
3188 double total = 0.0;
3189 NumberFormat formatter = new DecimalFormat("###,###,###");
3190
3191 for (i = 0; i < theForm.fields.size(); i++) {
3192 String fieldLabel = (String) theForm.fields.elementAt(i).getDataLabel();
3193 String fieldValue = (String) theForm.fields.elementAt(i).getData();
3194
3195 fieldValue = fieldValue.replace(" ", "").replace(",", "").replace(".00", "");
3196
3197 if (isNumeric(fieldValue) && fieldValue.length() > 2) {
3198 space = new String(new char[(15 - fieldLabel.trim().length())]).replace('\0', ' ');
3199 space2 = new String(new char[(11 - formatter.format(Double.valueOf(fieldValue)).length())]).replace('\0', ' ');
3200
3201 strtotal2 = fieldLabel.trim() + space + "Rp" + space2 + formatter.format(Double.valueOf(fieldValue)).replace(",", ".");
3202 Log.d(TAG, "doInBackground: strtotal2 " + strtotal2);
3203
3204 total = total + Double.valueOf(fieldValue);
3205 }
3206 }
3207
3208 space = new String(new char[8]).replace('\0', ' ');
3209 space2 = new String(new char[(11 - formatter.format(total).length())]).replace('\0', ' ');
3210
3211 String totalbaru = "Total" + space + "Rp" + space2 + formatter.format(total).replace(",", ".");
3212 Log.d(TAG, "doInBackground: totalbaru " + totalbaru);
3213
3214
3215 ArrayList<CLPrintObject> freeText = new ArrayList<>();
3216 CLPrintObject clPrintObject = new CLPrintObject();
3217 clPrintObject.setFreeText("KWITANSI PEMBAYARAN CASH");
3218 clPrintObject.setFormat(CLPrintEnum.TITLE);
3219 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3220 freeText.add(clPrintObject);
3221 clPrintObject = new CLPrintObject();
3222 clPrintObject.setFreeText(branchName);
3223 clPrintObject.setFormat(CLPrintEnum.BOLD);
3224 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3225 freeText.add(clPrintObject);
3226 clPrintObject = new CLPrintObject();
3227 clPrintObject.setFreeText(branchAddress);
3228 clPrintObject.setFormat(CLPrintEnum.BOLD);
3229 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3230 freeText.add(clPrintObject);
3231 clPrintObject = new CLPrintObject();
3232 clPrintObject.setFreeText(branchPhone);
3233 clPrintObject.setFormat(CLPrintEnum.BOLD);
3234 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3235 freeText.add(clPrintObject);
3236
3237
3238 clPrintObject = new CLPrintObject();
3239 clPrintObject.setFreeText(String.valueOf(now).trim() + " - " + collInitial);
3240 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3241 freeText.add(clPrintObject);
3242 clPrintObject = new CLPrintObject();
3243 clPrintObject.setFreeText("No : " + receiptNo.trim());
3244 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3245 freeText.add(clPrintObject);
3246 clPrintObject = new CLPrintObject();
3247 clPrintObject.setFreeText("Nama : " + custNamePrint);
3248 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3249 freeText.add(clPrintObject);
3250 clPrintObject = new CLPrintObject();
3251 clPrintObject.setFreeText("No Kontrak : " + contractNo);
3252 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3253 freeText.add(clPrintObject);
3254 clPrintObject = new CLPrintObject();
3255 clPrintObject.setFreeText("Angsuran ke : " + insNo);
3256 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3257 freeText.add(clPrintObject);
3258 clPrintObject = new CLPrintObject();
3259 clPrintObject.setFreeText("Tgl Jt Tempo: " + strDueDate);
3260 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3261 freeText.add(clPrintObject);
3262 clPrintObject = new CLPrintObject();
3263 clPrintObject.setFreeText("No Plat : " + licensePlate.trim());
3264 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3265 freeText.add(clPrintObject);
3266 clPrintObject = new CLPrintObject();
3267 clPrintObject.setFreeText(strtotal2);
3268 clPrintObject.setFormat(CLPrintEnum.BOLD);
3269 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3270 freeText.add(clPrintObject);
3271 clPrintObject = new CLPrintObject();
3272 clPrintObject.setFreeText(totalbaru);
3273 clPrintObject.setFormat(CLPrintEnum.BOLD);
3274 clPrintObject.setAlign(CLPrintAlignEnum.LEFT);
3275 freeText.add(clPrintObject);
3276 clPrintObject = new CLPrintObject();
3277 clPrintObject.setFreeText("Mohon Simpan Kwitansi ini");
3278 clPrintObject.setFormat(CLPrintEnum.BOLD);
3279 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3280 freeText.add(clPrintObject);
3281 clPrintObject = new CLPrintObject();
3282 clPrintObject.setFreeText("Sebagai Bukti Pembayaran anda");
3283 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3284 freeText.add(clPrintObject);
3285 clPrintObject = new CLPrintObject();
3286 clPrintObject.setFreeText("Terima Kasih");
3287 clPrintObject.setAlign(CLPrintAlignEnum.CENTER);
3288 freeText.add(clPrintObject);
3289 Log.d(TAG, "doInBackground:freeText "+ freeText.toString());
3290 paymentHandler.doPrintFreeText(freeText);
3291
3292// try {
3293// CLPayment cashCLPayment = new CLPayment();
3294// cashCLPayment.setAmount(totalbaru);
3295// cashCLPayment.setDescription(custNamePrint);
3296// cashCLPayment.setTransactionType(TransactionType.CASH);
3297// paymentHandler.doProceedPayment(cashCLPayment);
3298//
3299// }catch (Exception e){
3300// e.printStackTrace()
3301// }
3302
3303 isTimeOut = "";
3304
3305 return isTimeOut;
3306 }
3307
3308 @Override
3309 protected void onPostExecute(String sResponse) {
3310 Log.d(TAG, "onPostExecute: 123"+sResponse);
3311
3312 if (sResponse.contentEquals("")) {
3313 Log.d(TAG, "onPostExecute: sResponse "+sResponse);
3314 hapusfoto();
3315 finish();
3316 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3317 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3318 intent.putExtra("flagUpdate", "U");
3319 startActivity(intent);
3320 Toast.makeText(mContext, "Data has been Print", Toast.LENGTH_LONG).show();
3321 //new PostData().execute();
3322 } else {
3323 Toast.makeText(mContext, sResponse, Toast.LENGTH_SHORT).show();
3324 Toast.makeText(mContext, "Anda harus melakukan Re-Print !!", Toast.LENGTH_LONG).show();
3325 try{
3326 ContentValues cv = new ContentValues();
3327 cv.put("status", sResponse);
3328 prefsEditor.putString("status", sResponse).commit();
3329 //datasource.updateData(db,cv,tableName," userid = '" + userID + "'");
3330 datasource.updateData(db,cv,tableName," userid = '" + userID + "' and paidBy = '"+ paidBy + "'");
3331 cv.clear();
3332 }catch (Exception e){
3333 e.printStackTrace();
3334 }
3335 finish();
3336 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3337 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3338 intent.putExtra("flagUpdate", "U");
3339 startActivity(intent);
3340 dialog.dismiss();
3341 }
3342
3343
3344 }
3345
3346 }
3347
3348
3349
3350
3351
3352 private void hapusprintcash(){
3353 try{
3354 db = datasource.getWritableDatabase();
3355 datasource.deleteData(db, "userid = '" + userID + "'", "printcash");// bisa
3356 }catch (Exception e){
3357 e.printStackTrace();
3358 }finally {
3359 db.close();
3360 }
3361
3362 }
3363
3364 private class PostData extends AsyncTask<Void, Void, String> {
3365 @Override
3366 protected void onPreExecute() {
3367
3368 }
3369
3370 @Override
3371 protected String doInBackground(Void... params) {
3372 try {
3373 db = datasource.getWritableDatabase();
3374
3375 ///tambahan buat save picture ke sqlite dan server
3376 int cnt = 0;
3377 String image_str = null;
3378 String image_lat_str = null;
3379 String image_lng_str = null;
3380
3381 String[] data = theForm.getEncodedData();
3382 ContentValues cv = new ContentValues();
3383
3384
3385 //tambahan unutk save picture.
3386 Cursor c = db.rawQuery("SELECT imageStr, lat, lng FROM " + tableImageCollection, null);
3387 Log.d(TAG, "doInBackground: "+ db.rawQuery("SELECT imageStr, lat, lng FROM " + tableImageCollection, null));
3388 try {
3389 while (c.moveToNext()) {
3390 cnt++;
3391 if (image_str == null) {
3392 image_str = (c.getString(0));
3393 image_lat_str = c.getString(1);
3394 image_lng_str = c.getString(2);
3395 Log.d(TAG, "doInBackground: "+image_lat_str+image_lng_str);
3396 } else {
3397 image_str = image_str + "split" + (c.getString(0));
3398 image_lat_str = image_lat_str + ";" + c.getString(1);
3399 image_lng_str = image_lng_str + ";" + c.getString(2);
3400 Log.d(TAG, "doInBackground: "+image_lat_str+image_lng_str);
3401 }
3402 }
3403 } finally {
3404 c.close();
3405 }
3406 Calendar cl = Calendar.getInstance();
3407 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3408 String myTime = df.format(cl.getTime());
3409
3410
3411 cv.put("fieldname", data[0]
3412 + "duedate;taskdate;installmentno;paidby");
3413 cv.put("fieldvalue", data[1]
3414 + "'" + dueDate + "';'" + taskDate + "';'" + insNo + "';'" + getValue().trim() + "'");
3415 //cv.put("imagestr", "");
3416 cv.put("imagestr", image_str);
3417 //cv.put("imagecount", "0");
3418 cv.put("imagecount", String.valueOf(cnt));//tambahan
3419 cv.put("moduleid", moduleid);
3420 cv.put("key", contractNo);
3421 cv.put("lat", latString);
3422 cv.put("lng", lngString);
3423 cv.put("dtmupd", myTime);
3424 cv.put("userid", generalPrefs.getString("userID", null));
3425 cv.put("imagelat", image_lat_str);
3426 cv.put("imagelng", image_lng_str);
3427 cv.put("custtype", "");
3428 cv.put("paiddate",tanggalbayar2);
3429
3430
3431 Log.d(TAG, "doInBackground: "+image_str + image_lat_str + image_lng_str);
3432 Log.d(TAG, "doInBackground: "
3433 +"module idnya : " + moduleid
3434 +"user idnya : " + generalPrefs.getString("userID", null)
3435 +"dtmupd idnya : " + myTime
3436 +"tanggalbayar2 : " + tanggalbayar2
3437 +"no kontraknya : " + contractNo
3438 +"imagecount : " + String.valueOf(cnt)
3439 +"fieldname : " + data[0]+ "duedate;taskdate;installmentno;paidby"
3440 +"fieldvalue : " + data[1] + "'" + dueDate + "';'" + taskDate + "';'" + insNo + "';'" + getValue().trim() + "'"
3441
3442 );
3443 datasource.generateData(db, cv, "result");
3444
3445 cv.clear();
3446
3447 datasource.deleteData(db, "contractno = '" + contractNo + "'", "collectionlist");
3448 datasource.deleteData(db, "moduleid = '" + moduleid + "' and idx = '" + contractNo + "'", "infodetail");
3449
3450 System.gc();
3451
3452 } catch (Exception e) {
3453 e.printStackTrace();
3454 CollectionActivity.this.e = e;
3455 } finally {
3456 db.close();
3457 }
3458 return "";
3459 }
3460
3461 @Override
3462 protected void onPostExecute(String sResponse) {
3463 if (e == null) {
3464 finish();
3465 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3466 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3467 intent.putExtra("flagUpdate", "N");
3468 startActivity(intent);
3469
3470 dialog.dismiss();
3471 Toast.makeText(mContext, "Data has been saved", Toast.LENGTH_LONG).show();
3472 } else {
3473 Toast.makeText(mContext, "Connection time out", Toast.LENGTH_SHORT).show();
3474 e = null;
3475 dialog.dismiss();
3476 }
3477 }
3478 }
3479
3480 private class PostData2 extends AsyncTask<Void, Void, String> {
3481 @Override
3482 protected void onPreExecute() {
3483 dialog.show();
3484 }
3485
3486 @Override
3487 protected String doInBackground(Void... params) {
3488 try {
3489
3490 db = datasource.getWritableDatabase();
3491
3492
3493 ///tambahan buat save picture ke sqlite dan server
3494 int cnt = 0;
3495 String image_str = null;
3496 String image_lat_str = null;
3497 String image_lng_str = null;
3498
3499 String[] data = theForm.getEncodedData();
3500 ContentValues cv = new ContentValues();
3501
3502 Cursor c = db.rawQuery("SELECT imageStr, lat, lng FROM " + tableImageCollection, null);
3503 Log.d(TAG, "doInBackground: "+ db.rawQuery("SELECT imageStr, lat, lng FROM " + tableImageCollection, null));
3504 try {
3505 while (c.moveToNext()) {
3506 cnt++;
3507 if (image_str == null) {
3508 image_str = (c.getString(0));
3509 image_lat_str = c.getString(1);
3510 image_lng_str = c.getString(2);
3511 Log.d(TAG, "doInBackground: "+image_lat_str+image_lng_str);
3512 } else {
3513 image_str = image_str + "split" + (c.getString(0));
3514 image_lat_str = image_lat_str + ";" + c.getString(1);
3515 image_lng_str = image_lng_str + ";" + c.getString(2);
3516 Log.d(TAG, "doInBackground: "+image_lat_str+image_lng_str);
3517 }
3518 }
3519 } finally {
3520 c.close();
3521 }
3522
3523 Calendar cl = Calendar.getInstance();
3524 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3525 String myTime = df.format(cl.getTime());
3526
3527 cv.put("fieldname", data[0]
3528 + "duedate;taskdate;installmentno");
3529 cv.put("fieldvalue", data[1]
3530 + "'" + dueDate + "';'" + taskDate + "';'" + insNo + "'");
3531 cv.put("imagestr", image_str);
3532 //cv.put("imagecount", 0);
3533 cv.put("imagecount", String.valueOf(cnt));//tambahan
3534 cv.put("moduleid", moduleid);
3535 cv.put("key", contractNo);
3536 cv.put("lat", latString);
3537 cv.put("lng", lngString);
3538 cv.put("dtmupd", myTime);
3539 cv.put("userid", generalPrefs.getString("userID", null));
3540 cv.put("imagelat", image_lat_str);
3541 cv.put("imagelng", image_lng_str);
3542 cv.put("custtype", "");
3543 cv.put("paiddate", "");
3544
3545 Log.d(TAG, "doInBackground: post data2"+image_lat_str+image_lng_str);
3546 Log.d(TAG, "doInBackground: postdata2"+image_str);
3547 Log.d(TAG, "doInBackground: "
3548 +"module idnya : " + moduleid
3549 +"user idnya : " + generalPrefs.getString("userID", null)
3550 +"dtmupd idnya : " + myTime
3551 +"no kontraknya : " + contractNo
3552 +"imagecount : " + String.valueOf(cnt)
3553 +"fieldname : " + data[0]+ "duedate;taskdate;installmentno"
3554 +"fieldvalue : " + data[1] + "'" + dueDate + "';'" + taskDate + "';'" + insNo + "'"
3555
3556 );
3557
3558 datasource.generateData(db, cv, "result");
3559
3560 cv.clear();
3561 datasource.deleteData(db, "contractno = '" + contractNo + "'", "collectionlist");
3562 datasource.deleteData(db, "moduleid = '" + moduleid + "' and idx = '" + contractNo + "'", "infodetail");
3563
3564 System.gc();
3565
3566 } catch (Exception e) {
3567 e.printStackTrace();
3568 CollectionActivity.this.e = e;
3569
3570 } finally {
3571 db.close();
3572 }
3573 return "";
3574 }
3575
3576 @Override
3577 protected void onPostExecute(String sResponse) {
3578 if (e == null) {
3579 finish();
3580 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3581 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3582 intent.putExtra("flagUpdate", "N");
3583 startActivity(intent);
3584
3585 dialog.dismiss();
3586 Toast.makeText(mContext, "Data has been saved", Toast.LENGTH_LONG).show();
3587 } else {
3588 Toast.makeText(mContext, "Connection time out", Toast.LENGTH_SHORT).show();
3589 e = null;
3590 dialog.dismiss();
3591 }
3592 }
3593 }
3594
3595 ///--------------------GET VALUE--------------------\\
3596
3597 private String getValue() {
3598 String text = "";
3599 for (int i = 0; i < radiogroup.getChildCount(); i++) {
3600 RadioButton rbt = (RadioButton) radiogroup.getChildAt(i);
3601 if (rbt.isChecked()) {
3602 text = (String) rbt.getText().toString().trim();
3603 break;
3604 }
3605 }
3606 return text.trim();
3607 }
3608
3609 private void disableRadioButton() {
3610 for (int i = 0; i < radiogroup.getChildCount(); i++) {
3611 RadioButton rbt = (RadioButton) radiogroup.getChildAt(i);
3612 rbt.setEnabled(false);
3613 }
3614 }
3615
3616 private boolean CheckForm() {
3617 try {
3618 int i;
3619 boolean good = true;
3620
3621 for (i = 0; i < theForm.fields.size(); i++) {
3622 String fieldValue = (String) theForm.fields.elementAt(i).getData();
3623
3624 if (theForm.fields.elementAt(i).isRequired()) {
3625
3626 if (fieldValue == null || fieldValue.trim().length() == 0) {
3627 theForm.fields.elementAt(i).setData(
3628 theForm.fields.elementAt(i).getErrmsg());
3629 good = false;
3630 }
3631 }
3632 }
3633 return good;
3634 } catch (Exception e) {
3635 Log.e("Activity_Survey", "Error in CheckForm() : " + e.getMessage());
3636 e.printStackTrace();
3637 return false;
3638 }
3639 }
3640
3641 private class PrintInfo extends AsyncTask<Void, Void, String> {
3642
3643 @Override
3644 protected void onPreExecute() {
3645 dialog.show();
3646 }
3647
3648 @Override
3649 protected String doInBackground(Void... arg0) {
3650 boolean threadDone = false;
3651 StringBuilder infoPrint = new StringBuilder();
3652 int serverPort = 48200;
3653 int timeout = 30000;
3654 String isTimeOut = "";
3655
3656 String now;
3657 Calendar cl = Calendar.getInstance();
3658 SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
3659 now = df.format(cl.getTime());
3660 String strDueDate;
3661
3662 strDueDate = dueDate.substring(6, 8) + "/" + dueDate.substring(4, 6) + "/" + dueDate.substring(0, 4);
3663
3664 infoPrint.append("1_|C|B|INFORMASI TAGIHAN_ _");
3665
3666 infoPrint.append("C|N|" + branchName + "_");
3667 infoPrint.append("C|N|" + branchAddress + "_");
3668 infoPrint.append("C|N|" + branchPhone + "_ _");
3669
3670 infoPrint.append("L|N|" + String.valueOf(now).trim() + " - " + collInitial + "_ _");
3671
3672 infoPrint.append("L|N|" + "Nama : " + custNamePrint + "_");
3673 infoPrint.append("L|N|" + "No Kontrak : " + contractNo + "_");
3674 infoPrint.append("L|N|" + "Angsuran ke : " + insNo + "_");
3675 infoPrint.append("L|N|" + "Tgl Jt Tempo: " + strDueDate + "_");
3676 infoPrint.append("L|N|" + "No Plat : " + licensePlate.trim() + "_ _");
3677
3678 int i;
3679 String space = "";
3680 String space2 = "";
3681 double total = 0.0;
3682 NumberFormat formatter = new DecimalFormat("###,###,###");
3683
3684 for (i = 0; i < info.size(); i++) {
3685 String fieldLabel = (String) label.get(i);
3686 String fieldValue = (String) info.get(i);
3687
3688 fieldValue = fieldValue.replace(" ", "").replace(",", "").replace(".00", "");
3689
3690 if (isNumeric(fieldValue.replace("+", "#")) && fieldValue.length() > 2) {
3691 space = new String(new char[(15 - fieldLabel.trim().length())]).replace('\0', ' ');
3692 space2 = new String(new char[(11 - formatter.format(Double.valueOf(fieldValue)).length())]).replace('\0', ' ');
3693
3694 infoPrint.append("L|N|" + fieldLabel.trim() + space + "Rp" + space2 + formatter.format(Double.valueOf(fieldValue)).replace(",", ".") + "_");
3695
3696 total = total + Double.valueOf(fieldValue);
3697 }
3698 }
3699
3700 space = new String(new char[8]).replace('\0', ' ');
3701 space2 = new String(new char[(11 - formatter.format(total).length())]).replace('\0', ' ');
3702
3703 infoPrint.append("L|B|" + "Total" + space + "Rp" + space2 + formatter.format(total).replace(",", ".") + "_ _ _");
3704
3705 infoPrint.append("C|N|" + "Informasi Tagihan ini bukan" + "_");
3706 infoPrint.append("C|N|" + "Merupakan Bukti Pembayaran" + "_");
3707 infoPrint.append("C|N|" + "Terima Kasih" + "_");
3708
3709 try {
3710 serverSocket = new ServerSocket(serverPort);
3711 serverSocket.setSoTimeout(timeout);
3712
3713 while (!threadDone) {
3714 new MultiThread(serverSocket.accept(), infoPrint.toString()).start();
3715 threadDone = true;
3716 }
3717
3718 serverSocket.close();
3719
3720 } catch (Exception e) {
3721 e.printStackTrace();
3722
3723 try {
3724 serverSocket.close();
3725 } catch (IOException e1) {
3726 e1.printStackTrace();
3727 }
3728
3729 isTimeOut = "Print timeout, please try again..";
3730 }
3731
3732 return isTimeOut;
3733 }
3734
3735 @Override
3736 protected void onPostExecute(String sResponse) {
3737
3738 if (sResponse.contentEquals("")) {
3739 dialog.dismiss();
3740 } else {
3741 Toast.makeText(mContext, sResponse, Toast.LENGTH_LONG).show();
3742 dialog.dismiss();
3743 }
3744
3745 }
3746
3747 }
3748
3749 public String encryptSingleDES(String unencryptedString, String passKey) {
3750
3751 try {
3752
3753 byte[] myEncryptionKey = ISOUtil.hex2byte(passKey);
3754
3755 DESKeySpec keySpec = new DESKeySpec(myEncryptionKey);
3756
3757 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
3758 SecretKey secretKey = keyFactory.generateSecret(keySpec);
3759
3760 byte[] cleartext = ISOUtil.hex2byte(unencryptedString);
3761
3762 Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
3763 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
3764 String encrypedPwd = ISOUtil.hexString(cipher.doFinal(cleartext));
3765
3766 return encrypedPwd;
3767
3768 } catch (InvalidKeyException e1) {
3769 e1.printStackTrace();
3770 } catch (NoSuchAlgorithmException e) {
3771 e.printStackTrace();
3772 } catch (NoSuchPaddingException e) {
3773 e.printStackTrace();
3774 } catch (InvalidKeySpecException e) {
3775 e.printStackTrace();
3776 } catch (IllegalBlockSizeException e) {
3777 e.printStackTrace();
3778 } catch (BadPaddingException e) {
3779 e.printStackTrace();
3780 }
3781
3782 return null;
3783 }
3784
3785 private void setDateTimeField() {
3786 Calendar newCalendar = Calendar.getInstance();
3787 fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
3788
3789 public void onDateSet(DatePicker view, int dayOfMonth, int monthOfYear, int year) {
3790 Calendar newDate = Calendar.getInstance();
3791 newDate.set(dayOfMonth, monthOfYear, year);
3792 searchText.setText(dateFormatter.format(newDate.getTime()));
3793 }
3794
3795 },newCalendar.get(Calendar.DAY_OF_MONTH), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.YEAR));
3796
3797
3798 }
3799
3800 private void datepicker(){
3801 final Calendar c = Calendar.getInstance();
3802 int mYear = c.get(Calendar.YEAR); // current year
3803 int mMonth = c.get(Calendar.MONTH); // current month
3804 int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
3805 datePickerDialog = new DatePickerDialog(CollectionActivity.this,
3806 new DatePickerDialog.OnDateSetListener() {
3807 @Override
3808 public void onDateSet(DatePicker view, int year,
3809 int monthOfYear, int dayOfMonth) {
3810 searchText.setText(dayOfMonth + "/"
3811 + (monthOfYear + 1) + "/" + year);
3812
3813 }
3814 }, mYear, mMonth, mDay);
3815 datePickerDialog.show();
3816 }
3817
3818
3819
3820 ///--------------------GET VALUE--------------------\\
3821
3822
3823 @Override
3824 public void onBackPressed() {
3825
3826 final SweetAlertDialog close = new SweetAlertDialog(CollectionActivity.this, SweetAlertDialog.WARNING_TYPE);
3827 close.setCanceledOnTouchOutside(true);
3828 close.setTitleText("Perhatian!")
3829 .setContentText("Anda Yakin Untuk Kembali ?")
3830 .setConfirmText("Ya")
3831 .setCancelText("Tidak")
3832
3833 .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
3834 @Override
3835 public void onClick(final SweetAlertDialog sDialog) {
3836 sDialog.dismiss();
3837 finish();
3838 hapusfoto();
3839 Intent intent = new Intent(mContext, ListCollectionActivity.class);
3840 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3841 intent.putExtra("flagUpdate", "N");
3842 startActivity(intent);
3843 }
3844 })
3845 .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
3846 @Override
3847 public void onClick(SweetAlertDialog sweetAlertDialog) {
3848 sweetAlertDialog.cancel();
3849
3850 }
3851 });
3852 close.show();
3853
3854
3855 return;
3856 }
3857
3858 @Override
3859 protected void onStart() {
3860 super.onStart();
3861 if (googleApiClient !=null){
3862 googleApiClient.connect();
3863 }
3864
3865 }
3866
3867 @Override
3868 public void onDestroy() {
3869 super.onDestroy();
3870
3871 if (wl.isHeld())
3872 wl.release();
3873
3874 if (theForm != null) {
3875 theForm = null;
3876 }
3877
3878 if (adapter != null) {
3879 adapter.notifyDataSetInvalidated();
3880 adapter = null;
3881 }
3882
3883 if (datasource != null) {
3884 datasource.close();
3885 }
3886
3887 if (locationManager != null) {
3888 if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
3889
3890 return;
3891 }
3892 locationManager.removeUpdates(locationListenerGps);
3893 locationManager.removeUpdates(locationListenerNetwork);
3894 locationManager = null;
3895 }
3896
3897 if (Nmap != null) {
3898 Nmap.clear();
3899 }
3900
3901 if (tabHost != null) {
3902 tabHost = null;
3903 }
3904
3905 if (dialog != null) {
3906 if (dialog.isShowing()) {
3907 dialog.dismiss();
3908 }
3909 }
3910
3911 if (db != null) {
3912 if (db.isOpen()) {
3913 db.close();
3914 }
3915 }
3916
3917 //googleApiClient.disconnect();
3918
3919 }
3920
3921 @Override
3922 public void onPause() {
3923 super.onPause();
3924
3925 if(wl.isHeld())
3926 wl.release();
3927
3928 if (dialog != null) {
3929 if (dialog.isShowing()) {
3930 dialog.dismiss();
3931 }
3932 }
3933
3934 if(serverSocket != null)
3935 try {
3936 serverSocket.close();
3937 } catch (IOException e) {
3938 e.printStackTrace();
3939 }
3940
3941
3942 flag = false;
3943 String now;
3944 Calendar c = Calendar.getInstance();
3945 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3946 now = df.format(c.getTime());
3947 generalPrefs.edit().putString("sessionStart", String.valueOf(now)).commit();
3948 }
3949
3950 @Override
3951 public void onResume() {
3952 super.onResume();
3953
3954 if (flag == false) {
3955 try {
3956 String sessionStart;
3957 String now;
3958 String timeOut;
3959 long diffInMin = 0;
3960
3961 Calendar c = Calendar.getInstance();
3962 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
3963 now = df.format(c.getTime());
3964
3965 timeOut = generalPrefs.getString("timeOut", null);
3966 sessionStart = generalPrefs.getString("sessionStart", null);
3967
3968 Date dateStart = df.parse(sessionStart);
3969 Date dateEnd = df.parse(now);
3970
3971 //googleApiClient.connect();
3972
3973 diffInMin = (dateEnd.getTime() / 60000) - (dateStart.getTime() / 60000);
3974
3975 if ((int) diffInMin > Integer.valueOf(timeOut) || (int) diffInMin < 0) {
3976 Toast.makeText(this,"Your session has been expired, please re login for security purpose", Toast.LENGTH_LONG).show();
3977 prefsEditor.putBoolean("finish", true).commit();
3978
3979 finish();
3980 Intent myintent = new Intent(mContext, HomeActivity.class);
3981 myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
3982 startActivity(myintent);
3983 }else{
3984 if(!wl.isHeld())
3985 wl.acquire();
3986 }
3987
3988 } catch (ParseException e) {
3989 e.printStackTrace();
3990 }
3991 }else{
3992 if(!wl.isHeld())
3993 wl.acquire();
3994 }
3995 }
3996
3997
3998
3999 @Override
4000 public void onConnected(@Nullable Bundle bundle) {
4001
4002
4003 }
4004
4005 @Override
4006 public void onConnectionSuspended(int i) {
4007 Toast.makeText(getApplicationContext(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
4008
4009 }
4010
4011 @Override
4012 public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
4013 Toast.makeText(getApplicationContext(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
4014 }
4015
4016 @Override
4017 public void onLocationChanged(Location location) {
4018
4019
4020 }
4021
4022
4023
4024}