Implement contact editing after saving to the database

Asked

Viewed 83 times

4

Hello!

I’m adapting a aplicativo that manages contacts with interaction banco de dados.

In the aplicativo, I am inserting and deleting contacts but I’m having difficulties to implement the método to edit contacts and save the edited contact to banco de dados.

The método onContextItemSelected is implemented and only this part is missing.

onContextItemSelected method in Mainactivity

    public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case EDIT:
            // TODO: Implement editing a contact
            break;
        case DELETE:
            dbHandler.deleteContact(Contacts.get(longClickedItemIndex));
            Contacts.remove(longClickedItemIndex);
            contactAdapter.notifyDataSetChanged();
            break;
    }

    return super.onContextItemSelected(item);
    }

Databasehandler class with updateContact method

public class DatabaseHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "controleAgenda",
        TABLE_CONTACTS = "contatos",
        KEY_ID = "id",
        KEY_NAME = "nome",
        KEY_PHONE = "telefone",
        KEY_ADDRESS = "endereco",
        KEY_EMAIL = "email",
        KEY_IMAGEURI = "imageUri";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_EMAIL + " TEXT," + KEY_IMAGEURI + " TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    onCreate(db);
}

public void createContact(Contato contato) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contato.getName());
    values.put(KEY_PHONE, contato.getPhone());
    values.put(KEY_ADDRESS, contato.getAddress());
    values.put(KEY_EMAIL, contato.getEmail());
    values.put(KEY_IMAGEURI, contato.getImageURI().toString());

    db.insert(TABLE_CONTACTS, null, values);
    db.close();
}

public Contato getContact(int id) {
    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );

    if (cursor != null)
        cursor.moveToFirst();

    Contato contato = new Contato(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
    db.close();
    cursor.close();
    return contato;
}

public void deleteContact(Contato contato) {
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] { String.valueOf(contato.getId()) });
    db.close();
}

public int getContactsCount() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();

    return count;
}

public int updateContact(Contato contato) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contato.getName());
    values.put(KEY_PHONE, contato.getPhone());
    values.put(KEY_ADDRESS, contato.getAddress());
    values.put(KEY_EMAIL, contato.getEmail());
    values.put(KEY_IMAGEURI, contato.getImageURI().toString());

    int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contato.getId()) });
    db.close();

    return rowsAffected;
}

public List<Contato> getAllContacts() {
    List<Contato> contacts = new ArrayList<Contato>();

    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);

    if (cursor.moveToFirst()) {
        do {
            contacts.add(new Contato(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
        }
        while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return contacts;
}
}
  • Explain better the difficulty you have. It makes some mistake?

  • Oops, thanks for the @ramaral feedback. My difficulty is actually to implement the necessary method to ediitar the contact, even if my question is not pertinent to this forum, I apologize. In the class that controls actions and interactions with the BD (DatabaseHandler), the method has already been implemented updateContact I am unable to implement this edition in the same way that was implemented to delete it, in the method onContextItemSelected present in MainActivity.

  • In realation to the bank should call the method dbHandler.updateContact(Contacts.get(longClickedItemIndex)). With regard to the Adapter I can’t tell you why I don’t know you.

1 answer

3


When you want to edit a contact from an application, what is usually done is the following:

By clicking on a contact from a contact list, a new edit screen ( Activity or Fragment ) with the contact information clicked is opened ( Obs.: contact information can be passed to the new screen using Bundle).

The editing screen will have EditTexts filled with the contact information clicked, because that way, if you want to edit the contact name, just edit the name filled in on EditText. Obviously, this screen also has a save changes button and a cancel changes button.

Thus, by clicking the save button the changes, you should do the following:

  1. ( Ideal) Check that the data is valid
  2. Create a new user using the new data filled in Edittext ( just create the new contact using the new, Do not add it to the bank yet! );
  3. ( Ideal, but depends on business logic) Make a query in the database with the new user to check if the data of the new user is conflicting with that of another user already registered.
  4. Call the database update function by passing the new parameter
  5. Notify Adapter that the database data has been changed.
  6. Close the edit screen and return to the previous screen.

This is a "simple and general" way to make register changes. If you have any questions about implementing one of these steps, or if you can find a simpler way to do so, feel free to share them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.