简体   繁体   中英

Data insertion failed in SQLiteDatabase

I am trying to create a person object and want to save that in SQLiteDatabase, but ultimately the data insertion fails. Below are the insertion method and its call. Can you guys tell me, what problem is happening here? Also, I am facing problem to save an image and retrieve it. I have commented out the code to save the image because it was stopping the application.

//Insert
long insertPerson(Person person) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    //values.put(ID_FIELD, person.getId());
    values.put(NAME_FIELD, person.getName());
    values.put(DOB_FIELD, person.getDateOfBirth());
    values.put(MOBILE_FIELD, person.getMobile());
    values.put(AGE_FIELD, person.getAge());
    values.put(NEXT_BIRTHDAY_FIELD, person.getNext_birthday());
    //values.put(IMAGE_FIELD, person.getBitmap().compress(Bitmap.CompressFormat.PNG, 0, stream));

    long inserted = db.insert(PERSON_TABLE, null, values);
    db.close();

    return inserted;
}

Save method

//Save data
public void saveData() {
    int id = 0;
    String name, date_of_birth, mobile, age, next_birthday;
    Bitmap profilePicture;

    //Get data from user
    date_of_birth = tv_DoB.getText().toString();
    name = et_name.getText().toString();
    mobile = et_mobile.getText().toString();
    profilePicture = iv_profile_image.getDrawingCache();

    age = final_year + "years old";
    next_birthday = remaining_months + "months" + remaining_days + "days";

    Person person = new Person(id, name, date_of_birth, mobile, age, next_birthday);

    Toast.makeText(getContext(), person.toString(), Toast.LENGTH_LONG).show();

    databaseHelper = new DatabaseHelper(getContext(), "person_database", null, 1);

    long inserted = databaseHelper.insertPerson(person);
    if (inserted >= 0) {
        Toast.makeText(getContext(), "Data inserted successfully...", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(getContext(), "Data insertion failed...", Toast.LENGTH_SHORT).show();
    }
}

Try one of the following:

  • Make sure the database name and schema is correct.
  • Uninstall/Clear data of your app from the device and install the app again.

Reason to uninstall:

While you are coding, you might have changed the schema of the database. But unfortunately, if the version code of the app is same, upon reinstalling the app with a different schema where old schema already exists, the schema will not be updated. So clearing app data would be the easiest way to allow new schema to be updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM