Android AsyncTask strangely posts duplicates

I think this is a difficult question. I will be brief and give a small example of what is happening. Let's say we have a data source in the Byron.txt file:

SHE walks in beauty, like the night of Cloudless edges and the starry sky;
And all that is better than dark and bright
Meet in her aspect and her eyes:
Thus, the soft light on this gentle light
Which sky on a tasteless day denies.

And this code is executed inside AsyncTask:

final ArrayList<Record> poem = new ArrayList<Record>();
final Object objectLock = new Object();
private Record rec = new Record();

@Override
protected Void doInBackground(Void... args) {
    String line = null;
    int i;
    int last;

    try {
        process = Runtime.getRuntime().exec("cat Byron.txt");
        bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()), 8192);

        synchronized (objectLock) {
            poem.clear();
            last = i = poem.size() - 1;
        }
        while(line = bufferedReader.readLine()) != null) {
            rec.setString(line);
            synchronized (objectLock) {
                last++;
                poem.add(last, rec);
            }

            while(!bPause && i < last) {
                i++;
                publishProgress(poem.get(i));
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected synchronized void onProgressUpdate(Record... m) {
    if(m.length > 0) {
        mContext.mTable.appendRow(m[0]);
    }

}

where there is a TableLayout in the user interface, and every time we get a new row, we add a new TableRow to it. And this is the result that we see in the user interface:

, ;
;
;
,
,

, , .
synchronized (objectLock) , .
, i last.
, ,
, , poem
, i last .

, , , , , : ?, ?
, , .
, synchronized (objectLock)
wait() notify()

(, , )
, , .

:

  • synchronized , , .
  • (bpause); while i last , bpause .
+3
2

. .
, AsyncTask, .

, , - - .

Record rec . poem ArrayList . , .
, , . - , poem.get(i) , , , .

.

+3

last.

synchronized (last) {
   last++;
   poem.add(last, line);
}
0

All Articles