Android: Sync database with map

I’m developing an android app using couchbase lite, and I’m looking for the best possible way to sync the whole database from a server. The database contains the coordinates of various locations that I would like to be displayed on a map. Do you have any ideas?

Hi
CB Lite will sync all documents from the remote DB as long as the user has access to the relevant document channels and no there are no blocking filters specified on the replication.
In your case, you could define all geo coordinates in a document and put it in a channel that is available to all users of your system.
You can learn more about replication here https://developer.couchbase.com/documentation/mobile/current/guides/couchbase-lite/native-api/replication/index.html

thank you for your answer, but I don;t think I fully understand how replication works.Here is my code so far:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {


public class MapsActivity extends AppCompatActivity
    implements OnMapReadyCallback {

final String dbname = "myapp";
private Manager manager;
private Database database;
private com.couchbase.lite.View viewItemsByDate;
private LiveQuery liveQuery;
Poi mPoi;
private static final String SYNC_URL = "http://url/myapp/";
private static final String TAG = "MapsActivity";
GoogleMap googleMap;
private String docId = "123";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Retrieve the content view that renders the map.
    setContentView(R.layout.activity_maps);

    // Get the SupportMapFragment and request notification
    // when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    createManager();
    createCouchdb();
    createDocument(docId);

    Document retrievedDocument = retrieveDocument(docId);
    updateDocument(retrievedDocument);
    deleteDocument(retrievedDocument);

    // Create replicators to push & pull changes to & from Sync Gateway.
    URL url = null;
    try {
        url = new URL(SYNC_URL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    Replication push = database.createPushReplication(url);
    Replication pull = database.createPullReplication(url);
    push.setContinuous(true);
    pull.setContinuous(true);

    // Start replicators
    push.start();
    pull.start();

    // retrievePoi(manager, database, docId);

}

public void createManager() {
    try {
        manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);
    } catch (IOException e) {
        return;
    }
}

public void createCouchdb() {
    try {
        database = manager.getDatabase(dbname);
    } catch (CouchbaseLiteException e) {
        return;
    }
}

public void createDocument(String docId) {
    // create some dummy data
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Calendar calendar = GregorianCalendar.getInstance();
    String currentTimeString = dateFormatter.format(calendar.getTime());
    Poi poi = new Poi("title", 120, 120, "category","order" );

    // put those dummy data together
    Map<String, Object> docContent = new HashMap<String, Object>();
    docContent.put("message", "Hey Couchbase Lite");
    docContent.put("creationDate", currentTimeString);
    docContent.put("poi", poi);

    // create an empty document, add content and write it to the couchDb
    Document document = new Document(database, docId);
    try {
        document.putProperties(docContent);
    } catch (CouchbaseLiteException e) {
    }
}

public Document retrieveDocument(String docId) {
    Document retrievedDocument = database.getDocument(docId);
    return retrievedDocument;
}


public void updateDocument(Document doc) {
    Map<String, Object> updatedProperties = new HashMap<String, Object>();
    updatedProperties.putAll(doc.getProperties());
    updatedProperties.put ("message", "We're having a heat wave!");
    updatedProperties.put ("temperature", "95");

    try {
        doc.putProperties(updatedProperties);
    } catch (CouchbaseLiteException e) {
    }
}



private void retrievePoi(Manager manager, Database couchDb, String docId) {
    Document retrievedDocument = couchDb.getDocument(docId); // Retrieve the document by id
    Object poiObj = retrievedDocument.getProperties().get("poi");
    Gson gson = new Gson();
    String jsonString = gson.toJson(poiObj, Map.class); //Convert the object to json string using Gson
    Poi poi = gson.fromJson(jsonString, Poi.class); //convert the json string to Poi object
    Log.i("getPoiFromDocument", "jsonString>>>" + jsonString);
    Log.i("getPoiFromDocument", "poi>>>" + poi.getTitle());
    Log.i("getPoiFromDocument", "longitude>>>" + poi.getLongitude());
    Log.i("getPoiFromDocument", "latitude>>>" + poi.getLatitude());
    Log.i("getPoiFromDocument", "category>>>" + poi.getCategory());
    Log.i("getPoiFromDocument", "order>>>" + poi.getOrder());

}


    @Override
    public void onMapReady (GoogleMap googleMap){
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title("Marker in Sydney"));

        LatLng athens = new LatLng(37.97945, 23.71622);
        googleMap.addMarker(new MarkerOptions().position(athens)
                .title("Athens"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(athens));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));

        ArrayList<Poi> mPoi = new ArrayList<Poi>();
        mPoi.add(new Poi("city", 21.22, 22.33, "category1", "order1"));
        mPoi.add(new Poi("city", 22.33, 22.33, "category2", "order2"));

        for (int i = 0; i < mPoi.size(); i++) {

            final LatLng name = new LatLng(mPoi.get(i).getLatitude(), mPoi.get(i).getLongitude());
            Marker marker = googleMap.addMarker(new MarkerOptions()
                    .position(name)
                    .snippet(name + " is cool")
            );
        }

    }

public void deleteDocument(Document doc) {
    try {
        doc.delete();
    } catch (CouchbaseLiteException e) {
    }
}
}

I have also created a class called Poi with all the getters and setters. What changes should I make?

1 Like

Hi @stoumpos,

I replied to your post on StackOverflow as well. If you have a set of Pois already in the database, what you probably want to do is set up replication, then create a LiveQuery. The LiveQuery will give you a list to iterate over. Every time the query updates, you’d want to take the new documents from that list and add the points to your map.

You’ve got several things going on in this code that don’t seem relevant. I think it will help you to take a more structured approach to working this out. One way to start would be to take out the replication code for now. Start by storing docs in the database, retrieving them, and get the points showing in your map. Once you have that, the replication code will take a little rearranging, but I think you’ll find it easier to see how it all comes together.

Hope that helps.

thank you very much for your response. I thought that I didn’t have to
use a LiveQuery since I was using filters for the replication, to get
only the public channel.
Thank you very much for your response. It has been really helpful.

is there tutorial with live query and couchbase lite for android that you would suggest?

Sure. Take a look at the tutorial here and see if that helps.