I have start a timer which call getMessage webservice which return comming message for that user arraylist size always show right number of messages but when show in list view of that message show only last message send give by web service I have use this code.
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if(msg.arg1!=RECIEVEFAILURE)
{
objrReceiveMessageSiteList =(ArrayList<ReceiveMessageSiteList>)msg.obj;
System.out.println("objrReceiveMessageSiteList.get(0)"+objrReceiveMessageSiteList.get(0).getMessageStatus());
System.out.println("objrReceiveMessageSiteList.get(0)"+objrReceiveMessageSiteList.size());
if(objrReceiveMessageSiteList.size()!=0 && !objrReceiveMessageSiteList.get(0).getMessageStatus().equalsIgnoreCase("No New Message"))
{
for(int i=0;i<objrReceiveMessageSiteList.size();i++)
{
objkeyvaluepair.setMessage(objrReceiveMessageSiteList.get(i).getMessage());
objkeyvaluepair.setMessageType(objrReceiveMessageSiteList.get(i).getMessageType());
objkeyvaluepair.setTimeStamp(objrReceiveMessageSiteList.get(i).getTimeStamp());
objkeyvaluepair.setSenderFirstName(objrReceiveMessageSiteList.get(i).getSenderFirstName());
objkeyvaluepair.setSenderId(objrReceiveMessageSiteList.get(i).getSenderId());
objkeyvaluepair.setRecieverFirstName(objrReceiveMessageSiteList.get(i).getReceiverFirstName());
messagerecord.add(objkeyvaluepair);
System.out.println("MESSAGE SIZE"+messagerecord.size());
System.out.println("MESSAGE---------- findeee"+messagerecord.get(i).getMessage());
}
System.out.println("objrReceiveMessageSiteList.get(0)--------------"+objrReceiveMessageSiteList.get(0).getMessageStatus());
message.setText(""+messagerecord.size());
}
}
}
};
inside this for loop arraylist is showing right message in syste.out.println.but when sending in adapter set adapter take right size but show only last message in all list view.please help me
You are adding the same object (objkeyvaluepair) to the ArrayList each iteration through the nested for loops.
In the inner-most for loop, you should be creating a new objkeyvaluepair object and then add this new object to the ArrayList.
change this method to the following:
public void handleMessage(Message msg)
{
super.handleMessage(msg);
if(msg.arg1!=RECIEVEFAILURE)
{
objrReceiveMessageSiteList =(ArrayList<ReceiveMessageSiteList>)msg.obj;
System.out.println("objrReceiveMessageSiteList.get(0)"+objrReceiveMessageSiteList.get(0).getMessageStatus());
System.out.println("objrReceiveMessageSiteList.get(0)"+objrReceiveMessageSiteList.size());
if(objrReceiveMessageSiteList.size()!=0 && !objrReceiveMessageSiteList.get(0).getMessageStatus().equalsIgnoreCase("No New Message"))
{
for(int i=0;i<objrReceiveMessageSiteList.size();i++)
{
//Create Local object of the Objkeyvaluepair here, for example
//ObjectKeyValuePair objkeyvaluePair=new OjectKeyvaluePair();
objkeyvaluepair.setMessage(objrReceiveMessageSiteList.get(i).getMessage());
objkeyvaluepair.setMessageType(objrReceiveMessageSiteList.get(i).getMessageType());
objkeyvaluepair.setTimeStamp(objrReceiveMessageSiteList.get(i).getTimeStamp());
objkeyvaluepair.setSenderFirstName(objrReceiveMessageSiteList.get(i).getSenderFirstName());
objkeyvaluepair.setSenderId(objrReceiveMessageSiteList.get(i).getSenderId());
objkeyvaluepair.setRecieverFirstName(objrReceiveMessageSiteList.get(i).getReceiverFirstName());
messagerecord.add(objkeyvaluepair);
System.out.println("MESSAGE SIZE"+messagerecord.size());
System.out.println("MESSAGE---------- findeee"+messagerecord.get(i).getMessage());
}
System.out.println("objrReceiveMessageSiteList.get(0)--------------"+objrReceiveMessageSiteList.get(0).getMessageStatus());
message.setText(""+messagerecord.size());
}
}
}
};
Related
Hi I am developing a chat application like whatsapp. I have to load the chat history from the api when user scrolls down like in whatsapp. I get the data and set it to the adapter. But the history is loading at the bottom of recycler view. I need to add it on top for every scroll. This is my code. Please help me. Thanks in advance.
if (Status.equals("1")) {
historyList = resp.getHistory();
Log.i("history size",String.valueOf(resp.getHistory().size()));
String historysize = String.valueOf(resp.getHistory().size());
Message message = new Message();
for (int i = 0; i < resp.getHistory().size(); i++) {
String fromusertoken = String.valueOf(resp.getHistory().get(i).getFromUserToken());
String txtmsg = resp.getHistory().get(i).getMessage();
String username = String.valueOf(resp.getHistory().get(i).getFromUserName());
if (fromusertoken.equals(user_token)) {
Message messages = new Message();
messages.setUser_token(fromusertoken);
messages.setUsername(username);
messages.setIsMine(true);
messages.setMessage(txtmsg);
messageAdapter.add(messages);
}
else {
Message messages = new Message();
messages.setUser_token(fromusertoken);
messages.setUsername(username);
messages.setIsMine(false);
messages.setMessage(txtmsg);
messageAdapter.add(messages);
}
}
messageAdapter.notifyDataSetChanged();
onItemsLoadComplete();
Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Single_chat.this, msg, Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(Single_chat.this, "No Response", Toast.LENGTH_SHORT).show();
}
}
There is a way to set the item on top by editing the adapter class not the activity. We have to add the item list like messagelist.add(0,message). Now only i found. For your regular chat you have to add as normal like messagelist.add(message). This will add the item at bottom. Hope this will be useful for others.
public void add(Message message) {
messageList.add(message);
notifyItemInserted(messageList.size() - 1);
}
public void add(int i,Message message) {
messageList.add(0,message);
notifyItemInserted(messageList.size() - 1);
}
I changed the list in adapter as messagelist.add(0,message). It worked.
public void add(Message message) {
messageList.add(0,message);
notifyItemInserted(messageList.size() - 1);
}
you can insert the history message at the index 0
messageAdapter.add(0,messages);
every iteration it will replace the first message by the last inserted message.
chatHistoyList.add(adapter.getCurrentChatList());
adapter.setData(chatHistoryList);
adapter.notifyDataSetChanged();
//This method has to be in adapter
public List<Chat> getCurrentChatList() {
return currentChatList;
}
I have a bluetooth printer integrated to my app and if I do some transactions, I can print the receipt to the customer. I have a method to handle the printing of receipts. Currently, I can print only one receipt but I would like to print the receipts twice.
Should I run the for loop twice so the method which prints my receipt is executed twice.
private void printReceipt(final Transaction transaction) {
showProgressPopup(getString(R.string.printing_dialog_message));
Runnable printThread = new Runnable() {
#Override
public void run() {
final BitSet resultBit = new BitSet(1);
try {
final ReceiptMetadata receiptMetadata =
AirFiUtils.getPaymentDeviceReceiptMetaData(getAirlineProfile(),
AirFiUtils.getMerchantAccount(getAirFiActivity()));
if (null != receiptMetadata) {
PrinterManager.printReceipt(PrinterType.valueOf(receiptMetadata.getPrinter().get(0)),
ReceiptType.CASH, receiptMetadata, transaction, getActivity().getApplicationContext(),
transaction.isSignatureCard());
resultBit.set(0, true);
}
} catch (Exception e) {
LOG.error("Error in printing ", e);
resultBit.set(0, false);
}
}
};
new Thread(printThread).start();
}
use for loop inside your if statement e.g
if(your_condition){
for(int i=0;i<2;i++){
//your desired code to print receipt
}}
or call your specific function two time which is need to be print receipt by applying for loop
I am getting data (List) from an API and I am trying to update my AutcompleteTextView with this data.
This is how I currently do :
I have a TextWatcher which calls a the method to get the data in afterTextChanged, so every time the user stops typing the method is called, and the adapter is notified with ``notifyDataSetChanged :
//in onCreate
addressAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,suggestions_address);
at_address.setAdapter(addressAdapter);
...
#Override
public void afterTextChanged(Editable s) {
autoComplete(s);
addressAdapter.notifyDataSetChanged();
//suggestions_address is the updated list, and when I print it I can see the
//results so it is not empty
Log.i("addresses",suggestions_address.toString());
}
...
class SuggestionQueryListener implements ResultListener<List<String>> {
#Override
public void onCompleted(List<String> data, ErrorCode error) {
if (error != ErrorCode.NONE) {
Toast.makeText(MainActivity2.this,error.toString(),Toast.LENGTH_LONG).show();
} else {
suggestions_address.clear();
for(int i = 0;i<data.size();i++){
suggestions_address.add(data.get(i));
}
}
}
}
public void autoComplete(CharSequence s) {
try {
String term = s.toString();
TextSuggestionRequest request = null;
request = new TextSuggestionRequest(term).setSearchCenter(new GeoCoordinate(48.844900, 2.395658));
request.execute(new SuggestionQueryListener());
if (request.execute(new SuggestionQueryListener()) != ErrorCode.NONE) {
//Handle request error
//...
}
} catch (IllegalArgumentException ex) {
//
}
}
But it seems that the adapter is not really updated because it doesn't show the suggestions when I type something.
Also, before doing this with an AutoCompleteTextView I did it with a listView, with the same process, and everything worked well.
Any ideas or solutions would be really appreciated
EDIT : I noticed something really strange : the data is not binded to the adapter, because adapter#getCount always returns 0, even if the list is not empty. But when I remove at_address.setAdapter(addressAdapter), the data adapter is updated and adapter#getCount returns the right number of elements.
I am really confused right now, please help !
Instead of this:
for(int i = 0;i<data.size();i++){
suggestions_address.add(data.get(i));
}
you can use just this:
suggestions_address.addAll(data);
you are calling notifyDataSetChanged after you start the request, you should call it after you get the result and update the suggestions_address, so call notifyDataSetChanged inside onCompleted
I have been able to create the if statement that checks for the string and it returns the toast message that i created but it keeps showing the toast message every time i open the chat. even if the most recent message doesn't contain the string I am looking for so i am assume it isn't checking to see if it is the last message received and it doesn't check to see if it is unread. the code is below. the reason i am trying to do this is because my parents share a facebook account and i want an easy way to display if the message is signed mom or dad. the code below only has the check for mom once it works i will be adding the check for dad signature. I am using the open source message client Xabber. Thank you for help.
public void setVisibleChat(String account, String user) {
final boolean remove = !AccountManager.getInstance()
.getArchiveMode(account).saveLocally();
AbstractChat chat = getChat(account, user);
if (chat == null)
chat = createChat(account, user);
else {
// Mark messages as read and them delete from db if necessary.
final ArrayList<MessageItem> messageItems = new ArrayList<MessageItem>();
for (MessageItem messageItem : chat.getMessages()) {
if (!messageItem.isRead()) {
messageItem.markAsRead();
messageItems.add(messageItem);
}
if (chat.getLastText().contains("Mom") && (!messageItem.isRead()));{
Toast.makeText(Application.getInstance(), "Message from Mom!", Toast.LENGTH_SHORT).show();
}
}
Application.getInstance().runInBackground(new Runnable() {
#Override
public void run() {
Collection<Long> ids = getMessageIds(messageItems, remove);
if (remove)
MessageTable.getInstance().removeMessages(ids);
else
MessageTable.getInstance().markAsRead(ids);
}
});
}
visibleChat = chat;
}
You've got an extra semi-colon here
if (chat.getLastText().contains("Mom") && (!messageItem.isRead())); <------
So your next block of code containing the Toast show statement will always be executed.
Remove the semi-colon
Still new to android/java and quite confused about bundles, messaging and handlers (apologies if my terminology is not quite correct). I have a custom dialog class which can display multiple dialogs. Listeners are set up to pass back data via a handler to the main calling activity.
The data passed back might be one item or many. In my testing I am attempting to send two items back. I have tried this a number of ways. I am always successful in transmitting a single item and having the handler receive it and extract it. I fail when doing multiple items (in slightly different ways.)
If I put two items into the bundle and send just one message, the handler appears to only receive the 2nd bundle item, not the first.
If I put one item in the bundle, send, clear the bundle and then put the 2nd item in the bundle and send, nothing seems to be received by the handler and the activity hangs.
I have also used the output of msg.toString() and note that if two messeages are sent, the "when" of the second is 0. Don't know if that matters or not.
Also, I have tried passing message by use of msg.sendToTarget as well as handler.sendMessage(msg) but it does not seem to matter which is used.
Code snips and output here: http://pastebin.com/xtUatEVu
I've left in but commented out some of the other things tried. I really do not understand what I am doing wrong.
Well after some extensive experimentation I've discovered a few things. The primary problem was that a message can only be used once, i.e, it is not a reusable envelope which you can put new letters and send again. Additionally, make sure the bundle key is unique. Note that I also discovered msg.what which is used to store the dialogID.
The Handler
private Handler uiMsgHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.i(TAG, "%%%% in the uiMsgHandler");
// msg.what() contains the dialogID. The bundle key is the itemID
if (msg != null) {
int DlgId = 0;
int ItemId = 0;
String value = ""; //leave it to each case to recast the value
String element = "";
Bundle b = new Bundle();
Set<String> s = null;
b = msg.getData();
Log.i(TAG,"bundle is "+b);
DlgId = msg.what;
Log.i(TAG,"DigId is "+DlgId);
switch (DlgId) {
case 1:
s = b.keySet(); //find the set of keys in this message bundle
Log.i(TAG,"s is "+s.toString());
Log.i(TAG,"s.size is "+s.size());
if (s.size() < 100) { // we allow up to 100 items, 99 is reserved
Iterator itr = s.iterator();
while (itr.hasNext()) {
element = (String) itr.next();
ItemId = Integer.parseInt(element.substring(0,1));
value = b.getString(element);
Log.i(TAG,"ItemID is "+ItemId+" value is "+value+" itr.next "+itr.hasNext());
// now we can handle each specific item
switch (ItemId) {
case 1:
Log.i(TAG,"Bundle data for Dialog "+DlgId+" Item "+ItemId+" is "+value);
// do something
// close the dialog
break;
case 2:
Log.i(TAG,"Bundle data for Dialog "+DlgId+" Item "+ItemId+" is "+value);
// do something
// close the dialog
break;
case 99:
Log.i(TAG,"Bundle data for Dialog "+DlgId+" Item "+ItemId+" is "+value);
// Cancel button was pressed
// close the dialog
break;
default: /* item out of range */
Log.i(TAG,"Error ItemID OoR: DialogID "+DlgId+" with message item id "+ItemId+" is out of range");
// close the dialog and toast w/ message
break;
} // end of ItemID switch
} // end of ItemID iterator while
} else { // end of number of items size check
Log.i(TAG,"too many items, must be < 100 but is "+s.size());
}
break; // end of case 1
default: /* dialog id was out of range */
Log.i(TAG,"Error: dialog id was out of range");
Log.i(TAG,"Bundle data for Dialog "+DlgId+" Item "+ItemId+"is "+value.substring(2));
// close the dialog
// toast with a message
break;
} // end of Dialog switch
} // msg null check
}
};
=====================================================================
Portion of the custom dialog
acceptButton = (Button) dialogview.findViewById(r_id_accept);
rejectButton = (Button) dialogview.findViewById(r_id_reject);
acceptButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Inform the user the button has been clicked
Log.i(TAG, "ACCEPT BUTTON PRESSED");
// now we are going to do the messaging
// addOptQty is item id 01
// addOptPrice is item id 02
// msg.what contains the dialogID
msg.what=id;
b.putString("1",""+addOptQty);
b.putString("2",""+addOptPrice);
msg.setData(b);
// now send the message to the handler
try {
mResponseHandler.sendMessageDelayed(msg,10);
} catch (Exception e) {
Log.i(TAG, "ERROR SENDING MESSAGE");
}
}
});
rejectButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
//Inform the user the button has been clicked
Log.i(TAG,"LOCI BUTTON PRESSED");
msg.what=id;
b.putString("99","CANCEL");
msg.setData(b);
// now send the message to the handler
try {
mResponseHandler.sendMessageDelayed(msg,10);
} catch (Exception e) {
Log.i(TAG, "ERROR SENDING MESSAGE");
}
}
});