K
K
Konstantin Malyarov2016-01-26 18:13:00
Java
Konstantin Malyarov, 2016-01-26 18:13:00

Not displaying TextView text correctly via ArrayAdapter?

Made it so that each incoming message is written to its own TextView.
This method is called on the thread.

public void inputMessage(){
            try {
                InputStream inputStream = socket.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(inputStream);
                String stringInputMessage;
                while (true){
                    if ((stringInputMessage = dataInputStream.readUTF()) != null){
                        final String finalStringInputMessage = stringInputMessage;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TextView textViewMessage = createTextView();
                                textViewMessage.setText(finalStringInputMessage);
                                listMessage.add(textViewMessage);
                                listViewMessage.setAdapter(arrayAdapterMessage);
                            }
                        });
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

This one is separate from the stream.
private TextView createTextView() {
        textViewMessage = new TextView(this);
        return textViewMessage;
    }

In the end, this is the picture.
e803816cf6f8429fbb7a6c6dc9ba74c3.jpg
Elements are added, but there is no text on them.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
itdroid, 2016-01-27
@itdroid

The problem is with the adapter.
No need to create a new TextView for new messages, just add the message to the list of all messages and pass that list to the adapter to update the ListView (in this case, get a reusable TextView out of the box):

List<String> messages = new ArrasyList<>();

//when new message arrives
messages.add(msg);

//update adapter
arrayAdapterMessage.setMessages(messages) ;
arrayAdapterMessage.notifyDatasetChanged();

The adapter will be responsible for creating and reusing the TextView.
Here is how to work with ListView:
www.vogella.com/tutorials/AndroidListView/article.html
startandroid.ru/ru/uroki/vse-uroki-spiskom/82-urok...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question