Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.41 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. public class User {
  461.  
  462. private String id;
  463. private String name;
  464. private String email;
  465. private String password;
  466. private String newPassword;
  467. private boolean type;
  468. private boolean sendNotification;
  469. private String image;
  470.  
  471. public User() {
  472. }
  473.  
  474. public String getId() {
  475. return id;
  476. }
  477.  
  478. public void setId(String id) {
  479. this.id = id;
  480. }
  481.  
  482. public String getName() {
  483. return name;
  484. }
  485.  
  486. public void setName(String name) {
  487. this.name = name;
  488. }
  489.  
  490. public void setNameIfNull(String name) {
  491. if (this.name == null) {
  492. this.name = name;
  493. }
  494. }
  495.  
  496. public String getEmail() {
  497. return email;
  498. }
  499.  
  500. public void setEmail(String email) {
  501. this.email = email;
  502. }
  503.  
  504. public void setEmailIfNull(String email) {
  505. if (this.email == null) {
  506. this.email = email;
  507. }
  508. }
  509.  
  510. public String getPassword() {
  511. return password;
  512. }
  513.  
  514. public void setPassword(String password) {
  515. this.password = password;
  516. }
  517.  
  518. public String getNewPassword() {
  519. return newPassword;
  520. }
  521.  
  522. public void setNewPassword(String newPassword) {
  523. this.newPassword = newPassword;
  524. }
  525.  
  526. public boolean isType() {
  527. return type;
  528. }
  529.  
  530. public void setType(boolean type) {
  531. this.type = type;
  532. }
  533.  
  534. public boolean isSendNotification() {
  535. return sendNotification;
  536. }
  537.  
  538. public void setSendNotification(boolean sendNotification) {
  539. this.sendNotification = sendNotification;
  540. }
  541.  
  542. public String getImage() {
  543. return image;
  544. }
  545.  
  546. public void setImage(String image) {
  547. this.image = image;
  548. }
  549.  
  550. public void saveDB(DatabaseReference.CompletionListener... completionListener) {
  551. DatabaseReference firebase = LibraryClass.getFirebase().child("users").child(getId());
  552. if (completionListener.length == 0) {
  553. setPassword(null);
  554. setId(null);
  555. firebase.setValue(this);
  556. } else {
  557. setPassword(null);
  558. setId(null);
  559. firebase.setValue(this, completionListener[0]);
  560. }
  561. }
  562.  
  563. public class Bakery {
  564.  
  565. private String id;
  566. private String userID;
  567. private String corporateName;
  568. private String fantasyName;
  569. private String fone;
  570. private String email;
  571. private String cnpj;
  572. private String bakeryImage;
  573. private Adress adress;
  574.  
  575. public Bakery() {}
  576.  
  577. public Bakery(String id, String userID, String corporateName, String fantasyName, String fone,
  578. String email, String cnpj, String bakeryImage, Adress adress) {
  579. this.id = id;
  580. this.userID = userID;
  581. this.corporateName = corporateName;
  582. this.fantasyName = fantasyName;
  583. this.fone = fone;
  584. this.email = email;
  585. this.cnpj = cnpj;
  586. this.bakeryImage = bakeryImage;
  587. this.adress = adress;
  588. }
  589.  
  590. public String getId() {
  591. return id;
  592. }
  593.  
  594. public void setId(String id) {
  595. this.id = id;
  596. }
  597.  
  598. public String getUserID() {
  599. return userID;
  600. }
  601.  
  602. public void setUserID(String userID) {
  603. this.userID = userID;
  604. }
  605.  
  606. public String getCorporateName() {
  607. return corporateName;
  608. }
  609.  
  610. public void setCorporateName(String corporateName) {
  611. this.corporateName = corporateName;
  612. }
  613.  
  614. public String getFantasyName() {
  615. return fantasyName;
  616. }
  617.  
  618. public void setFantasyName(String fantasyName) {
  619. this.fantasyName = fantasyName;
  620. }
  621.  
  622. public String getFone() {
  623. return fone;
  624. }
  625.  
  626. public void setFone(String fone) {
  627. this.fone = fone;
  628. }
  629.  
  630. public String getEmail() {
  631. return email;
  632. }
  633.  
  634. public void setEmail(String email) {
  635. this.email = email;
  636. }
  637.  
  638. public String getCnpj() {
  639. return cnpj;
  640. }
  641.  
  642. public void setCnpj(String cnpj) {
  643. this.cnpj = cnpj;
  644. }
  645.  
  646. public String getBakeryImage() {
  647. return bakeryImage;
  648. }
  649.  
  650. public void setBakeryImage(String bakeryImage) {
  651. this.bakeryImage = bakeryImage;
  652. }
  653.  
  654. public Adress getAdress() {
  655. return adress;
  656. }
  657.  
  658. public void setAdress(Adress adress) {
  659. this.adress = adress;
  660. }
  661.  
  662. public void saveDB(DatabaseReference.CompletionListener... completionListener) {
  663. DatabaseReference firebase = LibraryClass.getFirebase().child("bakeries").child(getId());
  664. if (completionListener.length == 0) {
  665. firebase.setValue(this);
  666. } else {
  667. firebase.setValue(this, completionListener[0]);
  668. }
  669. }
  670.  
  671. bakery.saveDB(RegisterBakeryActivity.this);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement