• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Help - Field when update doubles in database

The birthday class is the problem, when I update the field whose birthday class is linked it duplicates the data. Can anyone help me analyze the error in the code below?
Thank you in advance for your help.

Code:
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);
            }
        }
    }
}
 
What do you mean "duplicates" data in database.
Please provide "POST" string that you use to store data in database.
And the code of User Class.
 
NetworkUtils

Code:
package com.android.faced.connection;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.google.firebase.crash.FirebaseCrash;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class NetworkUtils {

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

    private static final String BASE_ENDPOINT = "https://www.facedapp.com/marangoniapp/rest";

    private static final String REGISTER_ENDPOINT = BASE_ENDPOINT+"/user";

    private static final String REGISTER_FACE_PLUS_ENDPOINT = BASE_ENDPOINT+"/images";

    private static final String PAYMENT_ENDPOINT = BASE_ENDPOINT+"/payment/getCardsForUser/controlPayId";

    private static final String GET_TOKENIZATION_ENDPOINT = BASE_ENDPOINT+"/payment/getTokenizationURL";

    private static final String REGISTER_NOTIFICATION_TOKEN_ENDPOINT = BASE_ENDPOINT+"/user/updateToken";

    private static final String GET_PENDENCIES_ENDPOINT = BASE_ENDPOINT+"/pendency";

    private static final String GET_HISTORY_ENDPOINT = BASE_ENDPOINT+"/pendency/history";

    private static final String CONFIRM_SALE_PENDENCY_ENDPOINT = BASE_ENDPOINT+"/payment/userConfirmSale";

    private static final String CEP_ENDPOINT = BASE_ENDPOINT+"/address";


    public static URL getUserRegisterURL() throws MalformedURLException {
        return new URL(REGISTER_ENDPOINT);
    }

    public static URL getFacePlusRegisterURL() throws MalformedURLException {
        return new URL(REGISTER_FACE_PLUS_ENDPOINT);
    }

    public static URL getCardsURL(String controlPayId) throws MalformedURLException {
        return new URL(PAYMENT_ENDPOINT+"/"+controlPayId);
    }

    public static URL getTokenizationURL(String controlPayId, long cardId) throws MalformedURLException {
        String endpoint = GET_TOKENIZATION_ENDPOINT;
        endpoint += "?controlPayId="+controlPayId;
        if(cardId > 0) {
            endpoint += "&cardId="+cardId;
        }
        return new URL(endpoint);
    }

    public static URL getRegistrationTokenURL(long userId, String token) throws MalformedURLException {
        String endpoint = REGISTER_NOTIFICATION_TOKEN_ENDPOINT;
        endpoint += "/userId/" + userId + "/token/" + token;
        return new URL(endpoint);
    }

    public static URL getUserPendenciesURL(long userId) throws MalformedURLException {
        String endpoint = GET_PENDENCIES_ENDPOINT;
        endpoint += "/userId/"+userId;
        return new URL(endpoint);
    }

    public static URL getPendencyURL(int pendencyId) throws MalformedURLException {
        String endpoint = GET_PENDENCIES_ENDPOINT;
        endpoint += "/"+pendencyId;
        return new URL(endpoint);
    }

    public static URL getConfirmSalePendencyURL(int pendencyId, int status) throws MalformedURLException {
        String endpoint = CONFIRM_SALE_PENDENCY_ENDPOINT;
        endpoint += "/pendencyId/"+pendencyId+"/status/"+status;
        return new URL(endpoint);
    }

    public static URL getHistoryURL(long userId) throws MalformedURLException {
        String endpoint = GET_HISTORY_ENDPOINT;
        endpoint += "/userId/"+userId;
        return new URL(endpoint);
    }

    public static URL getSearchCepURL(String cep) throws MalformedURLException {
        String endpoint = CEP_ENDPOINT;
        endpoint += "/"+cep;
        return new URL(endpoint);
    }

    public static boolean hasInternetConnection(Context context) {
        ConnectivityManager cm =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null &&
                activeNetwork.isConnectedOrConnecting();
    }

    public static String doPost(URL url, String requestString) {

        HttpURLConnection urlConnection;
        BufferedReader reader;

        String responseString;

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Content-Type","application/json");

            urlConnection.connect();

            // Send POST request
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            bw.write(requestString);
            bw.flush();
            bw.close();

            StringBuilder buffer = new StringBuilder();

            InputStream errorMessageStream = urlConnection.getErrorStream();
            if(errorMessageStream != null) {
                reader = new BufferedReader(new InputStreamReader(errorMessageStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    // Adiciona quebra de linha pra facilitar debug
                    buffer.append(line).append("\n");
                }
            }

            if(buffer.length() == 0) {
                try {
                    InputStream inputStream = urlConnection.getInputStream();
                    if (inputStream != null) {
                        reader = new BufferedReader(new InputStreamReader(inputStream));

                        String line;
                        while ((line = reader.readLine()) != null) {
                            // Add line break to facilitate debugging
                            buffer.append(line).append("\n");
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, "IOException while trying to connect with server", e);
                    FirebaseCrash.report(e);
                }
            }


            if (buffer.length() == 0) {
                return null;
            }
            responseString = buffer.toString();

            Log.d(TAG, "Response = "+responseString);

            return responseString;

        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException while trying to connect with server", e);
            FirebaseCrash.report(e);
        } catch (IOException e) {
            Log.e(TAG, "IOException while trying to connect with server", e);
            FirebaseCrash.report(e);
        }

        return null;
    }

    public static String doGet(URL url) {

        HttpURLConnection urlConnection;
        BufferedReader reader;

        String responseString;

        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            StringBuilder buffer = new StringBuilder();

            InputStream errorMessageStream = urlConnection.getErrorStream();

            if(errorMessageStream != null) {
                reader = new BufferedReader(new InputStreamReader(errorMessageStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    // Add line break to facilitate debugging
                    buffer.append(line).append("\n");
                }
            }

            if(buffer.length() == 0) {
                try {
                    InputStream inputStream = urlConnection.getInputStream();
                    if (inputStream != null) {
                        reader = new BufferedReader(new InputStreamReader(inputStream));

                        String line;
                        while ((line = reader.readLine()) != null) {
                            // Add line break to facilitate debugging
                            buffer.append(line).append("\n");
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, "IOException while trying to connect with server", e);
                    FirebaseCrash.report(e);
                }
            }

            if (buffer.length() == 0) {
                return null;
            }
            responseString = buffer.toString();

            Log.d(TAG, "Response = "+responseString);

            return responseString;

        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException while trying to connect with server", e);
            FirebaseCrash.report(e);
        } catch (IOException e) {
            Log.e(TAG, "IOException while trying to connect with server", e);
            FirebaseCrash.report(e);
        }

        return null;
    }
}


Preferences

Code:
package com.android.faced.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.android.faced.R;
import com.android.faced.model.User;

/**
* How only one user can be registered in the application
* We use SharedPreferences to do persistence
* of data
*/
public class Preferences {

    /**
     * Saves a user to SharedPreferences
     *
     * @param context
     * @param user
     */
    public static void saveUser(Context context, User user) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        String userIdPrefKey = getPrefKey(context, R.string.pref_user_id);
        String userNamePrefKey = getPrefKey(context, R.string.pref_user_name);
        String cpfPrefKey = getPrefKey(context, R.string.pref_user_cpf);
        String emailPrefKey = getPrefKey(context, R.string.pref_user_email);
        String phoneCodePrefKey = getPrefKey(context, R.string.pref_user_phone_code);
        String phoneNumberPrefKey = getPrefKey(context, R.string.pref_user_phone_number);
        String addressStreetPrefKey = getPrefKey(context, R.string.pref_user_address_street);
        String addressNumberPrefKey = getPrefKey(context, R.string.pref_user_address_number);
        String addressNeighborhoodPrefKey = getPrefKey(context, R.string.pref_user_address_neighborhood);
        String addressCityPrefKey = getPrefKey(context, R.string.pref_user_address_city);
        String addressStatePrefKey = getPrefKey(context, R.string.pref_user_address_state);
        String idFacePlusPrefKey = getPrefKey(context, R.string.pref_id_face_plus);
        String controlPayIdPrefKey = getPrefKey(context, R.string.pref_control_pay_id);
        String pushIdPrefKey = getPrefKey(context, R.string.pref_push_id);


        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong(userIdPrefKey, user.getId());
        editor.putString(userNamePrefKey, user.getName());
        editor.putString(cpfPrefKey, user.getCpf());
        editor.putString(emailPrefKey, user.getEmail());
        editor.putString(phoneCodePrefKey, user.getPhoneCode());
        editor.putString(phoneNumberPrefKey, user.getPhone());
        editor.putString(addressStreetPrefKey, user.getAddressStreet());
        editor.putString(addressNumberPrefKey, user.getAddressNumber());
        editor.putString(addressNeighborhoodPrefKey, user.getAddressNeighborhood());
        editor.putString(addressCityPrefKey, user.getAddressCity());
        editor.putString(addressStatePrefKey, user.getAddressState());
        editor.putString(idFacePlusPrefKey, user.getIdFacePlus());
        editor.putString(controlPayIdPrefKey, user.getControlPayId());
        editor.putString(pushIdPrefKey, user.getPushId());
        editor.apply();
    }

    public static void saveNotificationToken(Context context, String token) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("notification-token", token);
        editor.apply();
    }

    public static String getNotificationToken(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString("notification-token", null);
    }

    public static boolean hasUser(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        String userIdPrefKey = getPrefKey(context, R.string.pref_user_id);
        long id = preferences.getLong(userIdPrefKey, -1L);

        return id > 0;
    }

    public static boolean hasFacePlusId(Context context) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        String userIdPrefKey = getPrefKey(context, R.string.pref_id_face_plus);
        String facePlusId = preferences.getString(userIdPrefKey, null);

        return facePlusId != null && !facePlusId.equals("null");
    }

    public static User getUser(Context context) {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        User user = new User();

        String userIdPrefKey = getPrefKey(context, R.string.pref_user_id);
        long id = preferences.getLong(userIdPrefKey, -1L);

        if(id > 0) {

            String userNamePrefKey = getPrefKey(context, R.string.pref_user_name);
            String cpfPrefKey = getPrefKey(context, R.string.pref_user_cpf);
            String emailPrefKey = getPrefKey(context, R.string.pref_user_email);
            String phoneCodePrefKey = getPrefKey(context, R.string.pref_user_phone_code);
            String phoneNumberPrefKey = getPrefKey(context, R.string.pref_user_phone_number);
            String addressStreetPrefKey = getPrefKey(context, R.string.pref_user_address_street);
            String addressNumberPrefKey = getPrefKey(context, R.string.pref_user_address_number);
            String addressNeighborhoodPrefKey = getPrefKey(context, R.string.pref_user_address_neighborhood);
            String addressCityPrefKey = getPrefKey(context, R.string.pref_user_address_city);
            String addressStatePrefKey = getPrefKey(context, R.string.pref_user_address_state);
            String idFacePlusPrefKey = getPrefKey(context, R.string.pref_id_face_plus);
            String controlPayIdPrefKey = getPrefKey(context, R.string.pref_control_pay_id);
            String pushIdPrefKey = getPrefKey(context, R.string.pref_push_id);

            String userName = preferences.getString(userNamePrefKey, null);
            String cpf = preferences.getString(cpfPrefKey, null);
            String email = preferences.getString(emailPrefKey, null);
            String phoneCode = preferences.getString(phoneCodePrefKey, null);
            String phoneNumber = preferences.getString(phoneNumberPrefKey, null);
            String addressStreet = preferences.getString(addressStreetPrefKey, null);
            String addressNumber = preferences.getString(addressNumberPrefKey, null);
            String addressNeighborhood = preferences.getString(addressNeighborhoodPrefKey, null);
            String addressCity = preferences.getString(addressCityPrefKey, null);
            String addressState = preferences.getString(addressStatePrefKey, null);
            String idFacePlus = preferences.getString(idFacePlusPrefKey, null);
            String controlPayId = preferences.getString(controlPayIdPrefKey, null);
            String pushId = preferences.getString(pushIdPrefKey, null);

            user.setId(id);
            user.setName(userName);
            user.setCpf(cpf);
            user.setEmail(email);
            user.setPhoneCode(phoneCode);
            user.setPhone(phoneNumber);
            user.setAddressStreet(addressStreet);
            user.setAddressNumber(addressNumber);
            user.setAddressNeighborhood(addressNeighborhood);
            user.setAddressCity(addressCity);
            user.setAddressState(addressState);
            user.setIdFacePlus(idFacePlus);
            user.setControlPayId(controlPayId);
            user.setPushId(pushId);

            return user;
        } else {
            return null;
        }
    }

    private static String getPrefKey(Context context, int prefResId) {
        return context.getString(prefResId);
    }
}
 

Attachments

  • Captura de Tela 2018-05-01 às 11.55.00.png
    Captura de Tela 2018-05-01 às 11.55.00.png
    373.1 KB · Views: 115
Last edited:
I asked about User.class, POST string and what do you mean "duplicates".
You have provided Preferences and NetworkUtils with doPost() methods which does not clarify the content of POST request :)
Method doPost() uses requestString which is created by User.class toString() method.
The picture just duplicates Preference code. May be you were going to add something else.

Well, let's try to guess and assume that:
1. User.toStgring works well and creates valid JSON string.
2. When you append JSON string in database, you get duplicated records.

I think the problem is in "write to database" method.
Every records that related to given User should be overwritten if new record related to the same User.
This problem can be solved by the two ways.
1. You can use unique String Key for the User. And to use this key as primary index of record in table of database.
2. You can use integer AutoIncrement Key for every record and manually detect if record should be added or replaced.

First way is simple. Just concatenate Key fields of User in one String. Use this String as a Key field of record.
Second way a little bit more difficult. You should find record for given User, if it exists, overwrite it. If not, append.

You have not provided information about your Database.
So I don't know, how to you do work with your database.
What do you mean when you say "duplicates".
What structure of record in your database.
What structure of your POST request.

Please read text above and may be this helps.
If not, please provide more information.
 
