Blog

How to update data objects using API

by on April 15, 2015

Once an object is stored in the Backendless data storage, any of its properties (except for the system ones) can be updated using the data update API. The API works the same way as the initial call for saving the object. To update a property value, simply modify it in the instance representing the saved object. The example below retrieves a saved object, modifies the “name” property, and saves it back in the data store.

The data table and schema look as shown in the screenshots below:

Schema:


    Person class:

    import java.util.Date;
    
    public class Person {
       public int age;
       public String name;
       public Date birthdate;
    }

    Code to update an object:

    final AsyncCallback<Person> updateResponder = new AsyncCallback<Person>() {
       @Override
       public void handleResponse(Person updatedPerson) {
           Log.i(TAG, "Person's name after update " + updatedPerson.name);
       }
    
       @Override
       public void handleFault(BackendlessFault fault) {
           Log.e(TAG, fault.getMessage());
       }
    };
    
    Backendless.Data.of(Person.class).findLast(new AsyncCallback<Person>() {
       @Override
       public void handleResponse(Person person) {
           Log.i(TAG, "Loaded object. Name - " + person.name);
           person.name = "Frankie";
           Backendless.Data.of(Person.class).save(person, updateResponder);
       }
    
       @Override
       public void handleFault(BackendlessFault fault) {
           Log.i(TAG, fault.getMessage());
       }
    });


    Person class:

    data class Person(var age: Int = 0, var name: String? = null,
       var birthdate: Date? = null, var objectId: String? = null)

    Code to update an object:

    val updateResponder = object : AsyncCallback<Person> {
       override fun handleResponse(updatedPerson: Person) {
           Log.i(TAG, "Person's name after update ${updatedPerson.name}")
       }
    
       override fun handleFault(fault: BackendlessFault) {
           Log.e(TAG, fault.message)
       }
    }
    
    Backendless.Data.of(Person::class.java).findLast(object : AsyncCallback<Person> {
       override fun handleResponse(person: Person) {
           Log.i(TAG, "Loaded object. Name - ${person.name}")
           person.name = "Frankie"
           Backendless.Data.of(Person::class.java).save(person, updateResponder)
       }
    
       override fun handleFault(fault: BackendlessFault) {
           Log.i(TAG, fault.message)
       }
    })


    Person class:

    @interface Person : NSObject
    
    @property (strong, nonatomic) NSString *objectId;
    @property (strong, nonatomic) NSString *name;
    @property (strong, nonatomic) NSDate *birthdate;
    @property (nonatomic) NSInteger age;
    
    @end

    API Example:

    DataStoreFactory *dataStore = [Backendless.shared.data of:[Person class]];
    [dataStore findLastWithResponseHandler:^(Person *person) {
        NSLog(@"Loaded object. Name - %@", person.name);
            
        person.name = @"Frankie";
        [dataStore updateWithEntity:person responseHandler:^(Person *updatedPerson) {
            NSLog(@"Person's name after update %@", updatedPerson.name);
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
            
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];


    Person class:

    @objcMembers class Person: NSObject {
        var objectId: String?
        var name: String?
        var birthdate: Date?
        var age: Int = 0
    }

    API example:

    let dataStore = Backendless.shared.data.of(Person.self)
    dataStore.findFirst(responseHandler: { person in
        if let person = person as? Person {
            print("Loaded object. Name - \(person.name ?? "")")
                    
            person.name = "Frankie"
            dataStore.update(entity: person, responseHandler: { updatedPerson in
                if let updatedPerson = updatedPerson as? Person {
                    print("Person's name after update \(updatedPerson.name ?? "")")
                }
            }, errorHandler: { fault in
                print("Error: \(fault.message ?? "")")
            })
        }
                
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const PersonStorage = Backendless.Data.of('Person')
    
    const findFirstPerson = () => {
      return PersonStorage.findFirst()
    }
    
    const updatePerson = person => {
      console.log(`Loaded object. Name - ${ person.name }`)
    
      person.name = 'Bobby'
    
      return PersonStorage.save(person)
    }
    
    const onSuccess = updatedPerson => {
      console.log(`Person's name after update - ${ updatedPerson.name }`)
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    Promise.resolve()
      .then(findFirstPerson)
      .then(updatePerson)
      .then(onSuccess)
      .catch(onError)
    

    Backendless.Data.of("Person").findLast().then((person) {
     print("Loaded object. Name - ${person['name']}");
     person['name'] = "Frankie";
     Backendless.Data.of("Person").save(person).then((updatedPerson) {
       print("Person's name after update ${updatedPerson['name']}");
     });
    });

    The method that saves the object automatically checks if the object already exists in the persistent storage and, if so, updates the property values. As you can see from the example above, the method returns an updated instance back to the client.