Coder Social home page Coder Social logo

delight-im / android-ddp Goto Github PK

View Code? Open in Web Editor NEW
273.0 29.0 57.0 3.69 MB

[UNMAINTAINED] Meteor's Distributed Data Protocol (DDP) for clients on Android

License: Apache License 2.0

Java 100.00%
meteor android ddp client database java android-ddp real-time realtime

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.

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 2.3+

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 'com.github.delight-im:Android-DDP:v3.3.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 mMeteor;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // ...
    
            // create a new instance
            mMeteor = new Meteor(this, "ws://example.meteor.com/websocket");
    
            // register the callback that will handle events and receive messages
            mMeteor.addCallback(this);
    
            // establish the connection
            mMeteor.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() {
            mMeteor.disconnect();
            mMeteor.removeCallback(this);
            // or
            // mMeteor.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
      // mMeteor
    • All other API methods can be called on MeteorSingleton.getInstance() just as you would do on any other Meteor instance, as documented here with mMeteor

  • Registering a callback

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

    mMeteor.removeCallbacks();
    // or
    // // MeteorCallback callback;
    // mMeteor.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");
    
    mMeteor.insert("my-collection", values);
    // or
    // mMeteor.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");
    
    mMeteor.update("my-collection", query, values);
    // or
    // mMeteor.update("my-collection", query, values, options);
    // or
    // mMeteor.update("my-collection", query, values, options, new ResultListener() { });
  • Deleting data from a collection

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

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

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

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

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

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

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

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

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

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

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

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

    mMeteor.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:

mMeteor = 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 = mMeteor.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 = mMeteor.getDatabase().getCollection(collectionName);

Retrieving the names of all collections from the database

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

Fetching the number of collections from the database

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

Getting a document from a collection by ID

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

Retrieving the IDs of all documents from a collection

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

Fetching the number of documents from a collection

int numDocuments = mMeteor.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 = mMeteor.getDatabase().getCollection(collectionName).whereEqual(fieldName, fieldValue);
// String fieldName = "active";
// int fieldValue = false;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereNotEqual(fieldName, fieldValue);
// String fieldName = "accountBalance";
// float fieldValue = 100000.00f;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereLessThan(fieldName, fieldValue);
// String fieldName = "numChildren";
// long fieldValue = 3L;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereLessThanOrEqual(fieldName, fieldValue);
// String fieldName = "revenue";
// double fieldValue = 0.00;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereGreaterThan(fieldName, fieldValue);
// String fieldName = "age";
// int fieldValue = 21;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereGreaterThanOrEqual(fieldName, fieldValue);
// String fieldName = "address";
Query query = mMeteor.getDatabase().getCollection(collectionName).whereNull(fieldName);
// String fieldName = "modifiedAt";
Query query = mMeteor.getDatabase().getCollection(collectionName).whereNotNull(fieldName);
// String fieldName = "age";
// Integer[] fieldValues = new Integer[] { 60, 70, 80 };
Query query = mMeteor.getDatabase().getCollection(collectionName).whereIn(fieldName, fieldValues);
// String fieldName = "languageCode";
// String[] fieldValues = new String[] { "zh", "es", "en", "hi", "ar" };
Query query = mMeteor.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 = mMeteor.getDatabase().getCollection(collectionName).find();
// int limit = 30;
Document[] documents = mMeteor.getDatabase().getCollection(collectionName).find(limit);
// int limit = 30;
// int offset = 5;
Document[] documents = mMeteor.getDatabase().getCollection(collectionName).find(limit, offset);
Document document = mMeteor.getDatabase().getCollection(collectionName).findOne();

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

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

Getting a field from a document by name

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

Retrieving the names of all fields from a document

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

Fetching the number of fields from a document

int numFields = mMeteor.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

joshuaswett avatar ocram avatar perkinszhu avatar victorjmarin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-ddp's Issues

Subscription with args

It looks like it's currently not possible to create a subscription using arguments, and you must always subscribe to a publication that has no arguments. Is that correct?

As in arg1, arg2...

If this is the case, it would be very beneficial to add that functionality. I think it's pretty typical to subscribe to a subset of documents based on some chosen value so that an entire collection is not sent over the wire.

WebSocket always lost connection to meteor.com and Heroku

I have deployed my Server to meteor.com and it's succeed. This is my site http://booklook-coba.meteor.com/. but when I try to connect it with websocket protocol it's failed. This is my protocol "ws://booklook-coba.meteor.com:443/websocket". The connection always lost. I cannot do CRUD into my database even though it's working in my localhost.
Could you tell me more about this? Thank you

onDisconnect bug?

in Meteor.java, disconnect() method, on line 225 mCallback is set to null - therefore, onDisconnect() callback will never be fired. Is that a bug or is onDisconnect() supposed to happen only for non-user initiated disconnect? (sorry if I didn't ask this the right way or in the right place - this is my very first post on GitHub)

Error using call in client

Map<String, Object> signInValues = new HashMap<String, Object>();
signInValues.put("email", email);
signInValues.put("password", password);
mMeteor.call("/users_booklook/find", signInValues);

why I cant call method with 2 parameter like above in my android .

Publish JARS?

Any reason against publishing the JARs to Sonatype? I realize it's a pain in the ass, but I'd be more than happy to lend a hand getting things setup if you're amenable to the idea.

Add source files to android-ddp-0.0.1-bundle.jar

It would help in development of apps that use Android-DDP, if android-ddp-0.0.1-bundle.jar contained also source files of Android-ddp library. This way one could easily peek how given library class is implemented.

If you prefer to keep sources outside of bundle jar, consider providing separate android-ddp-0.0.1-bundle-src.jar with sources only.

Local Server

Hello! I set up a simple meteor server on localhost
It's fine when accessing via browser:
http://localhost:3000

I tried to connect from my android client and the connection is refused
mMeteor = new Meteor(getApplicationContext(), "ws://localhost:3000/websocket");

12-17 19:37:23.738 650-650/com.example.rafa93br.meteorddp2 I/System.out: Meteor
12-17 19:37:23.738 650-650/com.example.rafa93br.meteorddp2 I/System.out:   onClose
12-17 19:37:23.738 650-650/com.example.rafa93br.meteorddp2 I/System.out:     code == 2
12-17 19:37:23.738 650-650/com.example.rafa93br.meteorddp2 I/System.out:     reason == failed to connect to localhost/127.0.0.1 (port 3000) after 6000ms: isConnected failed: ECONNREFUSED (Connection refused)

I tried to connect to android-ddp-meteor.meteor.com and it worked just fine, so I think that the problem is with my server, is there any permissions i should there to allow android clients to connect?

How to clear all your local data and subscribe again ?

Hey,

I have an app with 3 activities (Login, List, Detail of item).
I need to be able to completely clean my List activity when I move back to login.
At the moment, I unsubscribe during the onStop() and subscribe during the onStart() but the second time I log in, I receive nothing.

Do you have an idea ?
Thanks (awesome library !)

Methods from Accounts Package.

Hi,

I'm trying to call Accounts.callLoginMethod method from my Android device. But, I get an error: 404, Method not found.

Is there a possible way to call a method from a different package or is it a feature yet to be implemented?

Thanks, in advance.

How to pass complex parameters to method call?

Can you please provide examples on how to pass parameters to Meteor.call()? How exactly can I pass an object like

{ key1: "value1", key2: "value2"}

or multiple objects or a mix of objects and arrays?

Best approach to save data locally

When developing with meteor for the client, it implicitly uses a minimongo db on the clientside, which also stores the data in the local storage. Also this enables users to run queries (sort, filter) on those data sets.

I've been saving the data coming in currently to local HashMaps but sorting and filtering data items is really resource intensive and leads to many UI hangs. Is there any solution or suggestion on how to save this data locally and have decent performance for getting specific subsets?

(One could of course always just subscribe to the specific published feed in every activity but there is not persistence when switching)

onDisconnect : WebSockets connection lost

Hi guys,

I'm using present version of Meteor and deploy with mup to DigitalOcean
Which all working fine with js client. but I got stuck for native Android (device/emulator x86) somehow.

Here's my code, some other code is just Log for callback

mMeteor = new Meteor(this, "http://123.456.789.00");
mMeteor.setCallback(this);

When I try to connect, it always throw WebSockets connection lost
Anyone hit this before? I think I just miss something stupid.
uses-permission is set BTW
ws:://123.456.789.00 is not working either
http://localhost:3000 is not working but this should be emulator issue.
http://192.168.2.133:3000 local IP is no luck too.

even worst, sometime it's not call back e.g. after I try registerAndLogin or else.
I think I'm doom! Any help would be appreciate.

Thanks

Maven

Would be awesome, if one could get the source code directly via maven.

Currently it is kinda messy to include the source code as a separate module in android studio.

json exception

How are you, The result is not a valid json data, it for more than two " "

if (listener instanceof ResultListener) {
mListeners.remove(id);
final String result;
if (data.has(Protocol.Field.RESULT)) {
result = data.get(Protocol.Field.RESULT).toString();
}
}

no method

mMeteor.call("/auto", new ResultListener() {

        @Override
        public void onSuccess(String result) {
            Log.e("TAG", "result=========="+result);

        }

        @Override
        public void onError(String error, String reason, String details) {
            // TODO Auto-generated method stub
            Log.e("TAG", "error=========="+error);
            Log.e("TAG", "reason=========="+reason);
            Log.e("TAG", "details=========="+details);

        }
    });

why reason==========Method not found error==========404

ECONNREFUSED (Connection refused)

Hi guys,

I'm testing on local ws://192.168.2.133:3000/websocket and everything working fine
but got stuck with real server which is Ubuntu 14 on DigitalOcean via MUP. ws://128.199.207.81:3000/websocket

onDisconnect : failed to connect to /128.199.207.81 (port 3000) after 6000ms: isConnected failed: ECONNREFUSED (Connection refused)

client js version 128.199.207.81 is working fine btw, so any hint would be appreciated.

Thanks

How to query database?

how can I call collection.find() on android? meteor.call("/Collection/find") gives 404 despite that it works on the web client.

Meteor.update() access denied

Hi @mwaclawek
Is known not finished yet?

Serverside.js

mongodb.allow({
  remove : function() {
    return true;
  },
  update : function(userId, doc, fields, modifier) {
    return true;
  },
  insert : function() {
    return true;
  }
});

Java

Map<String, Object> updateQuery = new HashMap<String, Object>();
updateQuery.put("_id", "r87MfSvjMdaD9J8Lh");
Map<String, Object> updateValues = new HashMap<String, Object>();
Map<String, Object> options = new HashMap<String, Object>();
updateValues.put("some-number", 5);
DDP.mMeteor.update("mongodb", updateQuery, updateValues)

LogCat:

09-12 06:25:37.078: I/tikatoy(27287): DDP: Update fail: Access denied. In a restricted collection you can only update documents, not replace them. Use a Mongo update operator, such as '$set'.

Thanks for the answer.

android

hey Can you give an android client and server interaction implementation example of add and delete

Offline usage

how is it possible to get the items synced localy for an offline-app?

Use Android-DDP on different activities

All Android-DDP examples shows on one activity. How can i use it on different activities. For example i connect my server in first activity and go next activity. How can i carry it. Maybe i can use singleton but i don't know.

How can i implement it?

Thank you.

Upon automatic re-connect after a connection outage, a failure to automatically log back in does not update mLoggedInUserId and the Meteor class will therefore still think you are logged in

To replicate this issue, log in to the same user account with two different devices (one being an Android device using Android-DDP). Configure your logout to use the Meteor.logoutOtherClients() method which will log out all devices for a certain account when one of the devices logs out. Now, log out on your account on the non-Android device. Due to the logout configuration stated above, the logout on the non-Android device will cause the Android device to be logged out. When the Android device gets logged out, its DDP connection is lost and the Android-DDP library gracefully re-establishes the connection. However, the login token is no longer valid and Android-DDP can't automatically log the Android device back in. In this circumstance, the mLoggedInUserId field is not cleared and the Meteor class will still return true when isLoggedIn() is called.

Add convenience methods for "accounts-password" methods

Right now, the Meteor class already has convenience methods for the following two methods from the accounts-password package:

  • createUser
  • login

We should add further methods that wrap the following method calls:

  • logout
  • verifyEmail
  • changePassword
  • forgotPassword
  • resetPassword

Question: how to get the initial collection items?

This must be a very dumb question, but how can i get all the initial collection items after subscribing to it?

I've looked into the onSuccess callback of the SubscribeListener but i didn't have any luck.

Thanks.

¿How can i get data from server?

Hi, i came this time with a question

I've done subscribe and publish, and i've done a call method and this work fine, but ¿How to get the data from db? ¿Do I need to use onDataAdded, onDataChanged and onDataRemoved methods?

Thanks.

Set Up server and Connect To Localhost

how to sett up server for this library, I made an android native app with this library and I use meteor for my web service. I dont remove insecure package and autopublish package. so I can Insert, delete and update without subscribe or call the method in client.
but my problem is I can not connect to my localhost. I use genymotion for the android emulator.
Any one can Help me, please,,, Thank you for this amazing library
It's my first time work with Web Socket,,
here is my code https://ideone.com/pXzJW8

Link Library Fail

Hello,
I did copy from jar to libs and I got this error:

09-10 11:01:58.354: I/dalvikvm(2718): Failed resolving Lcom/example/android_ddp/MainActivity; interface 85 'Lim/delight/android/ddp/MeteorCallback;'

And

09-11 02:12:11.758: W/dalvikvm(3326): Link of class 'Lcom/example/androidddp/MainActivity;' failed

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidddp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidddp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Data added event on subscription

Hi, I noticed that when a subscription is successful, an onDataAdded event is fired for each record of the data loaded by the subscription (data existing in the database up to the subscription time). Wouldn't the onDataAdded event be better fired only when new data is added after the subscription? The data loaded by the subscription can be delivered in the onSuccess callback of the SubscriberListener.

Callbacks not firing

I'm logging in the console some text when these methods get fired, but they are not going off. I am signed in and subscribed correctly. I have also set the callback correctly. None of the callbacks are firing correctly. Could this be an issue with the singleton pattern?

public MeteorHelper(Context context) {
    mMeteor = new Meteor(context, context.getString(R.string.url_server));
    mMeteor.setCallback(this);
    mContext = context;
}

public static synchronized MeteorHelper getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MeteorHelper(context);
    }
    return mInstance;
}

@Override
public void onDataAdded(String collectionName, String documentID, String newValuesJson) {
    Log.v(TAG, "(onDataAdded) collection: " + collectionName + " documentId: " + documentID + " payload: " + newValuesJson);
}

@Override
public void onDataChanged(String collectionName, String documentID, String updatedValuesJson, String removedValuesJson) {
    Log.v(TAG, "(onDataChanged) collection: " + collectionName + " documentId: " + documentID + " payload: " + updatedValuesJson);
}

@Override
public void onDataRemoved(String collectionName, String documentID) {
    Log.v(TAG, "(onDataRemoved) collection: " + collectionName + " documentId: " + documentID);
}

Instead they are just going to my log like so:

06-12 16:19:39.146    6960-6960/com.walintukai.watchdog.debug I/System.out﹕ RECEIVE: {"msg":"added","collection":"assets","id":"cZCMZabRbPmEt3gk5","fields":{"name":"House 1","desc":{"country":"USA","city":"Emeryville","postal":"942828","street":"Christie Ave","year":2004}}}
06-12 16:19:39.146    6960-6960/com.walintukai.watchdog.debug I/System.out﹕ RECEIVE: {"msg":"ready","subs":["fff1d350-5270-490e-87dc-1f6b783e6ab1"]}

Documentation for subscribing to a collection

