在AsyncTask的如何从doInBackground()的数据传送到主UI"瞬间"而不是每一个循环之后? (BufferedReader类)而不是、瞬间、doInBackgro

2023-09-06 04:48:27 作者:在我地盘别说话

EDIT1:

我确实改变了code这样的更新过程while循环中完成。然而,没有任何变化。显示这code以下。此外,除去其他不相关的线路上onProgressUpdate()。 显示在code以下。

I did change the code such that the update was done within the while loop. HOWEVER, NO CHANGE. SHOWN THIS IN CODE BELOW. ALSO, removed other irrelevant lines on onProgressUpdate(). SHOWN IN CODE BELOW.

请回答就像你会教一个业余。 我将数据从doInBackground()到主界面当前。有用。然而,这是非常慢的。 我想在循环完成后,显示即时的结果,而不是。那怎么code然而写入,性能明智的,如果循环运行了100次,我只得到一次经过100次重复后的结果。这很奇怪。我希望每个迭代后的结果输出。如何实现这一点。 目前;

Please answer like you would teach an amateur. I am passing data from doInBackground() to the main UI currently. It works. However, it is very slow. I want to display "instant" results and not after the loop completes. That's how the code is written, however, performance wise, if the loop runs for 100 times, I only get the results AT once after 100 iterations are complete. This is weird. I want results output after every iteration. How to achieve this. Currently;

    protected Void doInBackground(Void... params) 
        {

            try {
    //bunch of code
for(int k=x1[3];k<=x2[3];k++)
            {
//Process process = execute it;
    reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    int j;
                    char[] buffer = new char[4096];
                    StringBuffer output = new StringBuffer();
                    while ((j = reader.read(buffer)) > 0)
                    {
                    output.append(buffer, 0, j); 
                    }
                    str = output.toString();
                    Log.d("1:STR VALUE", str);
                    publishProgress(str);
                    reader.close();  

    } //FOR loop ends
                 }}
    protected void onProgressUpdate(String... values) {
            results1.append(str);
            results1.append("\n");
            super.onProgressUpdate(values);
        }

如何修改StringBuffer的输出,这样我立竿见影的读者得到数据后? 谢谢

How to modify the StringBuffer output such that I get instant results after the reader gets the data? Thanks

推荐答案

onProgressUpdate 运行在UI线程。

所以,你应该能够使用这种方法的UI交互,你的循环中。然而,尝试使用方法的给定参数:

So you should be able to interact with the UI with this method, inside your loop. However, try to use the given parameter of the method :

protected void onProgressUpdate(String... values)
{
    results1.append(values[0]);
    results1.append("\n");
}

调用 super.onProgressUpdate(值); 是没用,因为默认的实现是空的。

Calling super.onProgressUpdate(values); is useless as the default implementation is empty.