以下代码无法运行,请修改以下:public class MainActivity4 extends AppCompatActivity { public static final String TAG = "petgrowing"; TextView show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main4); show = findViewById(R.id.tv_res); } public void onClick(View btn) { Log.i(TAG, "onClick"); // 使用 Runnable 接口来动态创建新线程 new Thread(() -> { Log.i(TAG, "线程已运行"); try { Log.i(TAG, "run:正在工作..."); Document doc = Jsoup.connect("https://chl.cn/?jinri").get(); Log.i(TAG, "title=" + doc.title()); Elements tables = doc.getElementsByTag("table"); Element table1 = tables.first(); Log.i(TAG, "run:table=" + table1); Elements tds = table1.getElementsByTag("td"); Element td1 = tds.first(); Element td2 = tds.get(4); final String retStr = ("1:" + td1.text() + " 2:" + td2.text()); // 根据获取的数据更新 UI 线程上 TextView 的内容 runOnUiThread(() -> show.setText(retStr)); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }).start(); // 启动新线程 } }
时间: 2024-02-14 12:15:07 浏览: 94
可以尝试将 `onClick` 方法中的参数 `View btn` 改为 `View view`,因为该方法在布局文件中对应的控件的 `onClick` 属性中被调用时,系统会传入该控件的实例作为参数,而不是一个名为 `btn` 的参数。修改后的代码如下:
```
public class MainActivity4 extends AppCompatActivity {
public static final String TAG = "petgrowing";
TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
show = findViewById(R.id.tv_res);
}
public void onClick(View view) {
Log.i(TAG, "onClick");
// 使用 Runnable 接口来动态创建新线程
new Thread(() -> {
Log.i(TAG, "线程已运行");
try {
Log.i(TAG, "run:正在工作...");
Document doc = Jsoup.connect("https://chl.cn/?jinri").get();
Log.i(TAG, "title=" + doc.title());
Elements tables = doc.getElementsByTag("table");
Element table1 = tables.first();
Log.i(TAG, "run:table=" + table1);
Elements tds = table1.getElementsByTag("td");
Element td1 = tds.first();
Element td2 = tds.get(4);
final String retStr = ("1:" + td1.text() + " 2:" + td2.text());
// 根据获取的数据更新 UI 线程上 TextView 的内容
runOnUiThread(() -> show.setText(retStr));
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}).start(); // 启动新线程
}
}
```
阅读全文