I'll try to explain better.
The problem occurs after I've created the user and I'm going to update the information.
If I change the data and save it doubles.
Like the image below
 

Attachments

  • Screenshot_20180502-093705.jpg
    Screenshot_20180502-093705.jpg
    110.4 KB · Views: 104
  • Captura de Tela 2018-05-02 às 09.41.08.png
    Captura de Tela 2018-05-02 às 09.41.08.png
    26.5 KB · Views: 106
OK, understand. Your database does not recognize two records for the same user as I said before.
It(database) thinks that these are different records. It's possible when the key field of record is not connected to the user data.
This problem can be solved by the two ways.
1. Use Key Field that used for indexing records in database, that connected to User values (name address and so on)
https://stackoverflow.com/questions...ry-key-on-the-text-fields-in-android-database
2. Search and delete old records for given User before adding updated version.
https://stackoverflow.com/questions/9047629/how-to-delete-duplicated-database-records

The same I said above.
Every records that related to given User should be overwritten if new record related to the same User.
This problem can be solved by the two ways.
1. You can use unique String Key for the User. And to use this key as primary index of record in table of database.
2. You can use integer AutoIncrement Key for every record and manually detect if record should be added or replaced.
 
Last edited:
Thank you very much for helping.
Another question,
the birthday in app field shows no value on the screen.
Previous app image
 
