@Override
 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
   if (parent == mSpinnerGeology) {
     geologyIndex = position;
     new PreferencesUtil(getContext()).save("geologyIndex", geologyIndex);
     initConditions(getActivity());
     initConditions(getActivity());
     initConditiontValue(getActivity());
     changeAllGeology();
   }
   if (parent == mSpinnerCondition) {
     conditionIndex = position;
     initConditions(getActivity());
     initConditiontValue(getActivity());
   }
   if (parent == mSpinnerConditionValue) {
     conditionValueIndex = position;
   }
   String selectItem = null;
   try {
     selectItem = mSpinnerConditionValue.getSelectedItem().toString();
   } catch (Exception e) {
     e.printStackTrace();
   }
   slog.p(TAG, "selectItem " + selectItem);
   if (mETValue1 != null && mETValue2 != null) {
     if (selectItem != null && selectItem.equals("自定义")) {
       mETValue1.setVisibility(View.VISIBLE);
       mETValue2.setVisibility(View.VISIBLE);
     } else {
       mETValue1.setVisibility(View.GONE);
       mETValue2.setVisibility(View.GONE);
     }
   }
 }
 public void setEmailFieldHidden(boolean hidden) {
   EditText email = (EditText) findViewById(R.id.email);
   if (hidden) {
     email.setVisibility(View.GONE);
   } else {
     email.setVisibility(View.VISIBLE);
   }
 }
Exemplo n.º 3
0
 public void setModel(SendModel m) {
   sendModel = m;
   if (m == SendModel.TEXT) {
     mEdittext.setVisibility(VISIBLE);
     mHoldtospeek.setVisibility(GONE);
     mSend.setVisibility(GONE);
     mFacial.setVisibility(VISIBLE);
   } else {
     mEdittext.setVisibility(GONE);
     //            mHoldtospeek.setVisibility(VISIBLE);
     mSpeak.setVisibility(GONE);
     mSoundinput.setVisibility(View.VISIBLE);
     mFacial.setVisibility(GONE);
     mSend.setVisibility(VISIBLE);
   }
 }
  /** Shows/hides password field and client certificate spinner */
  private void updateViewFromAuthType() {
    AuthType authType = getSelectedAuthType();
    boolean isAuthTypeExternal = (AuthType.EXTERNAL == authType);

    if (isAuthTypeExternal) {

      // hide password fields, show client certificate fields
      mPasswordView.setVisibility(View.GONE);
      mPasswordLabelView.setVisibility(View.GONE);
      mClientCertificateLabelView.setVisibility(View.VISIBLE);
      mClientCertificateSpinner.setVisibility(View.VISIBLE);
    } else {

      // show password fields, hide client certificate fields
      mPasswordView.setVisibility(View.VISIBLE);
      mPasswordLabelView.setVisibility(View.VISIBLE);
      mClientCertificateLabelView.setVisibility(View.GONE);
      mClientCertificateSpinner.setVisibility(View.GONE);
    }
  }
