I’m working on an Android app that connects to Google Sheets through Apps Script. I already have a function that adds new entries to my spreadsheet, but now I need help creating a script that can delete rows based on a specific identifier.
Here’s my current code for adding data:
function insertRecord(params){
var timestamp = new Date();
var recordId = spreadsheet.getLastRow();
var productName = params.parameter.productName;
var manufacturer = params.parameter.manufacturer;
spreadsheet.appendRow([timestamp, recordId, productName, manufacturer]);
return ContentService.createTextOutput("Added successfully").setMimeType(ContentService.MimeType.TEXT);
}
I need a similar function that can locate and remove a row when I pass a specific ID from my Android application. Can someone show me how to write the Apps Script code for this deletion operation?
watch out for duplicate IDs - i ran into this where it only deleted the first match instead of all of them. if you’re working with large datasets, try getRange().getValues() instead of getDataRange(). way faster when you know the exact range you need.
Heads up - your recordId approach will bite you later. Using getLastRow() for IDs breaks when rows get deleted, leading to duplicate IDs on new records. Instead, consider using timestamps or UUIDs for unique identifiers.
When implementing the deletion function, make sure to handle edge cases properly. Always check if the sheet has data before running the deletion loop to prevent crashes from attempting to delete rows in an empty sheet.
A performance tip: if you expect frequent deletions, consider not actually removing rows. Instead, add a ‘deleted’ flag column and filter those out in your Android display logic.
I’ve dealt with similar deletion requirements in my projects. The main challenge is finding the row with your target ID - Apps Script doesn’t have built-in search methods for this. Here’s what worked best for me: javascript function deleteRecord(params){ var targetId = params.parameter.recordId; var data = spreadsheet.getDataRange().getValues(); for(var i = data.length - 1; i >= 0; i--){ if(data[i][1] == targetId){ // assuming ID is in column B (index 1) spreadsheet.deleteRow(i + 1); return ContentService.createTextOutput("Deleted successfully").setMimeType(ContentService.MimeType.TEXT); } } return ContentService.createTextOutput("Record not found").setMimeType(ContentService.MimeType.TEXT); } I iterate backwards through the array to avoid index shifting issues when deleting rows. Remember that spreadsheet row numbers start at 1 while array indices start at 0, so you need the i + 1 in deleteRow().