Thanks for your code, in theory this fits in nicely with what I am trying to do.

I saw a subscribe method in documentation that returns a string
String subscriptionId = mMeteor.subscribe("my-subscription");

Since this example is just string and I might want to subscribe to more complicated data structure than a plain string. like a row in MongoDB. How would I go about doing that? would I have to subscribe to each individual column seperately?

Is there a example code for how one may dynamically subscribe to a bigger collection data and update the UI on the fly without too much code? From the current examples in the documentation its not very easy to know if this is possible.
Thanks!

You've been logged out by the server. Please log in again. [403]

Hello! In 2.0 version (jar) when i succesfull login(with loginWithEmail) and subscribe to a collection from the server, i start to get errors like these(but when i just login without subscribe to any collections i haven't errors):

D/onException: com.firebase.tubesock.WebSocketException: IO Error
D/onException: com.firebase.tubesock.WebSocketException: IO Exception
D/onException: com.firebase.tubesock.WebSocketException: IO Error

payload == {"msg":"result","id":"e3f66184-be65-4175-836b-f976680877aa","error":{"error":403,"reason":"You've been logged out by the server. Please log in again.","message":"You've been logged out by the server. Please log in again. [403]","errorType":"Meteor.Error"}}

I log out after each 30 seconds - 1 minute. In older versions of android-ddp.jar i haven't that problems.

Another example

Hi!

I've done another example of a todo list hosted here:

http://todoandroidddp.meteor.com/

With login, add tasks, receive it reactively and now working in delete, if you don't mind I can upload into a branch or a pull request to master :)

And I'm thinking about to develop offline feature with Realm (https://realm.io/) for the tasks model as example too.

How to install in Android Studio?

Hi - I'm having a bear of a time understanding how to use your code in my project, since there are no obvious .jar or project/gradle files. Once you download the repo, what are the steps to include the library? I'm using Android Studio.

Thanks!

Login with mteor

Hello, I looking for login (mail, password) to meteor server with your app. can you help me ?

Move to gradle

I see the project is not under Gradle build system.
Can we migrate this to gradle ?

WebSockets protocol violation : onDissconnect

i am getting error 'WebSockets protocol violation' when i use "MeteorSingleton.getInstance().loginWithEmail"

log stack trace
Meteor
System.out: send
System.out: message == {"msg":"method","id":"cf4114bb-126d-458d-a8f3-70f6c4ae43b8","params":[{"password":"mypassword","user":{"email":"[email protected]"}}],"method":"login"}
System.out: dispatching
WebSocketException (de.tavendo.autobahn.WebSocketException: RSV != 0 and no extension negotiated)
.WebSocketReader: ended
WebSocketConnection: fail connection [code = 4, reason = WebSockets protocol violation
WebSocketReader: quit
WebSocketWriter: ended
System.out: Meteor
System.out: onClose
System.out: code == 4
System.out: reason == WebSockets protocol violation
System.out: MeteorSingleton
System.out: onDisconnect
System.out: code == 4
System.out: reason == WebSockets protocol violation
MainActivity: WebSockets protocol violation

How to keep user logged in?

How to keep a user logged in or log him automatically without saving his password? I noticed that the login request returns a token. Can't this be used?

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.