1

我有一个循环,其中包含 TextView.append("what eve text here") 在循环中如何将新字符串发送到 TextView,就像显示所有内容的 Eclipse 控制台一样。我试图基本上让循环运行并将每个输出实时添加到 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.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.drm.DrmStore.Action;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class station extends Activity implements View.OnClickListener
{
    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 stored here.
    //DateFormat variable  stored here
    private static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    private int intervals; //Random arrival integer stored here
    private int cashiers; //User input of number of cashiers stored here
    private int processing_time; //Random processing time stored here

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

        userinput = (EditText)findViewById(R.id.r_userinput);
        useroutput = (TextView)findViewById(R.id.r_useroutput);

        run = (Button)findViewById(R.id.button_run);
        clear = (Button)findViewById(R.id.button_clear);
        home = (Button)findViewById(R.id.button_home);

        if (run != null)
        {
            run.setOnClickListener(this);
        }
        if (clear != null)
        {
            clear.setOnClickListener(this);
        }
        if (home != null)
        {
            home.setOnClickListener(this);
        }

    }

    public void onClick(View view) 
    {
          if (view == run)
          {
              cashiers = Integer.parseInt(userinput.getText().toString());//Get the Integer value the user inputs from the TextArea
              arrival();
          }
          else if (view == clear) 
          {
            userinput.setText("Line Cleared"); //Use string resource !
            useroutput.setText("");
            System.out.println("cleared"); // Use string resource
          } 
          else if (view == home) 
          {
            Intent a = new Intent(this, MainActivity.class);
            startActivity(a);
          }
    }

    private void arrival()
    {
        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.
                    }

                }
            }
            useroutput.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();
    };

    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;
     }
}
4

2 回答 2

1

您的arrival方法正在 UI 线程上运行。你应该把它放在AsyncTask中。此方法将成为doInBackground并且每当您想要更新 UI(基本上,无论何时调用append),您都会调用publishProgress. 然后您重写onProgressUpdate以使 EditText 无效,这将导致它用新文本重新绘制自己。

于 2013-06-13T20:51:35.337 回答
0

似乎您在 UI 线程上使用了长时间运行的循环,这可能会导致 ANR 并实际上更新用户仅在结束后看到的内容。

一个可能的解决方案:

使用在后台运行的线程,并且每次您希望更新 textView 时,都可以使用 Handler 实例(您需要在 UI 线程上创建)来发布消息/可运行文件,这将导致 textview 自行更新新数据。

于 2013-06-13T21:23:40.807 回答