Search code examples
javaandroidsqlitesql-updateandroid-sqlite

. How to update individual database elements with SQLite?


Good evening everyone, this is my DatabaseHelper class:

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DB_NAME = "Users.db";
private static final String DB_TABLE = "Users_Table";

//Colonne
private static final String ID = "ID";
private static final String NAME = "NAME";

private static final String CREATE_TABLE = "CREATE TABLE "+ DB_TABLE+" ("+
        ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
        NAME+ " TEXT "+ ")";

public DatabaseHelper (Context context) {
    super(context, DB_NAME, null, 1);
}

@Override
public void onCreate (SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);

}

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

    onCreate( db );
}

public boolean updateData(int id, String name) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues(  );
    contentValues.put( NAME, name );
    contentValues.put( ID, id );
    db.update( DB_TABLE, contentValues, "ID = ?", new String[] {String.valueOf( id )} );
    db.close();
    return true;

}

//Metodo per inserire dati
public boolean insertData (String name) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues(  );
    contentValues.put( NAME, name );

    long result = db.insert( DB_TABLE, null, contentValues );

    return result != -1;  //Se il risultato è = -1 i dati NON vengono inseriti
}
    //Metodo per cancellare i dati
    public int deleteSelectedItem(String NAME) {
    SQLiteDatabase db = this.getWritableDatabase();
    int result = db.delete( DB_TABLE, "NAME = ?", new String[] {NAME} );
    return result;
    }
//Metodo per visualizzare i dati
public Cursor viewData(){
    SQLiteDatabase db = this.getReadableDatabase();
    String query = "Select * from "+DB_TABLE;
    Cursor cursor = db.rawQuery(query, null);

    return cursor;
}}

In MainActivity I call the method like this:

builder.setPositiveButton( "Modifica", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick (DialogInterface dialog, int which) {
                                    if (!editText.getText().toString().isEmpty()) {
                                        listItem.set( position, editText.getText().toString().trim() );

                                        db.updateData( editText.getText().toString() );
                                        arrayAdapter.notifyDataSetChanged();
                                        Toast.makeText( MainActivity.this, "Elemento modificato", Toast.LENGTH_SHORT ).show();
                                    } else {
                                        editText.setError( "aggiungi elemento qui" );
                                    }

                                }
                            } );

When I use it, the ListView updates, but when I restart the emulator, the text I had edited, it returns to its original state. So the method does not update the items in the database. What's wrong with my code? Thanks

EDIT: This is the viewData method in the Main:

private void viewData () {
    Cursor cursor = db.viewData();

    if (cursor.getCount() == 0) {
        Toast.makeText( this, "Nessun dato da visualizzare", Toast.LENGTH_SHORT ).show();
    } else {
        while (cursor.moveToNext()) {
            listItem.add( cursor.getString( 1 ) );
            //index 1 è il nome, index 0 è l'ID
        }

        arrayAdapter = new ArrayAdapter<>( MainActivity.this, R.layout.support_simple_spinner_dropdown_item, listItem );
        userlist.setAdapter( arrayAdapter );

    }
}

Solution

  • Change the definition of the table so that the column name is unique:

    private static final String CREATE_TABLE = "CREATE TABLE "+ DB_TABLE+" ("+
            ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
            NAME+ " TEXT UNIQUE"+ ")";
    

    You will have to uninstall the app from the device so the database is deleted and rerun so that the database and the table are recreated.
    Then change updateData() like this:

    public boolean updateData(String currentName, String newName) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues(  );
        contentValues.put( NAME, newName );
        boolean result = db.update( DB_TABLE, contentValues, NAME + " = ?", new String[] {currentName} ) > 0;
        db.close();
        return result;
    }
    

    So you pass the current name to updateData() to find the row that you want to update.
    Finally change the listener of the button:

    builder.setPositiveButton( "Modifica", new DialogInterface.OnClickListener() {
        @Override
        public void onClick (DialogInterface dialog, int which) {
            if (!editText.getText().toString().isEmpty()) {
                db.updateData( listItem.get( position ), editText.getText().toString().trim() );
                listItem.set( position, editText.getText().toString().trim() );
                arrayAdapter.notifyDataSetChanged();
                Toast.makeText( MainActivity.this, "Elemento modificato", Toast.LENGTH_SHORT ).show();
            } else {
                editText.setError( "aggiungi elemento qui" );
            }
        }
    });