Ver mensagens sem resposta | Ver tópicos ativos Hoje é 10 Dez 2019, 10:16



Responder Tópico  [ 1 Mensagem ] 
 Ajuda - Campo quando atualiza duplica na base de dados 
Autor Mensagem
What is Android?
What is Android?

Data de registro: 17 Abr 2018, 03:47
Mensagens: 2
Mensagem Ajuda - Campo quando atualiza duplica na base de dados
A classe birthday é o problema, quando eu vou atualizar o campo cujo a classe birthday está vinculada ele duplica os dados. Alguém pode me ajudar a analizar o erro no código a baixo?
Agradeço desde ja pela ajuda.


package com.android.faced.activities;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.faced.R;
import com.android.faced.connection.NetworkUtils;
import com.android.faced.data.Preferences;
import com.android.faced.model.User;
import com.android.faced.util.ImageUtil;
import com.android.faced.view.CpfEditText;
import com.android.faced.view.DateEditText;
import com.android.faced.view.EmailEditText;
import com.google.firebase.crash.FirebaseCrash;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

public class ChangeRegisterActivity extends BaseActivity {

    private static final String TAG = ChangeRegisterActivity.class.getSimpleName();

    ImageView pictureImageView;
    EditText nameEditText;
    CpfEditText cpfEditText;
    EmailEditText emailEditText;
    EditText dddEditText;
    EditText phoneNumberEditText;
    DateEditText birthdayEditText;
    EditText addressEditText;
    EditText numberEditText;
    EditText complementEditText;
    EditText neighborhoodEditText;
    Spinner stateSpinner;
    EditText cityEditText;

    Button saveButton;

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            validateInput();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_register);

        Toolbar toolbarView = findViewById(R.id.toolbar);

        if (null != toolbarView) {
            setSupportActionBar(toolbarView);

            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {

                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);

            }
        }

        User user = Preferences.getUser(this);

        if(user != null) {
            pictureImageView = findViewById(R.id.picture_img);
            nameEditText = findViewById(R.id.complete_name);
            cpfEditText = findViewById(R.id.cpf);
            emailEditText = findViewById(R.id.email);
            dddEditText = findViewById(R.id.ddd);
            phoneNumberEditText = findViewById(R.id.phone_number);
            birthdayEditText = findViewById(R.id.birthday);
            addressEditText = findViewById(R.id.address);
            numberEditText = findViewById(R.id.address_number);
            complementEditText = findViewById(R.id.complement);
            neighborhoodEditText =findViewById(R.id.neighborhood);
            stateSpinner = findViewById(R.id.state);
            cityEditText =findViewById(R.id.city);
            saveButton = findViewById(R.id.save_button);

            nameEditText.addTextChangedListener(mTextWatcher);
            cpfEditText.addTextChangedListener(mTextWatcher);
            emailEditText.addTextChangedListener(mTextWatcher);
            dddEditText.addTextChangedListener(mTextWatcher);
            phoneNumberEditText.addTextChangedListener(mTextWatcher);
            birthdayEditText.addTextChangedListener(mTextWatcher);
            addressEditText.addTextChangedListener(mTextWatcher);
            numberEditText.addTextChangedListener(mTextWatcher);
            neighborhoodEditText.addTextChangedListener(mTextWatcher);
            cityEditText.addTextChangedListener(mTextWatcher);

            nameEditText.setText(user.getName());
            cpfEditText.setText(user.getCpf());
            emailEditText.setText(user.getEmail());
            dddEditText.setText(user.getPhoneCode());
            phoneNumberEditText.setText(user.getPhone());
            birthdayEditText.SetText(user.getBirthday());
            addressEditText.setText(user.getAddressStreet());
            numberEditText.setText(user.getAddressNumber());
            complementEditText.setText(user.getAddressComplement());
            neighborhoodEditText.setText(user.getAddressNeighborhood());
            selectSpinnerValue(stateSpinner, user.getAddressState());
            cityEditText.setText(user.getAddressCity());

        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        Bitmap pictureBitmap = ImageUtil.getBitmapFromFile(getExternalFilesDir(null).getAbsolutePath() + "/pic.jpg");
        Resources res = getResources();
        RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, pictureBitmap);
        dr.setCircular(true);
        pictureImageView.setImageDrawable(dr);
    }

    private void selectSpinnerValue(Spinner spinner, String myString) {
        for(int i = 0; i < spinner.getCount(); i++){
            if(spinner.getItemAtPosition(i).toString().equals(myString)){
                spinner.setSelection(i);
                break;
            }
        }
    }

    private void validateInput() {
        boolean hasName = nameEditText.length() > 0;
        boolean hasCpf = cpfEditText.isValid();
        boolean hasEmail = emailEditText.length() > 0 && emailEditText.isValid();
        boolean hasPhoneCode = dddEditText.length() > 0;
        boolean hasPhone = phoneNumberEditText.length() > 0;
        boolean hasBirthday = birthdayEditText.isValidDate();

        boolean hasStreet = addressEditText.length() > 0;
        boolean hasNumber = numberEditText.length() > 0;
        boolean hasNeighborhood = neighborhoodEditText.length() > 0;
        boolean hasCity = cityEditText.length() > 0;
        boolean hasState = ((String) stateSpinner.getSelectedItem()).length() > 0;

        if (hasName && hasCpf && hasEmail && hasPhone && hasPhoneCode && hasBirthday && hasStreet &&
                hasNumber && hasNeighborhood && hasCity && hasState) {
            saveButton.setEnabled(true);
        } else {
            saveButton.setEnabled(false);
        }
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void editPicture(View view) {
        Intent intent = new Intent(ChangeRegisterActivity.this, RegisterPhotoActivity.class);
        intent.putExtra(RegisterPhotoActivity.CHANGE_PICTURE_EXTRA, true);

        startActivity(intent);
    }

    public void save(View view) {
        User user = buildUser();
        if(NetworkUtils.hasInternetConnection(this)) {
            new RegisterAsyncTask().execute(user.toJsonString());
        } else {
            Toast.makeText(this, R.string.no_internet_msg, Toast.LENGTH_LONG).show();
        }
    }

    private User buildUser() {
        User user = new User();
        user.setName(nameEditText.getText().toString());
        user.setCpf(cpfEditText.getText().toString());
        user.setEmail(emailEditText.getText().toString());
        user.setPhoneCode(dddEditText.getText().toString());
        user.setPhone(phoneNumberEditText.getText().toString());
        user.setBirthday(birthdayEditText.getText().toString());
        user.setAddressStreet(addressEditText.getText().toString());
        user.setAddressNumber(numberEditText.getText().toString());
        user.setAddressNeighborhood(neighborhoodEditText.getText().toString());
        user.setAddressCity(cityEditText.getText().toString());
        user.setAddressState((String) stateSpinner.getSelectedItem());
        return user;
    }

    private class RegisterAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            String userJsonObject = strings[0];

            try {
                URL url = NetworkUtils.getUserRegisterURL();

                return NetworkUtils.doPost(url, userJsonObject);
            } catch (MalformedURLException e) {
                Log.e(TAG, "MalformedURLException while trying to register the user", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);

            if(TextUtils.isEmpty(response)) {
                Toast.makeText(ChangeRegisterActivity.this, R.string.change_register_error_msg, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                JSONObject responseJson = new JSONObject(response);
                int status = responseJson.getInt("status");

                if(status == 200) {
                    User user = new User(responseJson.getJSONObject("user"));
                    Preferences.saveUser(ChangeRegisterActivity.this, user);
                    ChangeRegisterActivity.this.finish();
                } else {
                    // TODO show dialog handling error
                    Toast.makeText(ChangeRegisterActivity.this, responseJson.getString("message"), Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                Log.e(TAG, "JSONException while parsing change register response", e);
                FirebaseCrash.report(e);
            }
        }
    }
}
 


24 Abr 2018, 12:23
Perfil
Mostrar mensagens anteriores:  Organizar por  
Responder Tópico   [ 1 Mensagem ] 

Quem está online

Usuários vendo este fórum: adilson.afl, adolfo, akaytatsu, alberto, alexandrefett, allone, arquivo51, Arthas, AT-AT, axellsan, beeshop, bigr ecreio, blurkness, BMaia, caio, Cajux, canaville, Carlos Alexandre, cehills, Chassot, cleberkct, Cr-Informática, culumin, d.paim, danielbfranco, danilosouza, Darth Sidious, dmd, drjunior, dudu795, Eduardo - Brasil, Erik Patekoski, erosvaldo, estratec, euguns, eXagon, fabiano_eletro, gamito, Geovanne Duarte, grandebaro, gustavo, icarodavi, Ielo8, ismavolk, jairo, jairodealmeida, JAndroid, jhhm_2008, JMurray, johnnyjx, João Miguel Aguiar, jrsilva, juliancesar, Juliobcosta, Katia, Leonardo, Leonardo333, LForce, loferreira, Lord, lucianno, Lucious, luizcesar, maiconjunches, marcelocastellani, marcow, marinho5, mateusff, monteirojp, MSPRAFAEL, nina.rm, nino, nivaldo, Nute Gunray, obitow, oliverlessa, osternack, otpor, paulabr, paulovaz, pemam.com.br, pfsmorigo, phfmendes, pingumanbr, Rafael Alencar, ramonsiebra, raulcca, rayberg, regeriob2br, renan.fernandes, renata, retardad0, rfrafa, Ricardo Chikasawa, Roberto, rodrigo_corinthians, rsl_master, Rufino, ruizsa, sandro, schiroky, Shaman286, Shmi Skywalker, Silvio Vaz, sjta, sobrinho, Thiago, thiago20, Thitto, tiagofalcao, tiasousa, tnarnold, tonholis, unnamedd, vaniuz, vicfalmac, viniciusgoncalves, viniciusllima, wagner_francisco, Wds, yuri82, zorieuq e 22 visitantes


Você não pode criar novos tópicos neste fórum
Você não pode responder tópicos neste fórum
Você não pode editar suas mensagens neste fórum
Você não pode excluir suas mensagens neste fórum
Você não pode enviar anexos neste fórum

Procurar por:

© 2007 - 2016 Portal Android - Comunidade de Desenvolvedores Android

Estamos no Linkedin    Siga-nos no twitter


Powered by phpBB - Hospedado por Bemobi