我有一个内部私有AsyncTask,它将访问外部的全局TextView,并使用它来附加在该AsyncTask类中读入的String行。我可以很好地阅读,但是当我尝试将该行附加到TextView时,我会遇到致命的运行时异常。
这是AsyncTask代码:
private class StreamTask extends AsyncTask<String, Void, Integer> {
private static final int BUFFER_LENGTH = 1024 * 8; // Adjust to taste
String TAG2 = "StreamTask";
// Param #0 = file name
// Param #1 = charset name
@Override
protected Integer doInBackground(String... params) {
Log.d(TAG2, "in doInBackground");
if (params.length != 2) {
Log.d(TAG2, "AsyncTask has 2 params");
throw new IllegalArgumentException();
}
int chars = 0;
CharsetDecoder cd = Charset.forName(params[1]).newDecoder();
try{
Log.d(TAG2, "in first try block");
FileInputStream inputStream = null;
Scanner sc = null;
try {
Log.d(TAG2, "in second try block");
inputStream = new FileInputStream(params[0]);
Log.d(TAG2, "inputstream set "+params[0]);
sc = new Scanner(inputStream, params[1]);
Log.d(TAG2, "scanner set: "+params[1]);
while (sc.hasNextLine()) {
Log.d(TAG2, "in while block");
String line = sc.nextLine();
Log.d(TAG2, "this line is: "+line);
// System.out.println(line);
textView.append(line);//This is where the problem is~~~
}
// note that Scanner suppresses exceptions
if (sc.ioException() != null) {
Log.d(TAG2, "throws ioException");
throw sc.ioException();
}
}
catch(FileNotFoundException e){}
finally {
Log.d(TAG2, "in finally...");
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
}
catch(IOException e){}
return chars;
}
提前致谢!
杰森
答案 0 :(得分:3)
您无法从AsynTask的doInBackground()
更新UI。因为它在其他线程上运行(不能直接更新UI)。
您可以更新在UI线程上运行的UI onPostExecute()
。像
@Override
protected void onPostExecute(String b){
textView.append(b);
}
了解AsynTask
如果您只需要从doInBackground更新UI,则可以使用runOnUiThread
,如下所示
runOnUiThread(new Runnable() {
public void run() {
textView.append(line);
}
});