How to dynamically append a new line to a multiline textview

YingnanWangYingnanWang USMember
edited April 2015 in Xamarin.Android

I have a multiline textview need to show the status of the server. So it should always add a new line when server status changes. However, the new line doesn't show up immediatelly but show when all the processes are finished. I have set the android:singleLine="false" .Can anyone help me change it into a automatically show TextView? THX

`logTextView = FindViewById (Resource.Id.LOGtextView);
logTextView.SetText ("Client log:\n", TextView.BufferType.Normal);
.............

logTextView.Append(string.Format("Socket connected to 172.27.27.1\n"));

.............

logTextView.Append(string.Format ("Start send image to server\n"));

.............

logTextView.Append(string.Format ("Successfully send the image to server\n"));

..............

logTextView.Append(string.Format ("Successfully receive the image from server\n"));`

Tagged:

Best Answer

Answers

  • YingnanWangYingnanWang USMember

    I just want to refresh the text in textview every second. What should I do?

  • CheesebaronCheesebaron DKInsider, University mod

    Sounds like you are blocking the UI thread. I suggest you stop doing that.

  • YingnanWangYingnanWang USMember
    edited May 2015

    I use following code to refresh the textview, but it still doesn't work. I haven't blocked the UI thread.

    private void SetLogTextView (string msg) { RunOnUiThread (() => logTextView.Text=logTextView.Text+msg ); }

  • CheesebaronCheesebaron DKInsider, University mod

    I haven't blocked the UI thread

    How can you be so certain?

    However, the new line doesn't show up immediatelly but show when all the processes are finished

    This indicates that it is indeed blocking the UI thread. Post some more relevant code.

  • YingnanWangYingnanWang USMember
    edited May 2015

    My code for the socket android client, just send image to server and receive image back from server:

    `public void StartClient() {
    //start client and sent a image to server

            // Connect to a remote device.
            try {
    
                #region setup socket
                Int32 port = 5037;
                IPAddress ipAddress = IPAddress.Parse("172.27.35.1");
                //IPAddress ipAddress = IPAddress.Parse("192.168.56.1");
                IPEndPoint ipe = new IPEndPoint(ipAddress, port); 
    
                // Create a TCP/IP  socket.
                Socket sock = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, ProtocolType.Tcp); 
                #endregion
    
                // Connect the socket to the remote endpoint. Catch any errors.
                try {
    
                    //sock.Connect(ipe);
    
                    try
                    {
                        sock.Connect(ipe);
                    }
                    catch (System.Exception ex)
                    {
                        if ((ex is SocketException) && ((SocketException)ex).ErrorCode == 10035) 
                        {
                            // Waiting for connection
                            int time = 0;
                            while (time < 2000) // If it was lower than 1 second
                            {
                                // Do what you want
                                if (sock.Connected) // If connected then break
                                    break;
                                System.Threading.Thread.Sleep(50); // Wait 50milisec
                                time += 50;
                            }
                        }
                        else
                        {
                            System.Console.WriteLine("Failed");
                        }
                    }
    
    
    
    
    
                    //RunOnUiThread(()=>logTextView.Text= logTextView.Text + string.Format("Socket connected to {0}\n",sock.RemoteEndPoint.ToString()));
    
                    SetLogTextView(string.Format("Socket connected to {0}\n",sock.RemoteEndPoint.ToString()));
    
    
    
    
                    //替换为data from gallery
                    #region read image into byte buffer
    
                    if(_bitmap!=null)
                    {
    
    
                        var ms = new MemoryStream();
                        _bitmap.Compress(Bitmap.CompressFormat.Png, 0, ms);
                        var imageBytes = ms.ToArray();
                        byte[] nullByte=Encoding.ASCII.GetBytes("\0");
    
                        byte[] ImageByteForSend = new byte[imageBytes.Length + nullByte.Length];
                        imageBytes.CopyTo(ImageByteForSend, 0);
                        nullByte.CopyTo(ImageByteForSend,imageBytes.Length);
    
                        //logTextView.Text= logTextView.Text + string.Format ("Start send image to server\n");
                        SetLogTextView(string.Format ("Start send image to server\n"));
    
                        #endregion
    
    
                        #region Send Image Size
                        byte[] imageSize = Encoding.ASCII.GetBytes(ImageByteForSend.Length.ToString()+"\0");
                        int imageSizeSend=sock.Send(imageSize);
                        #endregion
    
    
    
                        #region receive confirm from server
                        byte[] recvComfirm=new byte[100];
                        int recvConfrimFromServer=sock.Receive(recvComfirm);
                        string status=Encoding.ASCII.GetString(recvComfirm,0,recvConfrimFromServer);
                        #endregion
    
    
                        #region Send Image
    
                        int sentByteCount=0;
                        int off=0;
                        int remainSendBufferCount=ImageByteForSend.Length;
                        do{
    
                            if(remainSendBufferCount>10240)
                            {
                                byte[] bytesPerBufferLong = new byte[10240];
                                Array.Copy(ImageByteForSend,off,bytesPerBufferLong,0,10240);
    
    
                                sentByteCount=sock.Send(bytesPerBufferLong);
    
                                off+=sentByteCount;
    
                                remainSendBufferCount=remainSendBufferCount-sentByteCount;
    
                                System.Console.WriteLine("{0} bytes has been send",off.ToString());
    
                            }
    
                            //最后一次发送时的buffer size不定
                            if(remainSendBufferCount<10240)
                            {
                                byte[] bytesPerBufferSmall = new byte[remainSendBufferCount];
                                Array.Copy(ImageByteForSend,off,bytesPerBufferSmall,0,remainSendBufferCount);
    
    
                                sentByteCount=sock.Send(bytesPerBufferSmall);
    
                                off+=sentByteCount;
                                remainSendBufferCount=remainSendBufferCount-remainSendBufferCount;
                                System.Console.WriteLine("{0} bytes has been send",off.ToString());
                            }
    
                        }while(off<ImageByteForSend.Length);
    
                        #endregion
    
                        //RunOnUiThread(()=>logTextView.Text= logTextView.Text + string.Format ("Successfully send the image to server\n"));
    
                        SetLogTextView(string.Format ("Successfully send the image to server\n"));
                    }
    
                    ////////////////////////
    
    
                    #region receive confirm from server
                    byte[] opencvstartComfirm=new byte[100];
                    int opencvStartFromServer=sock.Receive(opencvstartComfirm);
                    string opencvStart=Encoding.ASCII.GetString(opencvstartComfirm,0,opencvStartFromServer);
                    //RunOnUiThread(()=>logTextView.Text= logTextView.Text+ opencvStart+string.Format("\n"));
                    SetLogTextView(opencvStart+string.Format("\n"));
                    #endregion
    
                    #region receive confirm from server
                    byte[] opencvFinish=new byte[100];
                    int opencvFinFromServer=sock.Receive(opencvFinish);
                    string opencvfin=Encoding.ASCII.GetString(opencvFinish,0,opencvFinFromServer);
                    //RunOnUiThread(()=>logTextView.Text= logTextView.Text + opencvfin+string.Format("\n"));
                    SetLogTextView(opencvfin+string.Format("\n"));
                    #endregion
    
    
    
    
                    #region receive image size
                    byte[] recvSize=new byte[100];
                    int recvSizeFromServer=sock.Receive(recvSize);
                    string sizeString=Encoding.ASCII.GetString(recvSize,0,recvSizeFromServer);
                    int SizeRecv = int.Parse(sizeString);
                    #endregion
    
                    #region send confirm signal
                    byte[] confirmSignal = Encoding.ASCII.GetBytes("Get the size, server please send the image"+"\0");
                    int ConfirmSend=sock.Send(confirmSignal);
                    #endregion
    
                    #region receive image
    
                    byte[] recvImage=new byte[SizeRecv];
                    int totalSizeWrite=0;
    
                    do{
                        byte[] bytesPerbufferrecv=new byte[10240];
                        int bytesRec = sock.Receive(bytesPerbufferrecv);
    
                        Array.Copy(bytesPerbufferrecv,0,recvImage,totalSizeWrite,bytesRec);
    
                        totalSizeWrite=totalSizeWrite+bytesRec;
                    }while(totalSizeWrite<SizeRecv);
    
                    #endregion
    
                    #region set the recv image to imageView
                    Bitmap recvByte2Bitmap=BitmapFactory.DecodeByteArray(recvImage,0,recvImage.Length);
    
                        if(recvByte2Bitmap!=null)
                        {
                            Bitmap newRecv=Bitmap.CreateScaledBitmap(recvByte2Bitmap,_bitmap.Width,_bitmap.Height,true);
    
                            FinalBitmap=newRecv;
                        }
    
    
                    #endregion
    
                    //RunOnUiThread(()=>logTextView.Text=logTextView.Text + string.Format ("Successfully receive the image from server\n"));
                    SetLogTextView(string.Format ("Successfully receive the image from server\n"));
    
                    // Release the socket.
                    sock.Shutdown(SocketShutdown.Both);
                    sock.Close();
    
                    socketStatus=1;
    
    
                } catch (ArgumentNullException ane) {
                    System.Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
                    //logTextView.Text= logTextView.Text + string.Format ("Oops! An Error Happened!\n");
                    SetLogTextView(string.Format ("Oops! An Error Happened!\n"));
                } catch (SocketException se) {
                    System.Console.WriteLine("SocketException : {0}",se.ToString());
                    //logTextView.Text= logTextView.Text + string.Format ("Oops! An Error Happened!\n");
                    SetLogTextView(string.Format ("Oops! An Error Happened!\n"));
                } catch (System.Exception e) {
                    System.Console.WriteLine("Unexpected exception : {0}", e.ToString());
                    //logTextView.Text= logTextView.Text + string.Format ("Oops! An Error Happened!\n");
                    SetLogTextView(string.Format ("Oops! An Error Happened!\n"));
                }
    
            } catch (System.Exception e) {
                System.Console.WriteLine( e.ToString());
                //logTextView.Text= logTextView.Text + string.Format ("Oops! An Error Happened!\n");
                SetLogTextView(string.Format ("Oops! An Error Happened!\n"));
            }
        }`
    

    Function to set logTextView:

    private void SetLogTextView (string msg) { RunOnUiThread (() => logTextView.Text=logTextView.Text+msg ); }

    Is that because I use try-catch which might block the thread? But I have try exclude the try-catch part, it still not work.

  • YingnanWangYingnanWang USMember

    @Cheesebaron Thank you very much sir! await/async exactaly fix my problem. Thank you very much!

Sign In or Register to comment.