Search code examples
androiddatabasesqliteandroid-studioandroid-sqlite

SQLite Insert Query trims 0 as the first character of an inserted string


I have an insert query, it adds the contacts on the database. However, I have a problem with inserting a string that has "0" as its first character.

For example I input this: 09127400049
It will now be saved as: 9127400049

public void addEmergencyContacts(String name, long number, String email, String relationship) {
    ContentValues cv = new ContentValues();
    cv.put("NAME", name);
    cv.put("NUMBER", number);
    cv.put("EMAIL", email);
    cv.put("RELATIONSHIP", relationship);

    this.getWritableDatabase().insertOrThrow("ELSA_EMERGENCY_CONTACTS", "", cv);
}

Here's how I insert contacts

controller.addEmergencyContacts(emergencyContactET.getText().toString(), Long.parseLong(emergencyNumberET.getText().toString()), emergencyEmailET.getText().toString(), relationship);

Do you know any solutions or suggestion there


Solution

  • To insert the 0 character you will need to do the following:-

    • Define the NUMBER column with a column type of TEXT, if it is not already defined as type TEXT.
    • Change the addEmergencyContacts method's signature so that the 2nd parameter is String
      • i.e. change public void addEmergencyContacts(String name, long number, String email, String relationship) {..... to public void addEmergencyContacts(String name, String number, String email, String relationship) {.....
    • Change each call to addEmergencyContacts to pass the value for the 2nd parameter as a string ensuring that the leading 0 is included in that string.
    • either
      • Delete the App's data or
      • Uninstall the App
    • rerun the App.

    The reasoning is that in order to be flexible and efficient SQLite :-

    • has flexible column types
    • allows most columns to store data of any type
    • uses rules that attempt to store data in as few bytes as possible.

    Rather than go into great detail here's a link detailing the factors Datatypes In SQLite Version 3.