Advertisement
Guest User

Untitled

a guest
Feb 24th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.65 KB | None | 0 0
  1. public class RegisterBakeryActivity extends CommonActivity implements GoogleApiClient.ConnectionCallbacks,
  2. GoogleApiClient.OnConnectionFailedListener, DatabaseReference.CompletionListener{
  3.  
  4. private GoogleApiClient mGoogleApiClient;
  5. private Location mLastLocation;
  6. private Resources resources;
  7. private EditText inputCorporateName, inputFantasyName, inputFone, inputEmail, inputCnpj, inputStreet, inputNumber, inputDiscrict, inputCity, inputAdminPassword;
  8. private String corporateName, fantasyName, fone, email, cnpj, street, district, city, adminPassword, idString, numberString, cnpjAux;
  9. private int number;
  10. private static final String TAG = RegisterBakeryActivity.class.getSimpleName();
  11. private ProgressDialog progressDialog, pDialog;
  12. // URL to get contacts JSON
  13. private static String url = "http://receitaws.com.br/v1/cnpj/";
  14. // JSON Node names
  15. private static final String TAG_FANTASY = "fantasia";
  16. private static final String TAG_NAME = "nome";
  17. private static final String TAG_EMAIL = "email";
  18. private static final String TAG_STREET = "logradouro";
  19. private static final String TAG_DISTRICT = "bairro";
  20. private static final String TAG_PHONE = "telefone";
  21. private static final String TAG_NUMBER = "numero";
  22. private static final String TAG_CITY = "municipio";
  23. private String nameJson;
  24. private String numberJson;
  25. private String emailJson;
  26. private String fantasyJson;
  27. private String phoneJson;
  28. private String streetJson;
  29. private String districtJson;
  30. private String cityJson;
  31. private User user;
  32. private Bakery bakery;
  33. private Adress adress;
  34. private FirebaseAuth mAuth;
  35. private FirebaseAuth.AuthStateListener mAuthStateListener;
  36.  
  37. // Hashmap for ListView
  38. ArrayList<HashMap<String, String>> bakerieList;
  39. private String code;
  40. private String adressLocation = "";
  41. private Location l;
  42. private Double latitude, longitude;
  43. private DatabaseReference mBakeriessNodeRef;
  44.  
  45. @Override
  46. public void onCreate(Bundle savedInstanceState) {
  47. super.onCreate(savedInstanceState);
  48. setContentView(R.layout.activity_register_bakery);
  49. callConnection();
  50. if (android.os.Build.VERSION.SDK_INT > 9) {
  51. StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  52. StrictMode.setThreadPolicy(policy);
  53. }
  54.  
  55. bakerieList = new ArrayList<HashMap<String, String>>();
  56. resources = getResources();
  57. mAuth = FirebaseAuth.getInstance();
  58.  
  59. Button btnSearchByCNPJ = (Button) findViewById(R.id.btn_search_by_cnpj);
  60. btnSearchByCNPJ.setOnClickListener(new View.OnClickListener() {
  61. @Override
  62. public void onClick(View v) {
  63. cnpjAux = inputCnpj.getText().toString().trim();
  64. // Calling async task to get json
  65. new GetBakery().execute();
  66. }
  67. });
  68.  
  69. Button btnAddBakery = (Button) findViewById(R.id.btn_add_bakery);
  70. btnAddBakery.setOnClickListener(new View.OnClickListener() {
  71. @Override
  72. public void onClick(View v) {
  73. if (validateFields()) {
  74. openProgressDialog("Cadastrando...", "Aguarde um momento!");
  75. initUser();
  76. initBakery();
  77. saveUser();
  78. }
  79. }
  80. });
  81. mAuthStateListener = new FirebaseAuth.AuthStateListener() {
  82. @Override
  83. public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  84. FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
  85.  
  86. if (firebaseUser == null || user.getId() != null) {
  87. return;
  88. }
  89.  
  90. user.setId(firebaseUser.getUid());
  91. user.saveDB(RegisterBakeryActivity.this);
  92. bakery.saveDB(RegisterBakeryActivity.this);
  93. }
  94. };
  95. initViews();
  96. initWatchers();
  97. }
  98.  
  99. /**
  100. * Chama o método para limpar erros
  101. *
  102. * @param s Editable
  103. */
  104. private void callClearErrors(Editable s) {
  105. if (!s.toString().isEmpty()) {
  106. clearErrorFields(inputCorporateName);
  107. }
  108. }
  109.  
  110. /**
  111. * Efetua a validação dos campos.Nesse caso, valida se os campos não estão vazios e se tem
  112. * tamanho permitido.
  113. * Nesse método você poderia colocar outros tipos de validações de acordo com a sua necessidade.
  114. *
  115. * @return boolean que indica se os campos foram validados com sucesso ou não
  116. */
  117. private boolean validateFields() {
  118. corporateName = inputCorporateName.getText().toString().trim();
  119. email = inputEmail.getText().toString().trim();
  120. fantasyName = inputFantasyName.getText().toString().trim();
  121. fone = inputFone.getText().toString().trim();
  122. cnpj = inputCnpj.getText().toString().trim();
  123. street = inputStreet.getText().toString().trim();
  124. number = Integer.parseInt(inputNumber.getText().toString().trim());
  125. String numberAux = inputNumber.getText().toString().trim();
  126. district = inputDiscrict.getText().toString().trim();
  127. city = inputCity.getText().toString().trim();
  128. adminPassword = inputAdminPassword.getText().toString().trim();
  129. return (!isEmptyFields(email, fantasyName, fone, cnpj, street, district, numberAux, city, adminPassword) && hasSizeValid(fone, cnpj) && emailValid(email));
  130. }
  131.  
  132. private boolean isEmptyFields(String email, String fantasyName, String fone, String cnpj, String street, String district, String number, String city, String adminPassword) {
  133. if (TextUtils.isEmpty(email)) {
  134. inputEmail.requestFocus(); //seta o foco para o campo email
  135. inputEmail.setError(resources.getString(R.string.register_email_required));
  136. return true;
  137. } else if (TextUtils.isEmpty(fantasyName)) {
  138. inputFantasyName.requestFocus(); //seta o foco para o campo
  139. inputFantasyName.setError(resources.getString(R.string.register_field_required));
  140. return true;
  141. } else if (TextUtils.isEmpty(fone)) {
  142. inputFone.requestFocus(); //seta o foco para o campo
  143. inputFone.setError(resources.getString(R.string.register_field_required));
  144. return true;
  145. } else if (TextUtils.isEmpty(cnpj)) {
  146. inputCnpj.requestFocus(); //seta o foco para o campo
  147. inputCnpj.setError(resources.getString(R.string.register_field_required));
  148. return true;
  149. } else if (TextUtils.isEmpty(street)) {
  150. inputStreet.requestFocus(); //seta o foco para o campo
  151. inputStreet.setError(resources.getString(R.string.register_field_required));
  152. return true;
  153. } else if (TextUtils.isEmpty(district)) {
  154. inputDiscrict.requestFocus(); //seta o foco para o campo
  155. inputDiscrict.setError(resources.getString(R.string.register_field_required));
  156. return true;
  157. } else if (TextUtils.isEmpty(number)) {
  158. inputNumber.requestFocus(); //seta o foco para o campo
  159. inputNumber.setError(resources.getString(R.string.register_field_required));
  160. return true;
  161. } else if (TextUtils.isEmpty(city)) {
  162. inputCity.requestFocus(); //seta o foco para o campo
  163. inputCity.setError(resources.getString(R.string.register_field_required));
  164. return true;
  165. } else if (TextUtils.isEmpty(adminPassword)) {
  166. inputAdminPassword.requestFocus(); //seta o foco para o campo
  167. inputAdminPassword.setError(resources.getString(R.string.register_field_required));
  168. return true;
  169. }
  170. return false;
  171. }
  172.  
  173. private boolean hasSizeValid(String fone, String cnpj) {
  174.  
  175. if (!(fone.length() > 11)) {
  176. inputFone.requestFocus();
  177. inputFone.setError(resources.getString(R.string.register_fone_size_invalid));
  178. return false;
  179. } else if (!(cnpj.length() > 4)) {
  180. inputCnpj.requestFocus();
  181. inputCnpj.setError(resources.getString(R.string.register_cnpj_size_invalid));
  182. return false;
  183. }
  184. return true;
  185. }
  186.  
  187. /**
  188. * Limpa os ícones e as mensagens de erro dos campos desejados
  189. *
  190. * @param editTexts lista de campos do tipo EditText
  191. */
  192. private void clearErrorFields(EditText... editTexts) {
  193. for (EditText editText : editTexts) {
  194. editText.setError(null);
  195. }
  196. }
  197.  
  198. private boolean emailValid(String email) {
  199.  
  200. String Expn = "^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
  201. + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?"
  202. + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
  203. + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?"
  204. + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
  205. + "([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
  206. if (email.matches(Expn) && email.length() > 0) {
  207. return true;
  208. } else {
  209. inputEmail.requestFocus();
  210. inputEmail.setError(resources.getString(R.string.register_email_char_invalid));
  211. return false;
  212. }
  213. }
  214.  
  215. /**
  216. * Async task class to get json by making HTTP call
  217. */
  218. private class GetBakery extends AsyncTask<Void, Void, Void> {
  219.  
  220. @Override
  221. protected void onPreExecute() {
  222. super.onPreExecute();
  223. // Showing progress dialog
  224. openProgressDialog("Buscando dados...", "Aguarde!");
  225. }
  226.  
  227. @Override
  228. protected Void doInBackground(Void... arg0) {
  229.  
  230. // Creating service handler class instance
  231. ServiceHandler sh = new ServiceHandler();
  232.  
  233. url = url + cnpjAux;
  234. // Making a request to url and getting response
  235. String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
  236.  
  237. Log.d("Response: ", "> " + jsonStr);
  238.  
  239. if (jsonStr != null) {
  240. try {
  241. JSONObject c = new JSONObject(jsonStr);
  242. fantasyJson = c.optString(TAG_FANTASY);
  243. nameJson = c.optString(TAG_NAME);
  244. emailJson = c.optString(TAG_EMAIL);
  245. streetJson = c.optString(TAG_STREET);
  246. numberJson = c.optString(TAG_NUMBER);
  247. phoneJson = c.optString(TAG_PHONE);
  248. districtJson = c.optString(TAG_DISTRICT);
  249. cityJson = c.optString(TAG_CITY);
  250.  
  251. // tmp hashmap for single contact
  252. HashMap<String, String> bakery = new HashMap<String, String>();
  253.  
  254. // adding each child node to HashMap key => value
  255. bakery.put(TAG_FANTASY, fantasyJson);
  256. bakery.put(TAG_NAME, nameJson);
  257. bakery.put(TAG_EMAIL, emailJson);
  258. bakery.put(TAG_PHONE, phoneJson);
  259. bakery.put(TAG_CITY, cityJson);
  260. bakery.put(TAG_DISTRICT, districtJson);
  261. bakery.put(TAG_NUMBER, numberJson);
  262. bakery.put(TAG_STREET, streetJson);
  263. adressLocation = streetJson + ", " + numberJson;
  264. List<Address> list = new ArrayList<Address>();
  265. Geocoder geocoder = new Geocoder(RegisterBakeryActivity.this, Locale.getDefault());
  266. String error = "";
  267.  
  268. try {
  269. list = (ArrayList<Address>) geocoder.getFromLocationName(adressLocation, 1);
  270. } catch (IOException e) {
  271. e.printStackTrace();
  272. error = "Network problem";
  273. } catch (IllegalArgumentException e) {
  274. e.printStackTrace();
  275. error = "Illegal arguments";
  276. }
  277.  
  278. if (list != null && list.size() > 0) {
  279. Address a = list.get(0);
  280. latitude = a.getLatitude();
  281. longitude = a.getLongitude();
  282. } else {
  283.  
  284. }
  285.  
  286. // adding contact to contact list
  287. bakerieList.add(bakery);
  288. } catch (JSONException e) {
  289. e.printStackTrace();
  290. }
  291. } else {
  292. Log.e("ServiceHandler", "Couldn't get any data from the url");
  293. }
  294. return null;
  295. }
  296.  
  297. @Override
  298. protected void onPostExecute(Void result) {
  299. super.onPostExecute(result);
  300. closeProgressDialog();
  301. setEditText(fantasyJson, nameJson, emailJson, streetJson, numberJson, districtJson, cityJson, phoneJson);
  302. }
  303.  
  304. }
  305.  
  306. private void setEditText(String fantasy, String name, String email, String street, String number, String district, String city, String phone) {
  307. inputDiscrict.setText(district);
  308. inputCity.setText(city);
  309. inputEmail.setText(email);
  310. inputFantasyName.setText(fantasy);
  311. inputFone.setText(phone);
  312. inputCorporateName.setText(name);
  313. inputStreet.setText(street);
  314. inputNumber.setText(number);
  315. }
  316.  
  317. private synchronized void callConnection(){
  318. Log.i("LOG", "RegisterBakeryActivity.callConnection()");
  319. mGoogleApiClient = new GoogleApiClient.Builder(this)
  320. .addOnConnectionFailedListener(this)
  321. .addConnectionCallbacks(this)
  322. .addApi(LocationServices.API)
  323. .build();
  324. mGoogleApiClient.connect();
  325. }
  326.  
  327. @Override
  328. public void onConnected(Bundle bundle) {
  329. Log.i("LOG", "AddressLocationActivity.onConnected(" + bundle + ")");
  330.  
  331. //l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  332.  
  333. if(l != null){
  334. mLastLocation = l;
  335. }
  336. }
  337.  
  338. @Override
  339. public void onConnectionSuspended(int i) {
  340. Log.i("LOG", "AddressLocationActivity.onConnectionSuspended(" + i + ")");
  341. }
  342.  
  343. @Override
  344. protected void initViews() {
  345. inputCorporateName = (EditText) findViewById(R.id.input_corporate_name);
  346. inputCorporateName.setKeyListener(null);
  347. inputFantasyName = (EditText) findViewById(R.id.input_fantasy_name);
  348. inputFone = (EditText) findViewById(R.id.input_fone);
  349. MaskEditTextChangedListener maskFone = new MaskEditTextChangedListener("(##)####-####", inputFone);
  350. inputFone.addTextChangedListener(maskFone);
  351. inputEmail = (EditText) findViewById(R.id.input_email);
  352. inputCnpj = (EditText) findViewById(R.id.input_cnpj);
  353. inputStreet = (EditText) findViewById(R.id.input_street);
  354. inputNumber = (EditText) findViewById(R.id.input_number);
  355. inputDiscrict = (EditText) findViewById(R.id.input_district);
  356. inputCity = (EditText) findViewById(R.id.input_city);
  357. inputAdminPassword = (EditText) findViewById(R.id.input_admin_password);
  358.  
  359. }
  360.  
  361. @Override
  362. protected void initUser() {
  363. user = new User();
  364. user.setName(fantasyName);
  365. user.setEmail(email);
  366. final Encryption cripto = Encryption.getInstance(adminPassword);
  367. user.setPassword(cripto.getEncryptPassword());
  368. user.setType(true);
  369. user.setSendNotification(true);
  370. }
  371.  
  372. private void initBakery(){
  373. bakery = new Bakery();
  374. adress = new Adress(user.getId(), null, null, street, district, city, number, latitude, longitude, null);
  375. bakery.setEmail(email);
  376. bakery.setAdress(adress);
  377. bakery.setCnpj(cnpj);
  378. bakery.setCorporateName(corporateName);
  379. bakery.setFantasyName(fantasyName);
  380. bakery.setFone(fone);
  381. bakery.setUserID(user.getId());
  382. }
  383.  
  384. private void initWatchers(){
  385.  
  386. TextWatcher textWatcher = new TextWatcher() {
  387. @Override
  388. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  389. }
  390.  
  391. @Override
  392. public void onTextChanged(CharSequence s, int start, int before, int count) {
  393. }
  394.  
  395. @Override
  396. public void afterTextChanged(Editable s) {
  397. callClearErrors(s);
  398. }
  399. };
  400. inputCorporateName.addTextChangedListener(textWatcher);
  401. inputFantasyName.addTextChangedListener(textWatcher);
  402. inputFone.addTextChangedListener(textWatcher);
  403. inputEmail.addTextChangedListener(textWatcher);
  404. inputCnpj.addTextChangedListener(textWatcher);
  405. inputStreet.addTextChangedListener(textWatcher);
  406. inputNumber.addTextChangedListener(textWatcher);
  407. inputDiscrict.addTextChangedListener(textWatcher);
  408. inputCity.addTextChangedListener(textWatcher);
  409. inputAdminPassword.addTextChangedListener(textWatcher);
  410. }
  411.  
  412. @Override
  413. public void onConnectionFailed(ConnectionResult connectionResult) {
  414. Log.i("LOG", "AddressLocationActivity.onConnectionFailed(" + connectionResult + ")");
  415. }
  416.  
  417. private void saveUser() {
  418. mAuth.createUserWithEmailAndPassword(
  419. user.getEmail(),
  420. user.getPassword()
  421. ).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
  422. @Override
  423. public void onComplete(@NonNull Task<AuthResult> task) {
  424.  
  425. if (!task.isSuccessful()) {
  426. closeProgressDialog();
  427. }
  428. }
  429. }).addOnFailureListener(this, new OnFailureListener() {
  430. @Override
  431. public void onFailure(@NonNull Exception e) {
  432. showSnackbar(e.getMessage());
  433. }
  434. });
  435. }
  436.  
  437. @Override
  438. public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
  439. //bakery.saveDB(RegisterBakeryActivity.this);
  440. mAuth.signOut();
  441. showToast("Padaria registrada com sucesso!");
  442. closeProgressDialog();
  443. finish();
  444. }
  445.  
  446. @Override
  447. protected void onStart() {
  448. super.onStart();
  449. mAuth.addAuthStateListener(mAuthStateListener);
  450. }
  451.  
  452. @Override
  453. protected void onStop() {
  454. super.onStop();
  455. if (mAuthStateListener != null) {
  456. mAuth.removeAuthStateListener(mAuthStateListener);
  457. }
  458. }
  459. }
  460.  
  461. public class User {
  462.  
  463. private String id;
  464. private String name;
  465. private String email;
  466. private String password;
  467. private String newPassword;
  468. private boolean type;
  469. private boolean sendNotification;
  470. private String image;
  471.  
  472. public User() {
  473. }
  474.  
  475. public String getId() {
  476. return id;
  477. }
  478.  
  479. public void setId(String id) {
  480. this.id = id;
  481. }
  482.  
  483. public String getName() {
  484. return name;
  485. }
  486.  
  487. public void setName(String name) {
  488. this.name = name;
  489. }
  490.  
  491. public void setNameIfNull(String name) {
  492. if (this.name == null) {
  493. this.name = name;
  494. }
  495. }
  496.  
  497. public String getEmail() {
  498. return email;
  499. }
  500.  
  501. public void setEmail(String email) {
  502. this.email = email;
  503. }
  504.  
  505. public void setEmailIfNull(String email) {
  506. if (this.email == null) {
  507. this.email = email;
  508. }
  509. }
  510.  
  511. public String getPassword() {
  512. return password;
  513. }
  514.  
  515. public void setPassword(String password) {
  516. this.password = password;
  517. }
  518.  
  519. public String getNewPassword() {
  520. return newPassword;
  521. }
  522.  
  523. public void setNewPassword(String newPassword) {
  524. this.newPassword = newPassword;
  525. }
  526.  
  527. public boolean isType() {
  528. return type;
  529. }
  530.  
  531. public void setType(boolean type) {
  532. this.type = type;
  533. }
  534.  
  535. public boolean isSendNotification() {
  536. return sendNotification;
  537. }
  538.  
  539. public void setSendNotification(boolean sendNotification) {
  540. this.sendNotification = sendNotification;
  541. }
  542.  
  543. public String getImage() {
  544. return image;
  545. }
  546.  
  547. public void setImage(String image) {
  548. this.image = image;
  549. }
  550.  
  551. public void saveDB(DatabaseReference.CompletionListener... completionListener) {
  552. DatabaseReference firebase = LibraryClass.getFirebase().child("users").child(getId());
  553. if (completionListener.length == 0) {
  554. setPassword(null);
  555. setId(null);
  556. firebase.setValue(this);
  557. } else {
  558. setPassword(null);
  559. setId(null);
  560. firebase.setValue(this, completionListener[0]);
  561. }
  562. }
  563. }
  564.  
  565. public class Bakery {
  566.  
  567. private String id;
  568. private String userID;
  569. private String corporateName;
  570. private String fantasyName;
  571. private String fone;
  572. private String email;
  573. private String cnpj;
  574. private String bakeryImage;
  575. private Adress adress;
  576.  
  577. public Bakery() {}
  578.  
  579. public Bakery(String id, String userID, String corporateName, String fantasyName, String fone,
  580. String email, String cnpj, String bakeryImage, Adress adress) {
  581. this.id = id;
  582. this.userID = userID;
  583. this.corporateName = corporateName;
  584. this.fantasyName = fantasyName;
  585. this.fone = fone;
  586. this.email = email;
  587. this.cnpj = cnpj;
  588. this.bakeryImage = bakeryImage;
  589. this.adress = adress;
  590. }
  591.  
  592. public String getId() {
  593. return id;
  594. }
  595.  
  596. public void setId(String id) {
  597. this.id = id;
  598. }
  599.  
  600. public String getUserID() {
  601. return userID;
  602. }
  603.  
  604. public void setUserID(String userID) {
  605. this.userID = userID;
  606. }
  607.  
  608. public String getCorporateName() {
  609. return corporateName;
  610. }
  611.  
  612. public void setCorporateName(String corporateName) {
  613. this.corporateName = corporateName;
  614. }
  615.  
  616. public String getFantasyName() {
  617. return fantasyName;
  618. }
  619.  
  620. public void setFantasyName(String fantasyName) {
  621. this.fantasyName = fantasyName;
  622. }
  623.  
  624. public String getFone() {
  625. return fone;
  626. }
  627.  
  628. public void setFone(String fone) {
  629. this.fone = fone;
  630. }
  631.  
  632. public String getEmail() {
  633. return email;
  634. }
  635.  
  636. public void setEmail(String email) {
  637. this.email = email;
  638. }
  639.  
  640. public String getCnpj() {
  641. return cnpj;
  642. }
  643.  
  644. public void setCnpj(String cnpj) {
  645. this.cnpj = cnpj;
  646. }
  647.  
  648. public String getBakeryImage() {
  649. return bakeryImage;
  650. }
  651.  
  652. public void setBakeryImage(String bakeryImage) {
  653. this.bakeryImage = bakeryImage;
  654. }
  655.  
  656. public Adress getAdress() {
  657. return adress;
  658. }
  659.  
  660. public void setAdress(Adress adress) {
  661. this.adress = adress;
  662. }
  663.  
  664. public void saveDB(DatabaseReference.CompletionListener... completionListener) {
  665. DatabaseReference firebase = LibraryClass.getFirebase().child("bakeries").child(getId());
  666. if (completionListener.length == 0) {
  667. firebase.setValue(this);
  668. } else {
  669. firebase.setValue(this, completionListener[0]);
  670. }
  671. }
  672. }
  673.  
  674. bakery.saveDB(RegisterBakeryActivity.this);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement