如果URL有效,则添加到回收器视图



我想检查edittext中的URL,如果它有效,请在recyclerator视图中添加一个项目。为此,我启动了一个线程来检查HTTP连接。

thread = new Thread(new Runnable() {
@Override
public void run() {
String link = edt.getText().toString();
URL url = null;
try {
url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int code = connection.getResponseCode();
if(code == 200) {
Log.d(TAG, "reachable");
InsertItem(url,adapter);
} else {
Log.d(TAG, "in catch: not reachable");
}
}  catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();

问题是我在尝试添加项目时遇到的错误

private void InsertItem(URL url, MyAdapter adapter) {
thread.currentThread().interrupt();
arrayList.add(0,new file(url.toString()));
adapter.notifyItemChanged(0);
};

错误为:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能访问其视图

看起来在你的新线程中,你正在调用InsertItem(url,adapter((应该以小写字母"I"开头(,它试图对UI元素执行一些工作。

由于错误状态,您不能触摸UI线程之外的视图。您可以尝试添加runOnUiThread(((->insertItems(url,adapter(,以便将操作发布到UI线程。

最新更新