How to resolve STATUS_OUT_OF_ORDER_API_CALL error? - android

I am trying to create a Nearby app. I am trying to connect two devices. I found a device an endpoint and then I send a connection request with requestConnection method of Nearby API. In failure listener of this API I am getting "STATUS_OUT_OF_ORDER_API_CALL" in error message. What can be the possible reasons for this error, and how to handle it.
Nearby.getConnectionsClient(context)
.requestConnection(myEndPointName, endPointID,
discoverConnectionLifecycleCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "start connection onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "start connection onFailure " + e.getLocalizedMessage());
// here I am getting STATUS_OUT_OF_ORDER_API_CALL in error message
}
});

POINT_TO_POINT only allows one connection at a time (either incoming or outgoing, not both). OUT_OF_ORDER is given if you try to connect to someone else without first disconnecting from the existing connection.

Related

addOnFailureListener not working in offline mode and network issues

addOnFailureListner does not work for add() data, but addOnFailureListner works for get().
This is not working
WorkPlaceRef.add(DATA).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
//Successfully created - This one triggers when I turn on wifi again.
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Error - This addonFailureListner is not working when there are no network.
}
});
This is working
WorkPlaceRef.get().addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
//Successfully received - This one triggers when I turn on wifi again.
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Error - this addonFialureListner triggers when there is no network.
}
});
It's not a failure to attempt to write data while offline. The Firestore SDK will write the data in a local offline cache first, and eventually synchronize that write with the server when the app comes back online. The success listener will be invoked whenever that happens.
Write failures only happen when there is some problem that can't be retried due to lack of connectivity, such as security rule violations, or exceeding some documented limit of the database.
If you want to know if some document data is not yet synchronized with the server, you can check its metadata to know if a write is pending.

How to implement retry on failed connection for Firestore on Android

Suppose while getting the data, the network connection is turned off and I got an error without getting any data:
Failed to get document because the client is offline.
The method I used is:
mFirestoreDb.collection("somePath").document("anotherPath").get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Log.d(TAG, "onSuccess: " + documentSnapshot.getData());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e);
}
});
How do I handle these type of errors so that when user clicks a retry button, it gets connected to Firestore and try to download the data again?
Forgot to mention that I'm initializing Firestore within ViewModel Factory. Now the problem is that if I initialize Firestore directly within Activity, then I can do a recursive call on a method, if I'm doing it right, but if I get the task from viewmodel, then I cannot do a recursive call like this:
On viewmodel class:
Task<DocumentSnapshot> task;
ViewModelConstructor(...) {
task = mFirestoreDb.collection("path")
.document("anotherPath").get();
}
public Task<DocumentSnapshot> getTask() {
return task;
}
On Activity:
private void someMethod() {
// ...
viewModel.getTask().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e);
someMethod();
}
});
}
P.S. I'm building an app for the first time and the only thing left is to implement a retry button.
Following this official article: https://cloud.google.com/firestore/docs/best-practices
"The Firestore SDKs and client libraries automatically retry failed transactions to deal with transient errors."

XMPP “stream:error (conflict)” when try to reconnect or login

I am using Smack and Openfire server for a chat client, all things working well like chat, sending an invitation for a new addition of user, getting list of available users etc. I don't have a clue what to do if the connection is in a Sticky Service and I added a connection listener to the connection and connection disconnected, let's say for "Internet Connection"
I am using the below code for the connectionlistener.
connection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
Log.i("","Successfully reconnected to the XMPP server.");
}
#Override
public void reconnectionFailed(Exception arg0) {
Log.i("","Failed to reconnect to the XMPP server.");
}
#Override
public void reconnectingIn(int seconds) {
Log.i("","Reconnecting in " + seconds + " seconds.");
}
#Override
public void connectionClosedOnError(Exception arg0) {
Log.i("","Connection to XMPP server was lost.");
Log.v("ONMESSAGE", "Error was " + arg0.toString() + "and Now connecting");
}
#Override
public void connectionClosed() {
Log.i("","XMPP connection was closed.");
}
});
So I thought of adding two lines of code to connectionClosedOnError() i.e
connection.disconnect(new Presence(Presence.Type.unavailable));
//code for connection(new one)
Which gives me some time following error
No Response from Server.
Not connected to server.
conflict error
Now I researched on the issue and found there is still connection when I try to reconnect using the same resource so I got the errors. My question is how to do reconnection and what is the correct procedure for that?
I know how to resolve the issue "XMPP “stream:error (conflict)” as I can provide a String to login() method as a third parameter and it resolves the issue.
That is not my main concern, what I want to know the procedure of reconnection. I tried logging in all methods and it's quite amazing that there are no order of methods being called.

Android Wear Message API unknown error code 4004

