GithubHelp home page GithubHelp logo

android-ddp's Introduction

Android-DDP

This library implements the Distributed Data Protocol (DDP) from Meteor for clients on Android.

Connect your native Android apps, written in Java, to apps built with the Meteor framework and build real-time features.

This project is completely based on this one

Motivation

  • Have you built a web application with Meteor?
    • Using this library, you can build native Android apps that can talk to your Meteor server and web application.
  • Are you primarily an Android developer (who has never heard of Meteor)?
    • With "Android-DDP", you can use a Meteor server as your backend for real-time applications on Android.
  • Doesn't Meteor provide built-in features for Android app development already?
    • With Meteor's built-in features, your Android app will be written in HTML, CSS and JavaScript, wrapped in a WebView. It will not be a native app.
    • By using this library, however, you can write native Android apps in Java while still using Meteor as your real-time backend.

Requirements

  • Android 4.1+

Installation

  • Add this library to your project

    • Declare the Gradle repository in your root build.gradle

      allprojects {
          repositories {
              maven { url "https://jitpack.io" }
          }
      }
    • Declare the Gradle dependency in your app module's build.gradle

      dependencies {
          compile 'me.jahirfiquitiva.Android-DDP:0.0.1'
      }
  • Add the Internet permission to your app's AndroidManifest.xml:

    <uses-permission android:name="android.permission.INTERNET" />

Usage

  • Creating a new instance of the DDP client

    public class MyActivity extends Activity implements MeteorCallback {
    
        private Meteor meteor;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // ...
    
            // create a new instance
            meteor = new Meteor(this, "ws://example.meteor.com/websocket");
    
            // register the callback that will handle events and receive messages
            meteor.addCallback(this);
    
            // establish the connection
            meteor.connect();
        }
    
        public void onConnect(boolean signedInAutomatically) { }
    
        public void onDisconnect() { }
    
        public void onDataAdded(String collectionName, String documentID, String newValuesJson) {
            // parse the JSON and manage the data yourself (not recommended)
            // or
            // enable a database (see section "Using databases to manage data") (recommended)
        }
    
        public void onDataChanged(String collectionName, String documentID, String updatedValuesJson, String removedValuesJson) {
            // parse the JSON and manage the data yourself (not recommended)
            // or
            // enable a database (see section "Using databases to manage data") (recommended)
        }
    
        public void onDataRemoved(String collectionName, String documentID) {
            // parse the JSON and manage the data yourself (not recommended)
            // or
            // enable a database (see section "Using databases to manage data") (recommended)
        }
    
        public void onException(Exception e) { }
    
        @Override
        public void onDestroy() {
            meteor.disconnect();
            meteor.removeCallback(this);
            // or
            // meteor.removeCallbacks();
    
            // ...
    
            super.onDestroy();
        }
    
    }
  • Singleton access

    • Creating an instance at the beginning

      MeteorSingleton.createInstance(this, "ws://example.meteor.com/websocket")
      // instead of
      // new Meteor(this, "ws://example.meteor.com/websocket")
    • Accessing the instance afterwards (across Activity instances)

      MeteorSingleton.getInstance()
      // instead of
      // meteor
    • All other API methods can be called on MeteorSingleton.getInstance() just as you would do on any other Meteor instance, as documented here with meteor

  • Registering a callback

    // MeteorCallback callback;
    meteor.addCallback(callback);
  • Unregistering a callback

    meteor.removeCallbacks();
    // or
    // // MeteorCallback callback;
    // meteor.removeCallback(callback);
  • Available data types

    JavaScript / JSON Java / Android
    String (e.g. "John" or 'Jane') String (e.g. "John" or "Jane")
    Number (e.g. 42) byte (e.g. (byte) 42)
    short (e.g. (short) 42)
    int (e.g. 42)
    long (e.g. 42L)
    float (e.g. 3.14f)
    double (e.g. 3.14)
    Boolean (e.g. true) boolean (e.g. true)
    Array (e.g. [ 7, "Hi", true ]) Object[] (e.g. new Object[] { 7, "Hi", true })
    List<Object> (e.g. List<Object> list = new LinkedList<Object>(); list.add(7); list.add("Hi"); list.add(true);)
    Object (e.g. { "amount": 100, "currency": "USD" }) Map<String, Object> (e.g. Map<String, Object> map = new HashMap<String, Object>(); map.put("amount", 100); map.put("currency", "USD");)
    MyClass (e.g. public class MyClass { public int amount; public String currency; } MyClass myObj = new MyClass(); myObj.amount = 100; myObj.currency = "USD";)
    null null
  • Inserting data into a collection

    Map<String, Object> values = new HashMap<String, Object>();
    values.put("_id", "my-id");
    values.put("some-key", "some-value");
    
    meteor.insert("my-collection", values);
    // or
    // meteor.insert("my-collection", values, new ResultListener() { });
  • Updating data in a collection

    Map<String, Object> query = new HashMap<String, Object>();
    query.put("_id", "my-id");
    
    Map<String, Object> values = new HashMap<String, Object>();
    values.put("some-key", "some-value");
    
    meteor.update("my-collection", query, values);
    // or
    // meteor.update("my-collection", query, values, options);
    // or
    // meteor.update("my-collection", query, values, options, new ResultListener() { });
  • Deleting data from a collection

    meteor.remove("my-collection", "my-id");
    // or
    // meteor.remove("my-collection", "my-id", new ResultListener() { });
  • Subscribing to data from the server

    String subscriptionId = meteor.subscribe("my-subscription");
    // or
    // String subscriptionId = meteor.subscribe("my-subscription", new Object[] { arg1, arg2 });
    // or
    // String subscriptionId = meteor.subscribe("my-subscription", new Object[] { arg1, arg2 }, new SubscribeListener() { });
  • Unsubscribing from a previously established subscription

    meteor.unsubscribe(subscriptionId);
    // or
    // meteor.unsubscribe(subscriptionId, new UnsubscribeListener() { });
  • Calling a custom method defined on the server

    meteor.call("myMethod");
    // or
    // meteor.call("myMethod", new Object[] { arg1, arg2 });
    // or
    // meteor.call("myMethod", new ResultListener() { });
    // or
    // meteor.call("myMethod", new Object[] { arg1, arg2 }, new ResultListener() { });
  • Disconnect from the server

    meteor.disconnect();
  • Creating a new account (requires accounts-password package)

    meteor.registerAndLogin("john", "[email protected]", "password", new ResultListener() { });
    // or
    // meteor.registerAndLogin("john", "[email protected]", "password", profile, new ResultListener() { });
  • Signing in with an existing username (requires accounts-password package)

    meteor.loginWithUsername("john", "password", new ResultListener() { });
  • Signing in with an existing email address (requires accounts-password package)

    meteor.loginWithEmail("[email protected]", "password", new ResultListener() { });
  • Check if the client is currently logged in (requires accounts-password package)

    meteor.isLoggedIn();
  • Get the client's user ID (if currently logged in) (requires accounts-password package)

    meteor.getUserId();
  • Logging out (requires accounts-password package)

    meteor.logout();
    // or
    // meteor.logout(new ResultListener() { });
  • Checking whether the client is connected

    meteor.isConnected();
  • Manually attempt to re-connect (if necessary)

    meteor.reconnect();

Using databases to manage data

Enabling a database

Pass an instance of Database to the constructor. Right now, the only subclass provided as a built-in database is InMemoryDatabase. So the code for the constructor becomes:

meteor = new Meteor(this, "ws://example.meteor.com/websocket", new InMemoryDatabase());

After that change, all data received from the server will automatically be parsed, updated and managed for you in the built-in database. That means no manual JSON parsing!

So whenever you receive data notifications via onDataAdded, onDataChanged or onDataRemoved, that data has already been merged into the database and can be retrieved from there. In these callbacks, you can thus ignore the parameters containing JSON data and instead get the data from your database.

Accessing the database

Database database = meteor.getDatabase();

This method call and most of the following method calls can be chained for simplicity.

Getting a collection from the database by name

