我是 jsoup 的新手,我只是想问一下,我是否必须像我在研究中在网上看到的那样在 public static void main 中使用 jsoup 代码,或者我是否可以在任何其他方法中使用它。我也遇到了 Jsoup.connect().get() 的问题。我的应用程序在运行时总是停止。我已经将 android.permission.Internet 添加到我的 AndroidManifest.xml 中。我阅读了说明书并决定从解析文档开始,但我仍然生成相同的结果——不幸的是,应用程序已停止。我的minsdkversion是8,targetsdkversion是15,请多多包涵。
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Jsoup_2 extends Activity{
static String website_url = "http://www.google.com";
/**
* @param args
*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsoupactivity);
try{
Document doc = Jsoup.connect(website_url).get();
((TextView)findViewById(R.id.label)).setText("Loading website");
}catch (Exception e){
((TextView)findViewById(R.id.label)).setText("error");
}
}
}
最佳答案
这是因为您在主线程中运行此代码。您必须放入一个 AsyncTask 或另一个新线程...永远不要在主线程上执行繁重的操作(例如 onCreate() 方法)。
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsoupactivity);
new AsyncTask(String,Integer,Document) {
public Document doInBackground(String... params) {
Document doc = null;
try{
doc = Jsoup.connect(params[0]).get();
}catch (Exception e){
doc = null;
}
return doc;
}
public void onPostExecute(Document result) {
if (result != null) {
((TextView)findViewById(R.id.label)).setText("Loading website");
} else {
((TextView)findViewById(R.id.label)).setText("Error");
}
}
}.execute(website_url);}}
关于安卓 - Jsoup.connect().get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17381406/