我使用此代码来获取某些网站的内容。textview 保持为空。我做错了什么?我将 jar 添加到 librires 中,并添加了 Internet 权限以显示。
public class MainActivity extends Activity {
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
}
public void onclick(View v) {
mt = new MyTask();
mt.execute(URL);
}
class MyTask extends AsyncTask<String, Void, String> {
Document doc;
String title=null;
@Override
protected void onPreExecute() {
super.onPreExecute();
tvInfo.setText("Please wait");
}
@Override
protected String doInBackground(String... params) {
try {
TimeUnit.SECONDS.sleep(2);
// doc = Jsoup.connect(params[0]).get();
// String title = doc.title();
doc = Jsoup.connect("http://www.example.com/").get();
Element content = doc.select("a").first();
title = content.text();
Log.d("AsyncTask doInBackground","URL: " + params[0]);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return title;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvInfo.setText(title);
}
}
}
当这里的每种方法都被称为非常感谢时,我也不明白excaly!
编辑 - 答案中建议的代码之后的代码。还是行不通:
public class MainActivity extends Activity implements OnClickListener{
MyTask mt;
TextView tvInfo;
String URL="http://www.example.com/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvInfo = (TextView) findViewById(R.id.textView1);
tvInfo.setOnClickListener(this);
}
private class MyTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String title = "hh";
try{
Document doc = Jsoup.connect("http://google.com").userAgent("Mozilla").get();
title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
}
catch (IOException e) {
e.printStackTrace();
}
return title;
}
@Override
protected void onPostExecute(String result) {
tvInfo.setText(result);
}
@Override
protected void onPreExecute() {
tvInfo.setText("Please wait");
}
}
@Override
public void onClick(View v) {
mt = new MyTask();
mt.execute(URL);
}
}