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