I was hoping someone may be able to help or at least point me in the right direction. I'm writing an android app that publishes/receives messages and i'm trying to use PubNub to accomplish this task. In my view I firstly unsubscribe from a group name and then subscribe to it. When I then publish a message, I successfully get one message. If I then leave the view and re-enter it, when I publish a message I get a duplicate. If I do the same again, the message is triplicated and so on.
Could someone please look at my code or give me any advice.
Many thanks.
private Pubnub pubnub = new Pubnub("pub-key", "sub-key");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(com.rickeshjobanputra.snapapp.R.layout.activity_group);
GroupName = intent.getStringExtra("GroupName");
String uuid = "12345";
pubnub.setUUID(uuid);
pubnub.unsubscribe(GroupName);
try {
pubnub.subscribe(GroupName, new Callback() {
#Override
public void successCallback(String channel, final Object message) {
System.out.println("SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
});
} catch (PubnubException e) {
System.out.println(e.toString());
}
addListenerOnButton();
}
private void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(com.rickeshjobanputra.snapapp.R.id.snap_something_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pubnub.publish(GroupName, "test", new Callback() {
});
}
});
}
UPDATE
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
pubnub.unsubscribeAllChannels();
try {
pubnub.subscribe("test", new Callback() {
#Override
public void connectCallback(String channel, Object message) {
pubnub.publish("test", "Hello from the PubNub Java SDK", new Callback() {});
}
#Override
public void successCallback(String channel, final Object message) {
System.out.println("SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
});
} catch (PubnubException e) {
System.out.println(e.toString());
}
}
Related
I have created a private channel, and joined the channel. I like to invite another user to join that channel and chat. To be clear, this should be a chat between two members only.
public class MainActivity extends AppCompatActivity {
/*
Change this URL to match the token URL for your Twilio Function
*/
final static String SERVER_TOKEN_URL = "https://example.com/twilio/token/";
final static String MY_CHANNEL_NAME = "testchat1234567810";
final static String TAG = "TwilioChat";
// Update this identity for each individual user, for instance after they login
private String mIdentity ;
private String accessToken;
private RecyclerView mMessagesRecyclerView;
private MessagesAdapter mMessagesAdapter;
private ArrayList<Message> mMessages = new ArrayList<>();
private EditText mWriteMessageEditText;
private Button mSendChatMessageButton;
private ChatClient mChatClient;
private Channel mGeneralChannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessagesRecyclerView = (RecyclerView) findViewById(R.id.messagesRecyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// for a chat app, show latest at the bottom
layoutManager.setStackFromEnd(true);
mMessagesRecyclerView.setLayoutManager(layoutManager);
mMessagesAdapter = new MessagesAdapter();
mMessagesRecyclerView.setAdapter(mMessagesAdapter);
mWriteMessageEditText = (EditText) findViewById(R.id.writeMessageEditText);
mSendChatMessageButton = (Button) findViewById(R.id.sendChatMessageButton);
mSendChatMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createOrJoinChannel();
if (mGeneralChannel != null) {
String messageBody = mWriteMessageEditText.getText().toString();
Message.Options options = Message.options().withBody(messageBody);
// mGeneralChannel.getMembers().add();
Members members = mGeneralChannel.getMembers();
if (members != null) {
ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
for (int i = 0; i < list.size(); i++) {
Log.i(TAG, "member " + i + list.get(i).getIdentity());
}
}
mGeneralChannel.getMembers().inviteByIdentity("user1#gmail.com", new StatusListener() {
#Override
public void onSuccess() {
Log.d(TAG, "User Invited on send!");
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "chats: inviting user" + errorInfo.getMessage());
}
});
mGeneralChannel.getMembersCount(new CallbackListener<Long>() {
#Override
public void onSuccess(Long aLong) {
Log.e("member count >>", aLong + "");
}
});
mGeneralChannel.getMessages().sendMessage(options, new CallbackListener<Message>() {
#Override
public void onSuccess(Message message) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Message created");
// need to modify user interface elements on the UI thread
mWriteMessageEditText.setText("");
}
});
}
});
}
}
});
retrieveAccessTokenfromServer();
}
private void retrieveAccessTokenfromServer() {
String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Log.e("deviceid >>",deviceId);
String tokenURL = SERVER_TOKEN_URL + deviceId;
Ion.with(this)
.load(tokenURL)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Log.e("result >>", result.toString() + "");
if (e == null) {
mIdentity = result.get("identity").getAsString();
accessToken = result.get("token").getAsString();
setTitle(mIdentity);
ChatClient.Properties.Builder builder = new ChatClient.Properties.Builder();
// ChatClient.setLogLevel(Log.VERBOSE);
ChatClient.Properties props = builder.createProperties();
ChatClient.create(MainActivity.this, accessToken, props, mChatClientCallback);
} else {
Toast.makeText(MainActivity.this,
R.string.error_retrieving_access_token, Toast.LENGTH_SHORT)
.show();
}
}
});
}
private CallbackListener<ChatClient> mChatClientCallback =
new CallbackListener<ChatClient>() {
#Override
public void onSuccess(ChatClient chatClient) {
mChatClient = chatClient;
// createOrJoinChannel();
// loadChannels();
Log.d(TAG, "Success creating Twilio Chat Client");
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG, "Error creating Twilio Chat Client: " + errorInfo.getMessage());
}
};
private void createOrJoinChannel() {
//Only SID or unique name of channel can be supplied as parameter
mChatClient.getChannels().getChannel(MY_CHANNEL_NAME, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
if (channel.getStatus() == Channel.ChannelStatus.JOINED) {
// already in the channel, load the messages
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
} else if (channel.getStatus() == Channel.ChannelStatus.NOT_PARTICIPATING) {
// already in the channel, load the messages
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
} else {
// join the channel
joinChannel(channel);
}
} else {
Log.i(TAG, "Error occurred in getting channel");
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "Error retrieving channel: " + errorInfo.getMessage());
createChannel();
}
});
}
private void joinChannel(final Channel channel) {
Log.i(TAG, "inside join channel" + channel.getUniqueName());
Log.i(TAG, "channel status: " + channel.getStatus());
Members members = channel.getMembers();
if (members != null) {
ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
for (int i = 0; i < list.size(); i++) {
Log.i(TAG, "member " + i + list.get(i).getIdentity());
}
} else {
Log.i(TAG, "null object"); //Getting this even when I get
//"Member already exists" error
}
channel.join(new StatusListener() {
#Override
public void onSuccess() {
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
}
#Override
public void onError(ErrorInfo errorInfo) {
//Error joining channel: Member already exists
Log.i(TAG, "Error joining channel: " + errorInfo.getMessage());
}
});
}
private void createChannel() {
mChatClient.getChannels().createChannel(MY_CHANNEL_NAME,
Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
#Override
public void onSuccess(final Channel channel) {
if (channel != null) {
/* channel.getMembersCount(new CallbackListener<Long>() {
#Override
public void onSuccess(Long aLong) {
Log.e("member count >>",aLong+"");
}
});*/
channel.getMembers().inviteByIdentity("user1#gmail.com", new StatusListener() {
#Override
public void onSuccess() {
Log.d(TAG, "User Invited!");
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "chats: inviting user" + errorInfo.getMessage());
}
});
channel.join(new StatusListener() {
#Override
public void onSuccess() {
}
});
setUniqueNameAndJoin(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "chats: " + "Unique name could not be set: " + errorInfo.getMessage());
}
});
}
private void setUniqueNameAndJoin(final Channel channel) {
channel.setUniqueName(MY_CHANNEL_NAME, new StatusListener() {
#Override
public void onSuccess() {
Log.i(TAG, "channel with unique name created " + channel.getUniqueName());
joinChannel(channel);
}
#Override
public void onError(ErrorInfo errorInfo) {
super.onError(errorInfo);
}
});
}
private ChannelListener mDefaultChannelListener = new ChannelListener() {
#Override
public void onMessageAdded(final Message message) {
Log.d(TAG, "Message added");
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// need to modify user interface elements on the UI thread
mMessages.add(message);
mMessagesAdapter.notifyDataSetChanged();
}
});
}
#Override
public void onMessageUpdated(Message message, Message.UpdateReason updateReason) {
Log.d(TAG, "Message updated: " + message.getMessageBody());
}
#Override
public void onMessageDeleted(Message message) {
Log.d(TAG, "Message deleted");
}
#Override
public void onMemberAdded(Member member) {
Log.d(TAG, "Member added: " + member.getIdentity());
}
#Override
public void onMemberUpdated(Member member, Member.UpdateReason updateReason) {
Log.d(TAG, "Member updated: " + member.getIdentity());
}
#Override
public void onMemberDeleted(Member member) {
Log.d(TAG, "Member deleted: " + member.getIdentity());
}
#Override
public void onTypingStarted(Channel channel, Member member) {
Log.d(TAG, "Started Typing: " + member.getIdentity());
}
#Override
public void onTypingEnded(Channel channel, Member member) {
Log.d(TAG, "Ended Typing: " + member.getIdentity());
}
#Override
public void onSynchronizationChanged(Channel channel) {
}
};
class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.ViewHolder> {
class ViewHolder extends RecyclerView.ViewHolder {
public TextView mMessageTextView;
public ViewHolder(TextView textView) {
super(textView);
mMessageTextView = textView;
}
}
public MessagesAdapter() {
}
#Override
public MessagesAdapter
.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
TextView messageTextView = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_text_view, parent, false);
return new ViewHolder(messageTextView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Message message = mMessages.get(position);
String messageText = String.format("%s: %s", message.getAuthor(), message.getMessageBody());
holder.mMessageTextView.setText(messageText);
}
#Override
public int getItemCount() {
return mMessages.size();
}
}
}
And also, I need to accept the invite. How it can be done?
I am using Twilio Programmable chat APIs in android for 1 to 1 chat.
Following is my usecase:
1) I create a unique channel name
2) Check if the channel already exists or not
if channel exists:
user joins channel
else
create a channel with unique name
user joins channel
end
Now, what is happening is, when I am trying to join the channel, it is giving me the error: "Member already exists". So, at this point if I try to check the members of the channel, I get the Member object to be null.
I have 2 doubts at this point:
1) Shouldn't the user object contain this member if it is already a part of the channel?
2) If the user is already a part of the channel, I should be able to send mesages to the channel, by just adding the channelListener, which in this case is not happening.
I don't understand the issue. Following are my code snippets:
ChatClient.Properties props = new ChatClient.Properties.Builder()
.createProperties();
ChatClient.create(ChatActivity.this, accessToken, props, mChatClientCallback);
private CallbackListener<ChatClient> mChatClientCallback =
new CallbackListener<ChatClient>() {
#Override
public void onSuccess(ChatClient chatClient) {
mChatClient = chatClient;
//loadChannels();
Log.i(TAG, "Success creating Twilio Chat Client");
createOrJoinChannel();
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG,"Error creating Twilio Chat Client: " + errorInfo.getMessage());
}
};
private void createOrJoinChannel(){
//Only SID or unique name of channel can be supplied as parameter
mChatClient.getChannels().getChannel(UNIQUE_CHANNEL_NAME, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
} else {
Log.i(TAG, "Error occurred in getting channel");
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG,"Error retrieving channel: " + errorInfo.getMessage());
createChannel();
}
});
}
private void joinChannel(final Channel channel) {
Log.i(TAG, "inside join channel" + channel.getUniqueName());
Log.i(TAG, "channel status: " + channel.getStatus());
Members members = channel.getMembers();
if(members!=null){
ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
for(int i=0; i<list.size(); i++){
Log.i(TAG, "member " + i + list.get(i).getIdentity());
}
}else{
Log.i(TAG, "null object"); //Getting this even when I get
//"Member already exists" error
}
channel.join(new StatusListener() {
#Override
public void onSuccess() {
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
}
#Override
public void onError(ErrorInfo errorInfo) {
//Error joining channel: Member already exists
Log.i(TAG,"Error joining channel: " + errorInfo.getMessage());
});
}
private void createChannel(){
mChatClient.getChannels().createChannel(FRIENDLY_CHANNEL_NAME,
Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
setUniqueNameAndJoin(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG,"chats: " + "Unique name could not be set: " + errorInfo.getMessage());
}
});
}
private void setUniqueNameAndJoin(final Channel channel){
channel.setUniqueName(UNIQUE_CHANNEL_NAME, new StatusListener() {
#Override
public void onSuccess() {
Log.i(TAG, "channel with unique name created " + channel.getUniqueName());
joinChannel(channel);
}
#Override
public void onError(ErrorInfo errorInfo) {
super.onError(errorInfo);
}
});
}
private ChannelListener mDefaultChannelListener = new ChannelListener() {
#Override
public void onMessageAdded(final Message message) {
Log.i(TAG, "Message added");
ChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// need to modify user interface elements on the UI thread
mMessages.add(message);
mMessagesAdapter.notifyItemInserted(mMessages.size()-1);
}
});
}
#Override
public void onMessageUpdated(Message message, Message.UpdateReason updateReason) {
Log.i(TAG, "Message updated: " + message.getMessageBody());
}
#Override
public void onMessageDeleted(Message message) {
Log.d(TAG, "Message deleted");
}
#Override
public void onMemberAdded(Member member) {
Log.i(TAG, "Member added: " + member.getIdentity());
}
#Override
public void onMemberUpdated(Member member, Member.UpdateReason updateReason) {
}
#Override
public void onMemberDeleted(Member member) {
}
#Override
public void onTypingStarted(Channel channel, Member member) {
}
#Override
public void onTypingEnded(Channel channel, Member member) {
}
#Override
public void onSynchronizationChanged(Channel channel) {
}
};
Can someone please explain to me, what am I doing wrong or what should be the correct way of doing things? Thanks in advance!
Twilio developer evangelist here.
You need to check the channel's status for your current user, using channel.getStatus(). There's a good example of this in the Android chat tutorial.
if (this.currentChannel.getStatus() == Channel.ChannelStatus.JOINED) {
// already in the channel, load the messages
} else {
// join the channel
}
I am currently using
https://github.com/NaikSoftware/StompProtocolAndroid
to connect websocket using STOMP. I have a simple implementation as
public class TestActivity extends AppCompatActivity {
private StompClient mStompCLient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
mStompCLient = Stomp.over(WebSocket.class, BASE_URL);
mStompCLient.topic("/topic/online/" + mSharedPreferences.getPrivateKey()).subscribe(new Subscriber<StompMessage>() {
#Override
public void onCompleted() {
Log.i(TAG, "/topic/online/ onCompleted: ");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, "/topic/online/ onError: " + e.getMessage());
}
#Override
public void onNext(StompMessage stompMessage) {
Log.d(TAG, "/topic/online/ onNext: " + stompMessage.getPayload());
String content = "";
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(stompMessage.getPayload());
content = jsonResponse.getString("uri");
} catch (JSONException e) {
e.printStackTrace();
}
listenToUpdatesFromFinalUri(content);
}
});
mStompCLient.lifecycle().subscribe(lifecycleEvent -> {
Log.i(TAG, "onCreate: " + lifecycleEvent.getMessage());
switch (lifecycleEvent.getType()) {
case OPENED:
Log.d(TAG, "Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Error", lifecycleEvent.getException());
break;
case CLOSED:
Log.d(TAG, "Stomp connection closed : " + lifecycleEvent.toString() + " :msg: " + lifecycleEvent.getMessage() + " :escep: " + lifecycleEvent.getException() + " :headers: " + lifecycleEvent.getHandshakeResponseHeaders() + " :type: " + lifecycleEvent.getType());
break;
}
});
mStompCLient.connect();
}
private void listenToUpdatesFromFinalUri(String content) {
mStompCLient.topic(content).subscribe(new Subscriber<StompMessage>() {
#Override
public void onCompleted() {
Log.i(TAG," onCompleted: ");
}
#Override
public void onError(Throwable e) {
Log.i(TAG, " onError: " + e.getMessage());
}
#Override
public void onNext(StompMessage stompMessage) {
Log.d(TAG, " onNext: " + stompMessage.getPayload());
}
});
}
#Override
protected void onStop() {
super.onStop();
disconnectStomp();
}
private void disconnectStomp() {
mStompCLient.disconnect();
}
}
Here I am trying to listen to the new subscription channel sent by the server after connection is established. It works if the subscribe() is called before the connect is called. But the final uri/subscription channel subscribed in listenToUpdatesFromFinalUri() function is not static so I need can't add subscription before the connect. I am currently unable to get response for the final uri/subscription. Any help is appreciated.
The issue has been solved in the new version 1.1.6
I have created an application that implements app to app calling using Sinch. It works only when the caller knows the name of the recipient.
To overcome this Sinch suggested to use PubNub to get the user state. They also have a tutorial here. The problem is that tutorial is old and PubNub has updated their API since. I tried to implement the functionality using their new API on my own using their docs, but it is not working or more accurately I don't know how to do it.
My current code is:
public class LoggedUsers extends Activity {
private PubNub pubNub;
String name;
private ArrayList users;
private JSONArray loggedUserList;
ListView UserList;
TextView allUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
allUsers = (TextView) findViewById(R.id.JSONFromPubNub);
SharedPreferences sp = getSharedPreferences("User_Details", MODE_APPEND);
try {
name = sp.getString("UserName", "");
} catch (NullPointerException e) {
}
final PNConfiguration pnc = new PNConfiguration();
pnc.setPublishKey("publish key");
pnc.setSubscribeKey("subscribe key");
pnc.setUuid(name);
pubNub = new PubNub(pnc);
users = new ArrayList<String>();
UserList = (ListView) findViewById(R.id.listView);
String user = getUserStatus();
allUsers.setText(user);
final ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), R.layout.single_item_list, users);
UserList.setAdapter(adapter);
pubNub.addListener(new SubscribeCallback() {
#Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
HashMap <String,String> map = new HashMap();
map.put("State","Offline");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
} else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
// Connect event. You can do stuff like publish, and know you'll get it.
// Or just use the connected event to confirm you are subscribed for
// UI / internal notifications, etc
HashMap <String,String> map = new HashMap();
map.put("State","Online");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
/* if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
pubnub.publish().channel("awesomeChannel").message("hello!!").async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult result, PNStatus status) {
// Check whether request successfully completed or not.
if (!status.isError()) {
// Message successfully published to specified channel.
}
// Request processing failed.
else {
// Handle message publish error. Check 'category' property to find out possible issue
// because of which request did fail.
//
// Request can be resent using: [status retry];
}
}
});
}*/
} else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
HashMap <String,String> map = new HashMap();
map.put("State","Online");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
// Happens as part of our regular operation. This event happens when
// radio / connectivity is lost, then regained.
} else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {
// Handle messsage decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
#Override
public void message(PubNub pubnub, PNMessageResult message) {
}
#Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
}
public String getUserStatus(){
final StringBuilder allUsers = new StringBuilder();
pubNub.subscribe().channels(Arrays.asList("CallingChannel1")).withPresence().execute();
pubNub.hereNow()
// tailor the next two lines to example
.channels(Arrays.asList("CallingChannel1"))
.includeState(true)
.includeUUIDs(true)
.async(new PNCallback<PNHereNowResult>() {
#Override
public void onResponse(PNHereNowResult result, PNStatus status) {
if (status.isError()) {
// handle error
return;
}
for (PNHereNowChannelData channelData : result.getChannels().values()) {
allUsers.append("---");
allUsers.append("channel:" + channelData.getChannelName());
allUsers.append("occoupancy: " + channelData.getOccupancy());
allUsers.append("occupants:");
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
allUsers.append("uuid: " + occupant.getUuid() + " state: " + occupant.getState());
}
}
}
});
return allUsers.toString();
}
#Override
protected void onResume() {
super.onResume();
}
}
Here are my problems:
I am trying to display all the data that I receive in a textview (later it will arranged in a listview or a recycler view) but I am getting a blank screen so I am getting null from the server.
The user status should be constantly updated to know if the user changes state (online -> offline) but there seems to be no async calls made in the code so I think it will be executed only once and then the dataset is not being changed.
How can I solve my problems?
PubNub Presence
You can monitor online and state changes using PubNub Presence. When you subscribe, subscribe with presence enabled and you will get state-change, join, leave & timeout events in the presence callback.
Callback callback = new Callback() {
#Override
public void successCallback(String channel, Object message) {
System.out.println(channel + " : "
+ message.getClass() + " : " + message.toString());
// take action on the presence events here
}
#Override
public void connectCallback(String channel, Object message) {
System.out.println("CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void disconnectCallback(String channel, Object message) {
System.out.println("DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void reconnectCallback(String channel, Object message) {
System.out.println("RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void errorCallback(String channel, PubnubError error) {
System.out.println("ERROR on channel " + channel
+ " : " + error.toString());
}
};
try {
pubnub.presence("my_channel", callback);
}
catch (PubnubException e) {
System.out.println(e.toString());
}
It appears Sinch is using a rather old version of the PubNub Android SDK. I would think you could still use PubNub Android SDK v4 to do what you need to do outside of Sinch SDK unless there is some explicit requirements by Sinch to use the same version of the SDK.
I am working on websocket communication with Autobahn.
On the main.class of my app, I set to call 'connect()' when users click a button.
// Toggle Button event
tButton = (ToggleButton) findViewById(R.id.toggleButton1);
tButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
}else{
}
}
});
And after that, there is MyOffers.class, and if this class is accessed,
MyOffers_Fragment class is produced four times automatically, because MyOffers.class contains 'carousel view' and there are four products.
On 'MyOffers_Fragment' class, when users click one of the image of products, message should be sent.
if (pos == 0) {
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setOnClickListener(new ImageButton.OnClickListener(){
public void onClick(View v){
String id = "Product0";
Log.d(TAG, "Current product is : " + id);
A.sendMessage(id);
}
});
}
But 'mConnection.sendTextMessage(id1);' this line makes 'NullPointerException' error.
There is a class 'Websocket_Connector.class'
public class WebSocket_Connector {
private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
public void sendMessage(String message) {
connect("ws://192.168.x.xxx:xxxx");
mConnection.sendTextMessage(message);
}
}
I called 'connect()' in the main page class, and after that try to send message.
But, it's not working..Can you please help me out?
public class WebSocket_Connector {
private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
public void sendMessage(String message) {
if (mConnection.isConnected())
mConnection.sendTextMessage(message);
else {
tmpString = message;
connect("ws://192.168.x.xxx:xxxx");
}
}
}