For the birthday you use some user defined class "com.android.faced.view.DateEditText"
Please provide XML file of the activity screen and the code of the DateEditText class.
Or just look at it carefully. Why method DateEditText.setText() does not work.
 
Last edited:
DateEditText

Code:
package com.android.faced.view;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class DateEditText extends MaskedEditText {

    private static final String DATE_MASK = "##/##/####";
    private static final String DATE_FORMAT = "dd/MM/yyyy";

    public DateEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setMask(DATE_MASK);
    }

    public DateEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMask(DATE_MASK);
    }

    public DateEditText(Context context) {
        super(context);
        setMask(DATE_MASK);
    }

    @Override
    protected boolean isValid(String maskedInput) {
        try {
            DateFormat df = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
            df.setLenient(false);
            df.parse(maskedInput);

            Calendar c = df.getCalendar();
            int year = c.get(Calendar.YEAR);

            return year >= 1900;
        } catch (ParseException e) {
            return false;
        }
    }

    public boolean isValidDate() {
        return isValid(getText().toString());
    }

    public void SetText(String birthday) {
    }
}

activity_change_register.xml

Code:
<android.support.design.widget.TextInputLayout
                android:id="@+id/birthday_input"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/phone_number_input"
                android:layout_marginTop="8dp"
                >
                <com.android.faced.view.DateEditText
                    android:id="@+id/birthday"
                    android:layout_width="match_parent"
                    android:layout_height="48dp"
                    android:hint="@string/birthday_hint"
                    android:inputType="text"
                    android:maxLines="1"
                    android:nextFocusForward="@id/address_input"
                    />
            </android.support.design.widget.TextInputLayout>
 
Last edited:
I'm sorry, but DateEditText extends another user defined class MaskEditText.
Please provide all classes that rise from DateEditText to parent class, which is in Android library.
 
Back
Top Bottom