Android Couchbase Lite basic CRUD

Let’s create a sample Android Application to do a create, read, update, and delete, aka CRUD operations in Couchbase Lite.

1. In the app build gradle file, add the Couchbase Lite Android library in the dependencies

compile 'com.couchbase.lite:couchbase-lite-android:1.2.0'

2. activity_main.xml, the layout file for the sample activity class.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv_log_window"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Hello World!" />
</RelativeLayout>

3. Movie.java, a sample class to be used for demonstration purpose. An object of this class will be saved in a couchbase document.

public class Movie {
    private String title;
    private String overview;
    private int length;

    public Movie(String title, String overview, int length) {
        this.title = title;
        this.overview = overview;
        this.length = length;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getOverview() {
        return overview;
    }

    public void setOverview(String overview) {
        this.overview = overview;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }
}

4. MainActivity.java, the activity class which will perform the CRUD operations in Couchbase Lite. For demonstration purpose, everything is dumped in this activity class. For best practice, the Couch Manager object should live in a Singleton class, and pass the ApplicationContext to create the Manager.

public class MainActivity extends Activity {
    final String dbname = "hello";
    private String docId = "123";
    private Manager manager;
    private Database couchDb;

    private TextView tvLogWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvLogWindow = (TextView) findViewById(R.id.tv_log_window);
        tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nStart Couchbase App!");
        if (!Manager.isValidDatabaseName(dbname)) {
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nBad couchbase db name!");
            return;
        }
        createManager();
        createCouchdb();
        createDocument(docId);

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

        tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nEnd the App!");
    }


    public void createManager() {
        try {
            manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nCouchbase Manager created!");
        } catch (IOException e) {
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nFailed to create Couchbase Manager! " + e);
            return;
        }
    }

    public void createCouchdb() {
        try {
            couchDb = manager.getDatabase(dbname);
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nCouchbase Database created!");
        } catch (CouchbaseLiteException e) {
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nFailed to create Couchbase Database!");
            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());
        Movie movie = new Movie("Star War", "The force awakens!", 120);

        // 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("movie", movie);
        tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\ndocContent=" + String.valueOf(docContent));

        // create an empty document, add content and write it to the couchDb
        Document document = new Document(couchDb, docId);
        try {
            document.putProperties(docContent);
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nDocument written to couchDb named " + dbname + " with ID = " + document.getId());
        } catch (CouchbaseLiteException e) {
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nFailed to write document to Couchbase database!");
        }
    }

    public Document retrieveDocument(String docId) {
        Document retrievedDocument = couchDb.getDocument(docId);
        tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nretrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
        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);
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nupdated retrievedDocument=" + String.valueOf(doc.getProperties()));
        } catch (CouchbaseLiteException e) {
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nFailed to update document! ");
        }
    }

    public void deleteDocument(Document doc) {
        try {
            doc.delete();
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nDeleted document, deletion status = " + doc.isDeleted());
        } catch (CouchbaseLiteException e) {
            tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nFailed to delete document! " + e);
        }
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search