How return a result from AsyncTask void onPostExecute() method in Java Android in Background Task? I had lost a lot days searching about it when Delegate Pattern Save My Life save my life. When had found here from StackOverFlow.
My Main Thread has a CsvUtil.getCompanies() method who need to return a List, and getCompanies() call a ReadLine class who consume a Google Sheet from Cloud.
public static final class ParseLine extends AsyncTask<String, Integer, String[]> {
private TaskDelegate delegate;
public ParseLine(TaskDelegate delegate) {
this.delegate = delegate;
}
public interface TaskDelegate {
public void onTaskEndWithResult(String[] parseLine);
}
@Override
protected String[] doInBackground(String... nextLine) {
try {
return parseLine(nextLine[0]);
} catch (IOException ex) {
Log.e("CsvReader", ex.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String[] parseLine) {
if (parseLine != null && delegate != null)
delegate.onTaskEndWithResult(parseLine);
}
}
private static final class GetNextLine extends AsyncTask<Void, Integer, String>
implements ParseLine.TaskDelegate {
private List<String[]> list;
public GetNextLine(List<String[]> l) {
list = l;
}
@Override
protected String doInBackground(Void... companies) {
try {
return getNextLine();
} catch (IOException ex) {
Log.e("CsvReader", ex.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String nextLine) {
if (nextLine != null) {
ParseLine parseLine = new ParseLine(this);
parseLine.execute(nextLine);
}
}
@Override
public void onTaskEndWithResult(String[] parseLine) {
list.add(parseLine);
}
}
Aucun commentaire:
Enregistrer un commentaire