我的onCreate
中包含此代码 tv = (TextView) findViewById(R.id.tv);
HttpHelper helper = new HttpHelper("http://www.pinoyfitness.com/");
helper.execute();
我在onCreate
之外有这个方法private class HttpHelper extends AsyncTask<Void, Void, String> {
String urlString;
public HttpHelper(String urlString) {
this.urlString = urlString;
}
public String downloadText() {
URL url = null;
HttpURLConnection urlConnection = null;
InputStream in = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
StringBuffer str = new StringBuffer("");
char[] inputBuffer = new char[2000];
try {
while((charRead=isr.read(inputBuffer))>0){
str.append(String.copyValueOf(inputBuffer,0,charRead));
inputBuffer = new char[2000];
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
return str.toString();
}
@Override
protected String doInBackground(Void... params) {
// This commented code will run the conventional way to connect to the
// return downloadText();
String s = "";
try {
// The next line does what downloadText() does. You'll need JSoup for this.
Document d = Jsoup.connect(urlString).timeout(0).get();
Elements links = d.select("h2.entry-title a");
for(Element e: links){
s += e.text() +"\n\n";
}
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// super.onPostExecute(result);
tv.setText(result);
}
}
错误在于:Document d = Jsoup.connect(urlString).timeout(0).get();
。它说:在com.example.pinoyfitness.Timeline $ HttpHelper.doInBackground(Timeline.java:115)
我想知道这行代码有什么问题。我尝试将整个代码复制并粘贴到一个新的android项目中,它可以工作。我已经完成了所有必要的操作,例如添加Internet权限和配置构建路径:Jsoup
答案 0 :(得分:0)
首先,考虑使用网络库,它将极大地改善您的代码并摆脱这些错误。 例如,使用OkHTTP或Android Async HTTP
答案 1 :(得分:0)
我发现了错误。这是一个空指针异常,因为我忘了在Java Build Path中检查导入的Jsoup - &gt;订单和出口