// String collectionName = "myCollection";
Collection collection = meteor.getDatabase().getCollection(collectionName);

Retrieving the names of all collections from the database

String[] collectionNames = meteor.getDatabase().getCollectionNames();

Fetching the number of collections from the database

int numCollections = meteor.getDatabase().count();

Getting a document from a collection by ID

// String documentId = "wjQvNQ6sGjzLMDyiJ";
Document document = meteor.getDatabase().getCollection(collectionName).getDocument(documentId);

Retrieving the IDs of all documents from a collection

String[] documentIds = meteor.getDatabase().getCollection(collectionName).getDocumentIds();

Fetching the number of documents from a collection

int numDocuments = meteor.getDatabase().getCollection(collectionName).count();

Querying a collection for documents

Any of the following method calls can be chained and combined in any way to select documents via complex queries.

// String fieldName = "age";
// int fieldValue = 62;
Query query = meteor.getDatabase().getCollection(collectionName).whereEqual(fieldName, fieldValue);
// String fieldName = "active";
// int fieldValue = false;
Query query = meteor.getDatabase().getCollection(collectionName).whereNotEqual(fieldName, fieldValue);
// String fieldName = "accountBalance";
// float fieldValue = 100000.00f;
Query query = meteor.getDatabase().getCollection(collectionName).whereLessThan(fieldName, fieldValue);
// String fieldName = "numChildren";
// long fieldValue = 3L;
Query query = meteor.getDatabase().getCollection(collectionName).whereLessThanOrEqual(fieldName, fieldValue);
// String fieldName = "revenue";
// double fieldValue = 0.00;
Query query = meteor.getDatabase().getCollection(collectionName).whereGreaterThan(fieldName, fieldValue);
// String fieldName = "age";
// int fieldValue = 21;
Query query = meteor.getDatabase().getCollection(collectionName).whereGreaterThanOrEqual(fieldName, fieldValue);
// String fieldName = "address";
Query query = meteor.getDatabase().getCollection(collectionName).whereNull(fieldName);
// String fieldName = "modifiedAt";
Query query = meteor.getDatabase().getCollection(collectionName).whereNotNull(fieldName);
// String fieldName = "age";
// Integer[] fieldValues = new Integer[] { 60, 70, 80 };
Query query = meteor.getDatabase().getCollection(collectionName).whereIn(fieldName, fieldValues);
// String fieldName = "languageCode";
// String[] fieldValues = new String[] { "zh", "es", "en", "hi", "ar" };
Query query = meteor.getDatabase().getCollection(collectionName).whereNotIn(fieldName, fieldValues);

Any query can be executed by a find or findOne call. The step of first creating the Query instance can be skipped if you chain the calls to execute the query immediately.

Document[] documents = meteor.getDatabase().getCollection(collectionName).find();
// int limit = 30;
Document[] documents = meteor.getDatabase().getCollection(collectionName).find(limit);
// int limit = 30;
// int offset = 5;
Document[] documents = meteor.getDatabase().getCollection(collectionName).find(limit, offset);
Document document = meteor.getDatabase().getCollection(collectionName).findOne();

Chained together, these calls may look as follows, for example:

Document document = meteor.getDatabase().getCollection("users").whereNotNull("lastLoginAt").whereGreaterThan("level", 3).findOne();

Getting a field from a document by name

// String fieldName = "age";
Object field = meteor.getDatabase().getCollection(collectionName).getDocument(documentId).getField(fieldName);

Retrieving the names of all fields from a document

String[] fieldNames = meteor.getDatabase().getCollection(collectionName).getDocument(documentId).getFieldNames();

Fetching the number of fields from a document

int numFields = meteor.getDatabase().getCollection(collectionName).getDocument(documentId).count();

Contributing

All contributions are welcome! If you wish to contribute, please create an issue first so that your feature, problem or question can be discussed.

Dependencies

Further reading

Disclaimer

This project is neither affiliated with nor endorsed by Meteor.

License

Copyright (c) delight.im <[email protected]>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

android-ddp's People

Contributors

jahirfiquitiva avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.