简体   繁体   中英

Android does not append() text to textview properly

I have a textview in which i append text in two ways: First way: by clicking button and getting what is in EditText.

 sendbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
              txview.append("Text: "+txedit.getText()+"\n");
              txedit.setText("");

 }
          });

And this works fine, when i click the button textview updates the view with new text.

BUT

The second way, I listen to xmpp listener (asmack library) and on recieving message I append it to textView.

 chat = xmpp.getChatManager().createChat(contactid[1], new MessageListener() {
                public void processMessage(Chat chat, Message message) {    
                     try {
                        chat.sendMessage(message.getBody());
                    } catch (XMPPException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                txview.append("Text"+message.getFrom()+"\n"+message.getBody()+"\n");               }                                                       }
            );;

The Problem is, that i recieve message, i know it for sure (because i resend it to user with chat.sendMessage(message.getBody());), BUT textview shows my messages only after I change the view or get application to background (clicking home button) and then getting it back to the front.

What I tried calling invalidate() on every view, doesn't work at all.

Is it any solution or an other way to do what im doing?

You can achieve posting on GUI thread by doing following trick. Pass your context (Activity or Service) to your listener. Inside listener:

Handler h = new Handler(context.getMainLooper());

h.post(new Runnable() {
    @Override
    public void run() {
         txview.append("Text"+message.getFrom()+"\n"+message.getBody()+"\n"); 
    }
});

Are you sure that in the second example the processMessage(Chat, Message) method is invoked on a GUI thread? If not, there is your problem. Never touch GUI from a non-GUI thread. Almost no GUI likes that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM