Search code examples
androidandroid-sqlite

Update any number of column


This is my function for update. It requires all the parameters for update. However I want update function in such a way that it updates according to the number of parameters passed by the user.

Function declaration in database

public boolean updateFeeder(int feederNo, int conductorCapacity, int total_load, int no_of_connection, 
int outgoing_line){   

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("feederNo", feederNo);
        contentValues.put("conductorCapacity", conductorCapacity);
        contentValues.put("totalLoad", total_load);
        contentValues.put("totalNoOfConnection",no_of_connection);
        contentValues.put("outgoingLine", outgoing_line);


        db.update(TABLE_ADD_FEEDER, contentValues, "feederNo = ?", new String[]{Integer.toString(feederNo)});
        Cursor cursor = db.rawQuery("Select feederNo from ADD_FEEDER where feederNo = ?", new String[]{String.valueOf(feederNo)});
        if(cursor.getCount()>0)
            return true;
        else
            return false;
    }

Function call

boolean isInserted = myDB.updateFeeder(Integer.parseInt(getFeederNo), Integer.parseInt(getConductorCapacity), Integer.parseInt(getTotalLoad), Integer.parseInt(getTotalNoOfConnection), Integer.parseInt(getOutgoingLine));


Solution

  • The parameter could be an string array, you could pass null on some positions and on updateFeeder() set the contentValues just when the position is not null and then set the value.

    You need to do this per position since you need to specify the column name on contentvalues.put

     public boolean updateFeeder(String[] params) {
           .......
            ContentValues contentValues = new ContentValues();
    
            if (params[0] != null)
                contentValues.put("feederNo", Integer.parseInt(params[0]));
    
            if (params[1] != null)
                contentValues.put("conductorCapacity", Integer.parseInt(params[1]));
           ......
           // same per position
        }