【发布时间】:2020-03-04 20:07:45
【问题描述】:
我正在尝试从网站获取信息并将其显示在 Android 应用中。问题“What is the fastest way to scrape HTML webpage in Android?”的第二个答案建议使用 BufferedReader。在答案中,此人使用 URL 类。我试图实现这样的答案:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView display = (TextView) findViewById(R.id.textDisplay);
@Override
protected void onCreate(Bundle savedInstanceState) throws Exception {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
URL url = new URL("http://stackoverflow.com/questions/2971155");
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null; ) {
builder.append(line.trim());
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException logOrIgnore) {
logOrIgnore.printStackTrace();
}
}
}
String start = "<div class=\"post-text\"><p>";
String end = "</p>";
String part = builder.substring(builder.indexOf(start) + start.length());
String question = part.substring(0, part.indexOf(end));
TextView display = (TextView) findViewById(R.id.textDisplay);
display.setText(question);
}
}
我收到了这个错误:
'onCreate(Bundle)' in 'com.example.myproject.MainActivity' clashes with
'onCreate(Bundle)' in 'android.appcompat.app.AppCompatActivity';
overridden method does not throw 'java.lang.Exception'
您建议如何处理这个问题,这是从网站获取数据的明智方式吗? 非常感谢任何帮助
【问题讨论】:
-
欢迎来到 StackOverflow!删除
throws Exception,添加catch到try 块,覆盖时不能修改方法声明。此外,你会得到异常,因为你试图在主线程上执行网络调用。使用 OkHttp 库。是的,不要尝试手动解析 html(SO 有 json API,afaik)