Search code examples
realm

How to store latitude and longitude in realm?


I am totally new in android. I am using GPS tracking in my application using realm. I am successful to find latitude and longitude but i don't know how to store latitude and longitude in realm. Can anyone please help me?


Solution

  • To store data in realm you need a class that extends RealmObject. You can do as follow:

    public class MyLatLng extends RealmObject {
       private double lat;
       private double lng;
    
       public void setLat(double val) { this.lat = val; }
       public void setLng(double val) { this.lng = val; }
    }
    

    Then for storing it, you need to initialize a new instance as follow:

    MyLatLng instance = new MyLatLng();
    instance.setLat(*yourLat*);
    instance.setLng(*yourLng*);
    

    After that, you can finally store it in Realm:

    Realm.init(context);
    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();
    realm.copyToRealm(instance); 
    realm.commitTransaction();