In AsyncTask How to pass data from doInBackground(

2019-02-15 15:37发布

问题:

EDIT1:

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.

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

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

回答1:

onProgressUpdate runs in the UI thread.

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");
}

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