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