gpt4 book ai didi

java - 为什么我会收到 TextView.append 运行时异常?

转载 作者:行者123 更新时间:2023-12-01 22:47:01 25 4
gpt4 key购买 nike

我有一个内部私有(private) AsyncTask,它将访问外部全局 TextView 并使用它来附加在该 AsyncTask 类中读取的字符串行。我可以很好地阅读,但是当我尝试将行附加到 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;
}

提前致谢!

杰森

最佳答案

您无法从 AsynTask 的 doInBackground() 更新 UI。因为它运行在其他线程上(不能直接更新UI)。

您可以通过在 UI 线程上运行的 onPostExecute() 更新 UI。喜欢

@Override
protected void onPostExecute(String b){
textView.append(b);
}

了解AsynTask

<小时/>

如果您需要仅从 doInBackground 更新 UI,则可以使用 runOnUiThread 如下所示

runOnUiThread(new Runnable() {
public void run() {
textView.append(line);
}
});
<小时/>

Communicating with the UI Thread是一篇好文章。

关于java - 为什么我会收到 TextView.append 运行时异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25200193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com