Exemplo n.º 5
0
  @Override
  public void onClick(View v) {
    TextView txtManageLabel, txtBrowseLabel, txtRefreshLabel, txtSearchLabel;
    txtManageLabel = (TextView) findViewById(R.id.txt_manage_label);
    txtBrowseLabel = (TextView) findViewById(R.id.txt_browse_label);
    txtRefreshLabel = (TextView) findViewById(R.id.txt_refresh_label);
    txtSearchLabel = (TextView) findViewById(R.id.txt_search_label);
    txtSearch.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            new AsyncTask<String, Void, ArrayList<RssItem>>() {
              @Override
              protected ArrayList<RssItem> doInBackground(String... params) {
                return dbQuery.searchRssItem(params[0]);
              }

              @Override
              protected void onPostExecute(ArrayList<RssItem> result) {
                rssList.clear();
                rssList.addAll(result);
                rssAdapter.config().notifyDataSetChanged();
              }
            }.execute(s.toString());
          }

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void afterTextChanged(Editable s) {}
        });
    txtSearch.setOnKeyListener(
        new OnKeyListener() {
          @Override
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) return true;
            return false;
          }
        });
    switch (v.getId()) {
      case R.id.btn_manage:
        startActivityForResult(
            new Intent(RssReaderActivity.this, RssManageActivity.class), REQ_RSS_MANAGE);
        break;

      case R.id.btn_browse:
        rssProvider = dbQuery.getRssProviderList(null);
        int length = rssProvider.getProviderNames().length;
        if (length == 0) break;

        String[] providers = new String[length + 1];
        providers[0] = "All";
        for (int i = 0; i < length; i++) providers[i + 1] = rssProvider.getProviderNames()[i];
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
            .setTitle(R.string.rss_choose_provider)
            .setItems(
                providers,
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int item) {
                    if (item == 0) {
                      loadData(null, true, false, false);
                      return;
                    }
                    loadData(rssProvider.getProviderNames()[item - 1], false, false, false);
                    curProvider = item - 1;
                    updateListView();
                  }
                });
        builder.create().show();
        break;

      case R.id.btn_refresh:
        if (curProvider == -1) loadData(null, true, true, true);
        else
          loadData(
              dbQuery.getRssProviderList(null).getProviderNames()[curProvider], false, true, true);
        break;

      case R.id.btn_search:
        if (txtSearchLabel.getText().toString().equals(getString(R.string.btn_search_text))) {
          btnManage.setVisibility(View.GONE);
          txtManageLabel.setVisibility(View.GONE);
          btnBrowse.setVisibility(View.GONE);
          txtBrowseLabel.setVisibility(View.GONE);
          btnRefresh.setVisibility(View.GONE);
          txtRefreshLabel.setVisibility(View.GONE);
          btnSearch.setBackgroundResource(R.drawable.btn_done_background);
          txtSearchLabel.setText(R.string.btn_done_text);
          txtSearch.setVisibility(View.VISIBLE);
          txtSearch.requestFocus();
        } else {
          btnManage.setVisibility(View.VISIBLE);
          txtManageLabel.setVisibility(View.VISIBLE);
          btnBrowse.setVisibility(View.VISIBLE);
          txtBrowseLabel.setVisibility(View.VISIBLE);
          btnRefresh.setVisibility(View.VISIBLE);
          txtRefreshLabel.setVisibility(View.VISIBLE);
          btnSearch.setBackgroundResource(R.drawable.btn_search_background);
          txtSearchLabel.setText(R.string.btn_search_text);
          txtSearch.setVisibility(View.GONE);
          txtSearch.setText("");
          loadData(null, true, false, false);
        }
        break;
      default:
        break;
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.account_setup_incoming);

    mUsernameView = (EditText) findViewById(R.id.account_username);
    mPasswordView = (EditText) findViewById(R.id.account_password);
    mClientCertificateSpinner =
        (ClientCertificateSpinner) findViewById(R.id.account_client_certificate_spinner);
    mClientCertificateLabelView = (TextView) findViewById(R.id.account_client_certificate_label);
    mPasswordLabelView = (TextView) findViewById(R.id.account_password_label);
    TextView serverLabelView = (TextView) findViewById(R.id.account_server_label);
    mServerView = (EditText) findViewById(R.id.account_server);
    mPortView = (EditText) findViewById(R.id.account_port);
    mSecurityTypeView = (Spinner) findViewById(R.id.account_security_type);
    mAuthTypeView = (Spinner) findViewById(R.id.account_auth_type);
    mImapAutoDetectNamespaceView = (CheckBox) findViewById(R.id.imap_autodetect_namespace);
    mImapPathPrefixView = (EditText) findViewById(R.id.imap_path_prefix);
    mWebdavPathPrefixView = (EditText) findViewById(R.id.webdav_path_prefix);
    mWebdavAuthPathView = (EditText) findViewById(R.id.webdav_auth_path);
    mWebdavMailboxPathView = (EditText) findViewById(R.id.webdav_mailbox_path);
    mNextButton = (Button) findViewById(R.id.next);
    mCompressionMobile = (CheckBox) findViewById(R.id.compression_mobile);
    mCompressionWifi = (CheckBox) findViewById(R.id.compression_wifi);
    mCompressionOther = (CheckBox) findViewById(R.id.compression_other);
    // mSubscribedFoldersOnly = (CheckBox)findViewById(R.id.subscribed_folders_only);
    mRequiresCellular = (CheckBox) findViewById(R.id.account_requires_cellular);
    mAccountName = (EditText) findViewById(R.id.account_name);

    mNextButton.setOnClickListener(this);

    mImapAutoDetectNamespaceView.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mImapPathPrefixView.setEnabled(!isChecked);
            if (isChecked && mImapPathPrefixView.hasFocus()) {
              mImapPathPrefixView.focusSearch(View.FOCUS_UP).requestFocus();
            } else if (!isChecked) {
              mImapPathPrefixView.requestFocus();
            }
          }
        });

    mAuthTypeAdapter = AuthTypeAdapter.get(this);
    mAuthTypeView.setAdapter(mAuthTypeAdapter);

    /*
     * Only allow digits in the port field.
     */
    mPortView.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

    String accountUuid = getIntent().getStringExtra(EXTRA_ACCOUNT);
    mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
    // mMakeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false);

    /*
     * If we're being reloaded we override the original account with the one
     * we saved
     */
    if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_ACCOUNT)) {
      accountUuid = savedInstanceState.getString(EXTRA_ACCOUNT);
      mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
    }

    boolean editSettings = Intent.ACTION_EDIT.equals(getIntent().getAction());

    try {
      ServerSettings settings = RemoteStore.decodeStoreUri(mAccount.getStoreUri());

      if (savedInstanceState == null) {
        // The first item is selected if settings.authenticationType is null or is not in
        // mAuthTypeAdapter
        mCurrentAuthTypeViewPosition =
            mAuthTypeAdapter.getAuthPosition(settings.authenticationType);
      } else {
        mCurrentAuthTypeViewPosition = savedInstanceState.getInt(STATE_AUTH_TYPE_POSITION);
      }
      mAuthTypeView.setSelection(mCurrentAuthTypeViewPosition, false);
      updateViewFromAuthType();

      if (settings.username != null) {
        mUsernameView.setText(settings.username);
      }

      if (settings.password != null) {
        mPasswordView.setText(settings.password);
      }

      if (settings.clientCertificateAlias != null) {
        mClientCertificateSpinner.setAlias(settings.clientCertificateAlias);
      }

      mStoreType = settings.type;
      if (Type.POP3 == settings.type) {
        serverLabelView.setText(R.string.account_setup_incoming_pop_server_label);
        findViewById(R.id.imap_path_prefix_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_advanced_header).setVisibility(View.GONE);
        findViewById(R.id.webdav_mailbox_alias_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_owa_path_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_auth_path_section).setVisibility(View.GONE);
        findViewById(R.id.compression_section).setVisibility(View.GONE);
        findViewById(R.id.compression_label).setVisibility(View.GONE);
        // mSubscribedFoldersOnly.setVisibility(View.GONE);
      } else if (Type.IMAP == settings.type) {
        serverLabelView.setText(R.string.account_setup_incoming_imap_server_label);

        ImapStoreSettings imapSettings = (ImapStoreSettings) settings;

        mImapAutoDetectNamespaceView.setChecked(imapSettings.autoDetectNamespace);
        if (imapSettings.pathPrefix != null) {
          mImapPathPrefixView.setText(imapSettings.pathPrefix);
        }

        findViewById(R.id.webdav_advanced_header).setVisibility(View.GONE);
        findViewById(R.id.webdav_mailbox_alias_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_owa_path_section).setVisibility(View.GONE);
        findViewById(R.id.webdav_auth_path_section).setVisibility(View.GONE);

        /*if (!editSettings) {
            findViewById(R.id.imap_folder_setup_section).setVisibility(View.GONE);
        }*/
      } else if (Type.WebDAV == settings.type) {
        serverLabelView.setText(R.string.account_setup_incoming_webdav_server_label);
        mConnectionSecurityChoices =
            new ConnectionSecurity[] {ConnectionSecurity.NONE, ConnectionSecurity.SSL_TLS_REQUIRED};

        // Hide the unnecessary fields
        findViewById(R.id.imap_path_prefix_section).setVisibility(View.GONE);
        findViewById(R.id.account_auth_type_label).setVisibility(View.GONE);
        findViewById(R.id.account_auth_type).setVisibility(View.GONE);
        findViewById(R.id.compression_section).setVisibility(View.GONE);
        findViewById(R.id.compression_label).setVisibility(View.GONE);
        // mSubscribedFoldersOnly.setVisibility(View.GONE);

        WebDavStoreSettings webDavSettings = (WebDavStoreSettings) settings;

        if (webDavSettings.path != null) {
          mWebdavPathPrefixView.setText(webDavSettings.path);
        }

        if (webDavSettings.authPath != null) {
          mWebdavAuthPathView.setText(webDavSettings.authPath);
        }

        if (webDavSettings.mailboxPath != null) {
          mWebdavMailboxPathView.setText(webDavSettings.mailboxPath);
        }
      } else {
        throw new Exception("Unknown account type: " + mAccount.getStoreUri());
      }

      if (!editSettings) {
        mAccount.setDeletePolicy(AccountCreator.getDefaultDeletePolicy(settings.type));
      }

      // Note that mConnectionSecurityChoices is configured above based on server type
      ConnectionSecurityAdapter securityTypesAdapter =
          ConnectionSecurityAdapter.get(this, mConnectionSecurityChoices);
      mSecurityTypeView.setAdapter(securityTypesAdapter);

      // Select currently configured security type
      if (savedInstanceState == null) {
        mCurrentSecurityTypeViewPosition =
            securityTypesAdapter.getConnectionSecurityPosition(settings.connectionSecurity);
      } else {

        /*
         * Restore the spinner state now, before calling
         * setOnItemSelectedListener(), thus avoiding a call to
         * onItemSelected(). Then, when the system restores the state
         * (again) in onRestoreInstanceState(), The system will see that
         * the new state is the same as the current state (set here), so
         * once again onItemSelected() will not be called.
         */
        mCurrentSecurityTypeViewPosition = savedInstanceState.getInt(STATE_SECURITY_TYPE_POSITION);
      }
      mSecurityTypeView.setSelection(mCurrentSecurityTypeViewPosition, false);

      updateAuthPlainTextFromSecurityType(settings.connectionSecurity);

      mCompressionMobile.setChecked(mAccount.useCompression(NetworkType.MOBILE));
      mCompressionWifi.setChecked(mAccount.useCompression(NetworkType.WIFI));
      mCompressionOther.setChecked(mAccount.useCompression(NetworkType.OTHER));

      if (settings.host != null) {
        mServerView.setText(settings.host);
      }

      if (settings.port != -1) {
        mPortView.setText(Integer.toString(settings.port));
      } else {
        updatePortFromSecurityType();
      }
      mCurrentPortViewSetting = mPortView.getText().toString();

      // mSubscribedFoldersOnly.setChecked(mAccount.subscribedFoldersOnly());
    } catch (Exception e) {
      failure(e);
    }
    // show & populate setup fields
    if (!Intent.ACTION_EDIT.equals(getIntent().getAction())) {
      findViewById(R.id.account_name_label).setVisibility(View.VISIBLE);
      mAccountName.setVisibility(View.VISIBLE);
      String desc = mAccount.getDescription();
      mAccountName.setText((desc != null ? desc : ""));
      findViewById(R.id.account_requires_cellular_label).setVisibility(View.VISIBLE);
      mRequiresCellular.setVisibility(View.VISIBLE);
      mRequiresCellular.setChecked(true);
    }
  }
    @Override
    public View onCreateView(
        LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View rootView = inflater.inflate(R.layout.fragment_user_crud, container, false);

      editTextUserName = (EditText) rootView.findViewById(R.id.editTextUserName);
      editTextEmail = (EditText) rootView.findViewById(R.id.editTextEmail);
      editTextLogin = (EditText) rootView.findViewById(R.id.editTextLogin);
      editTextPassword = (EditText) rootView.findViewById(R.id.editTextPassword);
      editTextConfirmPassword = (EditText) rootView.findViewById(R.id.editTextConfirmPassword);
      editTextZipCode = (EditText) rootView.findViewById(R.id.editTextZipCode);
      editTextAddress = (EditText) rootView.findViewById(R.id.editTextAddress);
      editTextNumberAddress = (EditText) rootView.findViewById(R.id.editTextNumberAddress);
      editTextComplement = (EditText) rootView.findViewById(R.id.editTextComplement);
      editTextNeighborhood = (EditText) rootView.findViewById(R.id.editTextNeighborhood);
      editTextCity = (EditText) rootView.findViewById(R.id.editTextCity);
      txtLatitude = (TextView) rootView.findViewById(R.id.txtLatitude);
      txtLongitude = (TextView) rootView.findViewById(R.id.txtLongitude);
      radioGroupGender = (RadioGroup) rootView.findViewById(R.id.radioGender);
      spinnerStates = (Spinner) rootView.findViewById(R.id.spinnerStates);
      btnSearchZipCode = (Button) rootView.findViewById(R.id.btnSearchZipCode);
      btnSaveUser = (Button) rootView.findViewById(R.id.btnSaveUser);

      ArrayAdapter arrayAdapterStates =
          new ArrayAdapter(getActivity(), R.layout.support_simple_spinner_dropdown_item, states);
      spinnerStates.setPrompt("Estados");
      spinnerStates.setAdapter(arrayAdapterStates);
      spinnerStates.setOnItemSelectedListener(
          new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
              if (position > 0) {
                String state = (String) spinnerStates.getItemAtPosition(position);
                spinnerStates.setSelection(states.indexOf(state));
              }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
              Toast.makeText(
                      getActivity(), "É necessário selecionar uma Categoria", Toast.LENGTH_SHORT)
                  .show();
            }
          });

      if (getActivity().getIntent().getSerializableExtra("user") != null) {
        UserBean userBeanLoad = (UserBean) getActivity().getIntent().getSerializableExtra("user");
        editTextUserName.setText(userBeanLoad.getUserName());
        editTextEmail.setText(userBeanLoad.getEmail());
        editTextLogin.setText(userBeanLoad.getLogin());
        editTextPassword.setVisibility(View.INVISIBLE);
        editTextConfirmPassword.setVisibility(View.INVISIBLE);
        editTextZipCode.setText(userBeanLoad.getZipCode());
        editTextAddress.setText(userBeanLoad.getAddress());
        editTextNumberAddress.setText(userBeanLoad.getNumberAddress());
        editTextComplement.setText(userBeanLoad.getComplement());
        editTextNeighborhood.setText(userBeanLoad.getNeighborhood());
        editTextCity.setText(userBeanLoad.getCity());
        if (userBeanLoad.getGender().equals(UserBean.Gender.MALE.getSex())) {
          radioButtonGender = (RadioButton) rootView.findViewById(R.id.radioMale);
          radioButtonGender.setChecked(true);
        } else {
          radioButtonGender = (RadioButton) rootView.findViewById(R.id.radioFemale);
          radioButtonGender.setChecked(true);
        }

        spinnerStates.setSelection(states.indexOf(userBeanLoad.getState()));
        getActivity()
            .getWindow()
            .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        btnSaveUser.setTag(userBeanLoad);
      }

      btnSaveUser.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              progressDialog =
                  ProgressDialog.show(getActivity(), "Processando", "Salvando usuário...");

              if (view.getTag() != null) {
                userBean = (UserBean) view.getTag();
              } else {
                userBean = new UserBean();
              }

              int selectedId = radioGroupGender.getCheckedRadioButtonId();
              switch (selectedId) {
                case R.id.radioFemale:
                  userBean.setGender(UserBean.Gender.FEMALE.getSex());
                  break;
                case R.id.radioMale:
                  userBean.setGender(UserBean.Gender.MALE.getSex());
                  break;
              }

              userBean.setUserName(editTextUserName.getText().toString());
              userBean.setEmail(editTextEmail.getText().toString());
              userBean.setLogin(editTextLogin.getText().toString());
              userBean.setPassword(editTextPassword.getText().toString());
              userBean.setZipCode(editTextZipCode.getText().toString());
              userBean.setAddress(editTextAddress.getText().toString());
              userBean.setNumberAddress(editTextNumberAddress.getText().toString());
              userBean.setComplement(editTextComplement.getText().toString());
              userBean.setNeighborhood(editTextNeighborhood.getText().toString());
              userBean.setCity(editTextCity.getText().toString());

              userBean.setState(spinnerStates.getSelectedItem().toString());

              AsyncTask<Void, Void, JSONObject> task =
                  new AsyncTask<Void, Void, JSONObject>() {

                    @Override
                    protected JSONObject doInBackground(Void... voids) {
                      Http http = new Http();
                      try {
                        StringBuilder strAddress = new StringBuilder();
                        strAddress.append(editTextAddress.getText().toString()).append(" ");
                        strAddress.append(editTextNumberAddress.getText().toString()).append(" ");
                        strAddress.append(editTextCity.getText().toString()).append(" ");
                        strAddress.append(spinnerStates.getSelectedItem().toString());

                        String result =
                            http.doGet(
                                PAGE_MAPS
                                    + URLEncoder.encode(strAddress.toString(), "UTF-8")
                                    + "&sensor=true");

                        JSONObject jsonObject = new JSONObject(result);

                        if (jsonObject.getString("status").equals("OK")) {
                          JSONArray jsonArrayResults = jsonObject.getJSONArray("results");
                          for (int i = 0; i < jsonArrayResults.length(); i++) {
                            JSONObject jsonObjectResults = jsonArrayResults.getJSONObject(i);
                            if (jsonObjectResults.get("geometry") != null) {
                              JSONObject jsonObjectGeometry =
                                  jsonObjectResults.getJSONObject("geometry");
                              return (JSONObject) jsonObjectGeometry.get("location");
                            }
                          }
                        }

                      } catch (IOException e1) {
                        Log.e(AppHelper.getClassError(UserCrudActivity.class), e1.getMessage());
                      } catch (JSONException e2) {
                        Log.e(AppHelper.getClassError(UserCrudActivity.class), e2.getMessage());
                      }

                      return null;
                    }

                    @Override
                    protected void onPostExecute(JSONObject jsonObject) {
                      super.onPostExecute(jsonObject);

                      boolean cepOK = true;
                      if (jsonObject == null || jsonObject.isNull("lng")) {
                        cepOK = false;
                        Toast.makeText(getActivity(), "CEP inexistente.", Toast.LENGTH_SHORT)
                            .show();
                      } else {
                        try {
                          userBean.setLatitude(jsonObject.get("lat").toString());
                          userBean.setLongitude(jsonObject.get("lng").toString());

                          boolean create = userBean.getId() == null ? true : false;

                          UserDB userDB = new UserDB(getActivity());
                          userBean = userDB.salvar(userBean);

                          if (userBean != null) {
                            Intent it = new Intent();
                            it.putExtra(
                                "msg",
                                create
                                    ? "Usuário salvo com sucesso!"
                                    : "Usuário atualizado com sucesso!");
                            it.putExtra("user", userBean);
                            getActivity().setResult(RESULT_OK, it);
                            getActivity().finish();
                          } else {
                            Intent it = new Intent();
                            it.putExtra(
                                "msg",
                                create
                                    ? "Falha ao cadastrar o Usuário!"
                                    : "Falha ao atualizar Usuário!");
                            getActivity().setResult(RESULT_CANCELED, it);
                            getActivity().finish();
                          }

                        } catch (JSONException e3) {
                          Log.e(AppHelper.getClassError(UserCrudActivity.class), e3.getMessage());
                        }
                      }

                      if (cepOK) {
                        UserDB userDB = new UserDB(getActivity());
                        userBean = userDB.salvar(userBean);
                        if (userBean != null) {
                          Intent it = new Intent();
                          it.putExtra(
                              "msg",
                              userBean.getId() == null
                                  ? "Usuário salvo com sucesso!"
                                  : "Usuário atualizado com sucesso!");
                          it.putExtra("user", userBean);
                          getActivity().setResult(RESULT_OK, it);
                          getActivity().finish();
                        } else {
                          Intent it = new Intent();
                          it.putExtra(
                              "msg",
                              userBean.getId() == null
                                  ? "Falha ao cadastrar o Usuário!"
                                  : "Falha ao atualizar Usuário!");
                          getActivity().setResult(RESULT_CANCELED, it);
                          getActivity().finish();
                        }
                      }
                    }
                  };

              if (validateFields(userBean)) {
                task.execute();
              }

              progressDialog.dismiss();
            }
          });

      btnSearchZipCode.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              progressDialog = ProgressDialog.show(getActivity(), "Pesquisando", "Carregando...");
              AsyncTask<Void, Void, JSONObject> task =
                  new AsyncTask<Void, Void, JSONObject>() {
                    @Override
                    protected JSONObject doInBackground(Void... params) {

                      Http http = new Http();
                      try {
                        String result =
                            http.doGet(PAGE_CORREIOS + editTextZipCode.getText().toString());
                        JSONObject jsonObject = new JSONObject(result);
                        if (!jsonObject.has("message")) {
                          return jsonObject;
                        }

                      } catch (IOException e1) {
                        Log.e(AppHelper.getClassError(UserCrudActivity.class), e1.getMessage());
                      } catch (JSONException e2) {
                        Log.e(AppHelper.getClassError(UserCrudActivity.class), e2.getMessage());
                      }

                      return null;
                    }

                    @Override
                    protected void onPostExecute(JSONObject jsonObject) {
                      if (jsonObject == null) {
                        Toast.makeText(getActivity(), "CEP inexistente.", Toast.LENGTH_SHORT)
                            .show();
                      } else {
                        try {
                          editTextAddress.setText(
                              jsonObject.get("tipoDeLogradouro")
                                  + " "
                                  + jsonObject.get("logradouro"));
                          editTextNeighborhood.setText(jsonObject.get("bairro").toString());
                          editTextCity.setText(jsonObject.get("cidade").toString());
                          spinnerStates.setSelection(
                              states.indexOf(jsonObject.get("estado").toString()));
                        } catch (JSONException e3) {
                          Log.e(AppHelper.getClassError(UserCrudActivity.class), e3.getMessage());
                        }
                      }
                      progressDialog.dismiss();
                    }
                  };
              task.execute();
            }
          });

      return rootView;
    }