繁体   English   中英

实时TextView输出

[英]TextView output in real time

您好,我有一个android应用程序,它基本上具有一个EditText来获取用户输入,TextView来输出处理后的数据以及一个按钮来执行所有操作。 用户单击按钮并创建新线程后,以下两个循环将运行,并且每次将新输出附加到TextView。 但是,循环完成后,TextView输出不会实时转到TextView的问题是,它会立即显示所有输出的数据,请帮助。

package com.example.assignment2_android;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class station extends Activity 
{
    Button run, clear, home;
    EditText userinput;
    TextView useroutput;

    //LinkedList Customer Queue created here.
    public static Queue<String> line = new  LinkedList<String> (); 
    private static String time;   //time variable.
    private static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");   //DateFormat variable.

    private int intervals;
    private int cashiers;
    private int processing_time;
    Thread arrival;
    Handler handler, handlerr, handlerrr;

    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.station);

        userinput = (EditText)findViewById(R.id.s_userinput);
        useroutput = (TextView)findViewById(R.id.s_useroutput);

        clear = (Button)findViewById(R.id.button_clear);
        clear.setOnClickListener(new View.OnClickListener() 
        {
              public void onClick(View view) 
              {
                  line.clear();
                  userinput.setText("Line Cleared");
                  useroutput.setText("");
                  System.out.println("cleared");
              }
        });

        home = (Button)findViewById(R.id.button_home);
        home.setOnClickListener(new View.OnClickListener() 
        {
              public void onClick(View view) 
              {
                  Intent a = new Intent(station.this, MainActivity.class);
                  startActivity(a);
              }
        });
    }

    public void startProgress(View view)
    {
        handler = new Handler();
        Thread arrival = new Thread();
        {
            useroutput.append("CUSTOMERS ARE COMING !!!! !!!!" + "\n" + "\n");;
            //Array of all the customer that will enter the queue.
            String list[] = {"Naqi", "Monty", "Mohin", "Yasmin", "Maighjoo", "Ashish", "Paal", "Kevin", "Ruhail", "Tony"};
            //2nd ArrayList which customer are added to and removed later on so no duplicates arise.
            ArrayList<String> customer = new ArrayList<String>(Arrays.asList(list));

            int array_customer_list = list.length; //Recording the number of customers in the array.

            //While statement containing for loop add customers to the empty LinkedList object.
            while (line.isEmpty())
            {
                for (int x = 0; x < array_customer_list; x++ )
                {
                    try
                    {
                        Thread.sleep(ran_interval() * 1000);   //Sleep method to hold the arrival time by 1-2 seconds. 
                        int cus = (int) (Math.random() * customer.size());   //Random customer is picked here. 
                        String new_cus = customer.get(cus);   //New customer object is created ere.
                        line.add(new_cus);   //Customer objects are added to the empty LinkedList queue.
                        customer.remove(cus);

                        //For loop statement to outputting the queue.
                        for (String s : line)
                        {
                            useroutput.append("[" + s.toString() + " " + "]" + "\n");; //Outputting each customer and using the ".name" method so customers are readable.
                        }
                        //Outputting the whole queue and stating who has joined the queue.
                        useroutput.append("\n" + "The queue has " + line.size() + " customers so far" + "\n" + 
                        new_cus.toString() + " Has Joined the Queue " + " <=== WAITING" + "\n" + "\n");
                    }
                    catch(Exception a)   //ERROR handler for sleep method.
                    {
                        System.out.println("Intervals error: " + a);   //Outputting the ERROR message.
                        System.exit(0);   //If ERROR found exit system.
                    }

                }
            }
            userinput.append("\n");
            useroutput.append("CUSTOMERS ARE WAITING !!!! !!!!" + "\n" + "\n");
            useroutput.append("Processing START !!!!" + "\n" + "\n");

            while (!line.isEmpty())   //While statement with for loop to remove each customer from LinkedList queue.
            {
                try 
                {
                    String cus = line.remove(); //Method to remove customer from LinkedList queue.
                    String time = getTime();
                    Thread.sleep((processing_time() * 1000) / cashiers); //Sleep method to hold the processing by 1-3 seconds.
                    for (String s : line)
                    {
                        useroutput.append("[" + s.toString() + " " + "]" + "\n"); //Outputting each customer and using the ".name" method so customers are readable.
                    }
                    //Outputting the whole queue and stating who has joined the queue.
                    useroutput.append("\n" + "The queue has " + line.size() + " customers left" + "\n" + 
                    cus.toString()+ " waited for " + time + " <=== SERVED" + "\n" + "\n");
                }
                catch(Exception a)   //ERROR handler for sleep method.
                {
                    System.out.println("Cashiers_wait error: " + a);   //Outputting the ERROR message.
                    System.exit(0);   //If ERROR found exit system.
                }
            }
            useroutput.append("Processing FINISHED !!!!" + "\n");
            System.out.println("working" + "\n" + "random arrival time is :" + intervals + "\n" + 
            "random processing time is :" + processing_time);
        }; arrival.start();
    };

    public void append_output(final String text)
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run() 
            {

                useroutput.append(text);
            }
        });
    }

    static String getTime()   //Time Constructor
    {
       Calendar cal = Calendar.getInstance();
       time = dateFormat.format(cal.getTime());   //Getting the current system time.
       return time;   //Return time.
    }

    public int ran_interval()
     {
         Random rand = new Random(); //Random object created here.
         int interval = this.intervals = rand.nextInt(2) + 1; //Random number between 1-2 is generated for customer arrival here.

         return interval;
     }

    public int processing_time()
     {
         Random ran = new Random();    //Random object created here.
         int time = this.processing_time = ran.nextInt(4) + 1;  //Random number between 1-3 is generated for customer arrival here.

         return time;
     }
}