I have the following block of code to sent a message to my device, but the message is not getting sent... I do not have any idea why...
Here is the code in which I build my GoogleApiClient:
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.d("dirk", "Google API Client connected");
sendMessage();
}
#Override
public void onConnectionSuspended(int cause) {
Log.d("dirk", "Google API Client disconnected, cause: " + cause);
mConnected = false;
mConnecting = false;
// TODO handle disconnect
}
})
.addOnConnectionFailedListener(new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d("dirk", "Google API Client connection failed, reason: " + result);
mConnected = false;
mConnecting = false;
// TODO handle connection failure
}
})
.addApi(Wearable.API)
.build();
And here is my code that is getting called from the sendMessage method:
Wearable.MessageApi.sendMessage(getClient(), nodeId, PATH, null).setResultCallback(new ResultCallback<SendMessageResult>() {
#Override
public void onResult(SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.d("dirk", "message could not be sent: " + sendMessageResult.getStatus().toString());
Log.d("dirk", "Client connected: " + getClient().isConnected());
// TODO show communication error
}
}
});
The logging is here:
Google API Client connected
message could not be sent: Status{statusCode=unknown status code: 4004, resolution=null}
Client connected: true
So all conditions seem to be fine, but the unknown error code 4004 cannot be resolved (at least I did not find anything wrong so far).
Anyone an idea what could be the reason of this?
Dirk
I've found a documentation that supports my previous assumptions from comment above. Please take a look at WearableStatusCodes class - it contains status codes used in WearableApi method results.
https://developer.android.com/reference/com/google/android/gms/wearable/WearableStatusCodes.html#INVALID_TARGET_NODE
So this error is no longer "unknown":) - 4004 is a code for INVALID_TARGET_NODE.
Please check what value you pass in nodeId variable.

What happened to Packet.setProperty() in (a)Smack 4.0?

Hi i am recently converting from aSmack 3.X to aSmack 4.0. In aSmack 4.0 it seems that the Packet.setProperty() method has been removed. Is there any documentation or examples of how to get this setting to the packet back in aSmack 4.0 as my system relies heavily on aSmack properties.
Thank you in advance.
Those methods where moved out of smack-core into smack-extensions with Smack 4. You now need to use JivePropertiesManager.getProperty(Packet, String) and JivePropertiesManager.addProperty(Packet, String) to add and get those.
More info about the API changes from Smack 3 to Smack 4 can be found at the official "Smack 4.0 Readme and Upgrade Guide".
This is an upgrade of my last FCM XMPP Connection Server application. Now, this project uses the latest version at this time of the Smack library (4.1.8).
https://github.com/carlosCharz/fcmxmppserverv2
This is my sample java project to showcase the Firebase Cloud Messaging (FCM) XMPP Connection Server. This server sends data to a client app via the FCM CCS Server using the XMPP protocol.
https://github.com/carlosCharz/fcmxmppserver
And also I've created a video in youtube where I explain what the changes are.
https://www.youtube.com/watch?v=KVKEj6PeLTc
Hope you find it useful.
Here is a code snippet for the implementation:
public class CcsClient implements StanzaListener {
//Other code
public void connect() throws XMPPException, SmackException, IOException {
XMPPTCPConnection.setUseStreamManagementResumptionDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setServiceName("FCM XMPP Client Connection Server");
config.setHost(Util.FCM_SERVER);
config.setPort(Util.FCM_PORT);
config.setSecurityMode(SecurityMode.ifpossible);
config.setSendPresence(false);
config.setSocketFactory(SSLSocketFactory.getDefault());
// Launch a window with info about packets sent and received
config.setDebuggerEnabled(mDebuggable);
// Create the connection
connection = new XMPPTCPConnection(config.build());
// Connect
connection.connect();
// Enable automatic reconnection
ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();
// Handle reconnection and connection errors
connection.addConnectionListener(new ConnectionListener() {
#Override
public void reconnectionSuccessful() {
logger.log(Level.INFO, "Reconnection successful ...");
// TODO: handle the reconnecting successful
}
#Override
public void reconnectionFailed(Exception e) {
logger.log(Level.INFO, "Reconnection failed: ", e.getMessage());
// TODO: handle the reconnection failed
}
#Override
public void reconnectingIn(int seconds) {
logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
// TODO: handle the reconnecting in
}
#Override
public void connectionClosedOnError(Exception e) {
logger.log(Level.INFO, "Connection closed on error");
// TODO: handle the connection closed on error
}
#Override
public void connectionClosed() {
logger.log(Level.INFO, "Connection closed");
// TODO: handle the connection closed
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
logger.log(Level.INFO, "User authenticated");
// TODO: handle the authentication
}
#Override
public void connected(XMPPConnection arg0) {
logger.log(Level.INFO, "Connection established");
// TODO: handle the connection
}
});
// Handle incoming packets (the class implements the StanzaListener)
connection.addAsyncStanzaListener(this,
stanza -> stanza.hasExtension(Util.FCM_ELEMENT_NAME, Util.FCM_NAMESPACE));
// Log all outgoing packets
connection.addPacketInterceptor(stanza -> logger.log(Level.INFO, "Sent: {}", stanza.toXML()), stanza -> true);
connection.login(fcmServerUsername, mApiKey);
logger.log(Level.INFO, "Logged in: " + fcmServerUsername);
}\
}

Categories

Resources