我正在开发一款使用Google云端硬盘作为数据库的应用。这是一个项目和必要的,所以请不要对此发表评论。
基本上,我正在使用jsoup抓取已发布的Google Doc。 jsoup doc解析数据,然后将其转换为Event,这是我在单独的类中声明的对象。问题是我无法获得任何数据。由于Android Studio中的onCreate方法无法抛出异常,因此我必须使用try和catch块。但是,由于这种情况,我无法使用doc创建任何TextView。这就是我到目前为止所做的:
Document doc = null;
String url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vRAS7DEUoTqv9gKNSTg9XrgktfqZs1vw3L-eivZW2UPCOeSqiqt8Xdtsd3o-tmS9m-uTHCYn8JbToAx/pubhtml";
try {
doc = Jsoup.connect(url).get();
} catch (Exception e) {
e.printStackTrace();
}
String title = doc.title();
String body = doc.body().text();
List<Event> allEvents = new ArrayList<Event>();
Element table = doc.select("table").get(0); //select the first table.
Elements rows = table.select("tr");
for (int i = 2; i < rows.size(); i++) { //first row is the col names so skip it, second is title.
Element row = rows.get(i);
Elements cols = row.select("td");
Event hold = new Event(cols.get(0).text(), cols.get(1).text(), cols.get(2).text(), cols.get(3).text());
allEvents.add(hold);
}
for (Event x : allEvents) {
x.createDateTime();
}
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < allEvents.size(); i++) {
TextView textView = new TextView(this);
textView.setText(allEvents.get(i).toString());
linearLayout.addView(textView);
}
这会产生错误,因为我无法修改try块中的doc变量。我希望根本没有这个块,但不幸的是,我没有选择权。有什么提示吗?
答案 0 :(得分:0)
像这样使用AsyncTask:
final Document[] doc = {null};
final String url = "https://docs.google.com/spreadsheets/d/e/2PACX-1vRAS7DEUoTqv9gKNSTg9XrgktfqZs1vw3L-eivZW2UPCOeSqiqt8Xdtsd3o-tmS9m-uTHCYn8JbToAx/pubhtml";
new AsyncTask<Void,Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
doc[0] = Jsoup.connect(url).get();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
List<Event> allEvents = new ArrayList<Event>();
Element table = doc[0].select("table").get(0); //select the first table.
Elements rows = table.select("tr");
for (int i = 2; i < rows.size(); i++) { //first row is the col names so skip it, second is title.
Element row = rows.get(i);
Elements cols = row.select("td");
EventLog.Event hold = new EventLog.Event(cols.get(0).text(), cols.get(1).text(), cols.get(2).text(), cols.get(3).text());
allEvents.add(hold);
}
for (UsageEvents.Event x : allEvents) {
x.createDateTime();
}
LinearLayout linearLayout = new LinearLayout(SplashActivity.this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < allEvents.size(); i++) {
TextView textView = new TextView(SplashActivity.this);
textView.setText(allEvents.get(i).toString());
linearLayout.addView(textView);
}
}
}.execute();