看来您的问题是您试图从不打算这样做的线程中更新UI。 您看似为此目的而创建了函数append_output ,但从未使用过它。 由于您的arrival线程未在UI上运行,因此无法实时更新文本框。 因此,基本上, useroutput.append在到达线程中没有一堆useroutput.appenduseroutput.append将它们全部更改为append_output(text) ,那应该可以解决您的问题。

首先组织您的导入并尊重android编码风格。 我更正了您的代码的开头。

private static Button mRun, mClear, mHome;
private static EditText mUserInput;
private static TextView mUserOutput;

//LinkedList Customer Queue created here.
public static Queue<String> line = new  LinkedList<String> ();
private static String time;   //time variable.
private static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");   //DateFormat variable.

private int intervals;
private int cashiers;
private int processing_time;
Thread arrival;
Handler handler, handlerr, handlerrr;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.station);

    mClear = (Button)findViewById(R.id.button_clear);
    mHome = (Button) findViewById(R.id.button_home);
    mUserInput = (EditText) findViewById(R.id.s_userinput);
    mUserOutput = (TextView) findViewById(R.id.s_useroutput);

    if (mClear != null) {
        mClear.setOnClickListener(this);
    }

    if (mHome != null) {
        mHome.setOnClickListener(this);
    }
}

public void onClick(View view) {
    if (view == mClear) {
        line.clear();
        mUserInput.setText(getString(R.string.line_cleared)); //Use string ressource !
        mUserOutput.setText("");
        System.out.println("cleared"); // Use string ressource
    } else if (view == mHome) {
        Intent a = new Intent(this, MainActivity.class);
        startActivity(a);
    }
}

您必须使用线程来执行一些复杂的计算,获取数据。 但是,不能在工作线程中完成用户界面的初始化。 您必须位于主线程上。 和往常一样,一切都在这里: http : //developer.android.com/guide/components/processes-and-threads.html

确实,您应该使用AsyncTask来处理UI更新。 做类似的事情:

 private class updateTextView extends AsyncTask<String, String, Void> {
  protected void doInBackground(String text) {
      publishProgress(text)
  }
  protected void onProgressUpdate(String text)
  {
      useroutput.append(text)
  }
 }

在您的课程声明上方。

然后,每次您要更新textview时,您只需

new updateTextView().execute(text)

我不确定这些语言的确切语法,因为我不是在安装了Android SDK之类的计算机上,但这至少应该使您走得足够远,以便您的IDE能够处理其余的内容。 尽管这可能是草率的或“较差的形式”,但它应该可以为您工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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