I am trying to get the details of no.of messages, no.of deleted messages and no.of total messages using javamail api in android. But i am always getting -1 for no.of deleted messages. I couldn't find what is the reason/bug is so please help me with this. Here is my code
class Readmails extends AsyncTask{
Folder inbox;
Folder inbox2;
Properties props = System.getProperties();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
props.setProperty("mail.store.protocol", "imaps");
try
{
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","test123#gmail.com", "testmycode12345");
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
System.out.println("No of New Messages : " + inbox.getNewMessageCount());
System.out.println("No of Deleted Messages : " +inbox.getDeletedMessageCount());
System.out.println("No of total Messages : " + inbox.getMessageCount());
System.out.println("No of Type Messages : " + inbox.getType());
/*Open the inbox using store.*/
inbox.open(Folder.READ_ONLY);
/* Get the messages which is unread in the Inbox*/
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try
{
inbox.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
System.exit(1);
}
catch (MessagingException e)
{
e.printStackTrace();
System.exit(2);
}
return null;
}
}
You are calling getDeletedMessageCount() before you open the inbox.
See this comment in the code, it says it returns -1 on closed folders. Move your call to inbox.open() above your println's
Related
I am making a chat application with smack library and openfire as a server but everytime i exit the chat conversation activity between two users and come back, the whole chat gets erased. I have already enabled archive settings to store one to one messages in the server but i do not know how to implement it in the app.
I want to show chats history in recyclerview by the sender and the receiver in the recyclerview.
currently i have implemented this function which caused error
private void setChatHistory(String entityBareId) {
EntityBareJid jid = null;
try {
jid = JidCreate.entityBareFrom(entityBareId);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
MamManager manager = MamManager.getInstanceFor(mConnection);
MamManager.MamQueryResult r = null;
try {
try {
r = manager.mostRecentPage(jid, 10);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
if (r.forwardedMessages.size() >= 1) //printing first of them
{
Message message = (Message) r.forwardedMessages.get(0).getForwardedStanza();
Log.i("mam", "message received" + message.getBody());
MessagesData data = new MessagesData("send",message.getBody());
mMessagesData.add(data);
mAdapter = new ConversationAdapter(mMessagesData);
recyclerView.setAdapter(mAdapter);
}
}
Error was
Attempt to read from field 'java.util.List org.jivesoftware.smackx.mam.MamManager$MamQueryResult.forwardedMessages' on a null object reference
At r.forwardedmessages.size()>=1.
Thanks in advance
If you want to keep history of conversation, you must save them in database. MAM just for fetching old conversation from server like when you uninstall or logout the app and decide to reinstall and get old messages.
For getting messages from server be sure you already enabled it, then forwarded messages shouldnt be null. here is a guide to enable it.
I have built a chat application using an Openfire (xmpp) server. One-to-one person chats are working fine and the messages are delivered instantly. But when we send a message inside a group, the first message gets delayed and the second message is delivered instantly.
MultiUserChatManager groupChat =
MultiUserChatManager.getInstanceFor(connection).getMultiUserChat("group_name");
groupChat.send("Message object");
Why is the first message getting delayed?
MUC Creation is
MultiUserChatManager mchatManager = MultiUserChatManager.getInstanceFor(xmpptcpConnection);
MultiUserChat mchat = mchatManager.getMultiUserChat(group);
if (!mchat.isJoined()) {
Log.d("CONNECT", "Joining room !! " + group + " and username " + username);
boolean createNow = false;
try {
mchat.createOrJoin(username);
createNow = true;
} catch (Exception e) {
Log.d("CONNECT", "Error while creating the room " + group + e.getMessage());
}
if (createNow) {
Form form = mchat.getConfigurationForm();
Form submitForm = form.createAnswerForm();
List<FormField> formFieldList = submitForm.getFields();
for (FormField formField : formFieldList) {
if(!FormField.Type.hidden.equals(formField.getType()) && formField.getVariable() != null) {
submitForm.setDefaultAnswer(formField.getVariable());
}
}
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
submitForm.setAnswer("muc#roomconfig_publicroom", true);
mchat.sendConfigurationForm(submitForm);
//mchat.sendConfigurationForm(
// new Form(DataForm.Type.submit)); //this is to create the room immediately after join.
}
}
Log.d("CONNECT", "Room created!!");
return true;
} catch (SmackException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
}
There's an issue about creation and a kind of side-effect propagated on sending.
I think simply that you need to join the chat the first time since you didn't before and the first message also activate the Groupchat on server, so the first message it's delayed because you didn't finalized the multiuserchat creation.
How to fix.
In creation phase, this part must be improved:
if (!mchat.isJoined()) {
Log.d("CONNECT", "Joining room !! " + group + " and username " + username);
boolean createNow = false;
try {
mchat.createOrJoin(username);
createNow = true;
} catch (Exception e) {
Log.d("CONNECT", "Error while creating the room " + group + e.getMessage());
}
With just:
boolean createNow
try
{
if (!mchat.isJoined())
{
createNow = mchat.createOrJoin(username);
}
}
catch (Exception e)
{
throw new Exception("ERROR!");
}
and after this invokation:
mchat.sendConfigurationForm(submitForm);
add:
if (!mchat.isJoined()) {
mchat.join(username);
}
creationOrJoin method it's about creation OR join (as name says): to activate the chat, you must join it after the creation phase.
However createOrJoin has maybe an unexpected behaviour due a double check about already joined rooms to keep syncro between session in client and session on server, so the mchat.join() must be invoked after.
An explicit name can sounds like: mustCreateBeforeOrCanJoinDirectly()
I've been working with Azure on the Android OS and I managed to upload my video file (.mp4) to a Container I had already prepared for it.
I did this by getting a Shared Access Signature (SAS) first, which provided me with:
a temporary key
the name of the container to where I want to send the files
the server URI
Then, I started an AsyncTask to send the file to the container using the "upload".
I checked the container, and the file gets uploaded perfectly, no problems on that end.
My question is regarding the progress of the upload. Is it possible to track it? I would like to have an upload bar to give a better UX.
P.S - I'm using the Azure Mobile SDK
Here's my code:
private void uploadFile(String filename){
mFileTransferInProgress = true;
try {
Log.d("Funky Stuff", "Blob Azure Config");
final String gFilename = filename;
File file = new File(filename); // File path
String blobUri = blobServerURL + sharedAccessSignature.replaceAll("\"", "");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
//Container name here
CloudBlobContainer container = blobCLient.getContainerReference(blobContainer);
blob = container.getBlockBlobReference(file.getName());
//fileToByteConverter is a method to convert files to a byte[]
byte[] buffer = fileToByteConverter(file);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
if (blob != null) {
new UploadFileToAzure().execute(inputStream);
}
} catch (StorageException e) {
Log.d("Funky Stuff", "StorageException: " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("Funky Stuff", "IOException: " + e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.d("Funky Stuff", "Exception: " + e.toString());
e.printStackTrace();
}
mFileTransferInProgress = false;
//TODO: Missing ProgressChanged method from AWS
}
private class UploadFileToAzure extends
AsyncTask <ByteArrayInputStream, Void, Void>
{
#Override
protected Void doInBackground(ByteArrayInputStream... params) {
try {
Log.d("Funky Stuff", "Entered UploadFileToAzure Async" + uploadEvent.mFilename);
//Method to upload, takes an InputStream and a size
blob.upload(params[0], params[0].available());
params[0].close();
} catch (StorageException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Thanks!
You can split your file and send its part using Block, there is a good example of your case in this link but it used C# so you should find the corresponding function in the android library reference.
Basically instead of sending you file as one big file, you split it to multiple files (bytes) and send it to azure so you can track the progress on how many bytes that already sent to azure
Has anyone been able to add custom commands in the ChromeCast API? I was successful in getting the TicTacToe example working with my developer ID as well as modified Protocol string (changed on both the client and server).
On the Android side, I have the existing "join" command which works, and I am adding a new "image" command:
public final void join(String name) {
try {
Log.d(TAG, "join: " + name);
JSONObject payload = new JSONObject();
payload.put(KEY_COMMAND, KEY_JOIN);
payload.put(KEY_NAME, name);
sendMessage(payload);
} catch (JSONException e) {
Log.e(TAG, "Cannot create object to join a game", e);
} catch (IOException e) {
Log.e(TAG, "Unable to send a join message", e);
} catch (IllegalStateException e) {
Log.e(TAG, "Message Stream is not attached", e);
}
}
public final void sendImage(String sURL) {
try {
Log.d(TAG, "sendImage");
JSONObject payload = new JSONObject();
payload.put(KEY_COMMAND, KEY_IMAGE);
payload.put(KEY_URL, sURL);
sendMessage(payload);
} catch (JSONException e) {
Log.e(TAG, "Cannot create object to send image", e);
} catch (IOException e) {
Log.e(TAG, "Unable to send an image message", e);
} catch (IllegalStateException e) {
Log.e(TAG, "Message Stream is not attached", e);
}
}
If I call the join command, it works fine and I can see the message logged through the console in the browser. But if I call the sendImage function, I get the following error:
"onEnded failed to connect channel: protocol error"
On the ChromeCast side, I can see when a valid command is received. This function is getting called when I send the join command, but not when I send my custom "image" command.
/**
* Message received event; determines event message and command, and
* choose function to call based on them.
* #param {event} event the event to be processed.
*/
onMessage: function(event) {
console.log('***== pre onMessage ==***');
var message = event.message;
var channel = event.target;
console.log('********onMessage********' + JSON.stringify(message));
console.log('mPlayer1: ' + this.mPlayer1);
console.log('mPlayer2: ' + this.mPlayer2);
if (message.command == 'join') {
this.onJoin(channel, message);
} else if (message.command == 'leave') {
this.onLeave(channel);
} else if (message.command == 'move') {
this.onMove(channel, message);
} else if (message.command == 'queue_layout_request') {
this.onQueueLayoutRequest(channel);
} else if (message.command == 'image') {
this.onImage(channel, message);
} else if (message.command == 'video') {
this.onVideo(channel, message);
} else if (message.command == 'song') {
this.onSong(channel, message);
} else {
cast.log.error('Invalid message command: ' + message.command);
}
},
Any ideas? Is there somewhere else where I need to define my custom commands?
EDITED: also showing the onImage prototype:
/**
* Image event: display an image
* #param {cast.receiver.channel} channel the source of the move, which
* determines the player.
* #param {Object|string} message contains the URL of the image
*/
onImage: function(channel, message) {
console.log('****onImage: ' + JSON.stringify(message));
//Hide video and show image
mVideo.style.visibility='hidden';
mImage.style.visibility='visible';
mImage.src = message.url;
},
That usually means there was a JavaScript error in your receiver. Open Chrome on port 9222 at the IP address of your ChromeCast device and use the Chrome developer tools to debug the issue.
Did you declare a new function "onImage" in your receiver prototype for the message handler?
I can receive my mails with Imap with this code sample :
URLName server = new URLName("imaps://" + username + ":"+ password + "#imap.gmail.com/INBOX");
Session session = Session.getDefaultInstance(new Properties(), null);
Folder folder = session.getFolder(server);
if (folder == null)
{
System.exit(0);
}
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
But sometimes Imap doesn't give any service and at those times I want to use Pop but I couldn't use it with my code. It is different the other codes for using receive mail. But in Android only this code is working.
What should I change in this code to work with Pop?
First, there's a nice URLName constructor that takes all the component pieces as separate parameters, so you don't have to do string concatenation.
Switch from IMAP to POP3 requires changing the protocol name as well as the host name. See the JavaMail FAQ for examples. The protocol name is "pop3s" and the host name is "pop.gmail.com".
Finally, you should use Session.getInstance instead of Session.getDefaultInstance. Compare the javadocs for the two methods to understand why.
How about this one.Really worked for me!!(Source:here)
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
URLName url = new URLName("pop3", "pop.gmail.com", 995, "","youremailid#gmail.com",yourpassword);
Session session = Session.getInstance(pop3Props, null);
Store store = new POP3SSLStore(session, url);
try {
store.connect();
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Folder folder = null;
try {
folder = store.getDefaultFolder();
folder = folder.getFolder("INBOX");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (folder == null) {
System.exit(0);
}
try {
folder.open(Folder.READ_ONLY);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try retreiving folder via store object.And also mention that the folder you wish to retreive is INBOX!Also note that in settings,port number is 995 form pop.(You may leave the first six lines as they are.)