我對Android開發很新,但我知道我不能在沒有某種線程的情況下運行Jsoup.connect(url).get()
,因爲它是一個同步調用。我嘗試創建一個名爲Product的類來擴展AsyncTask,然後讓我的原始類名爲List call Product,然後顯示int。但是,無論實際結果如何,它總是打印出0.如何使用Android的AsyncTask通過JSoup獲取所有數據,然後將該信息發送給另一個類?
我之前測試過我的代碼,所以我知道它的工作原理以及該問題必須與Android相關。
列表類:
public class List extends AppCompatActivity{
String itemURL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle itemData = getIntent().getExtras();
if(itemData==null){
return;
}
//Gets URL
itemURL = itemData.getString("itemURL");
int listSize=new Product(itemURL).getListSize();
System.out.println(listSize);
}
}
產品類:
public class Product extends AsyncTask<Void,Void,Void>{
String url;
String title;
int listSize;
public Product(String url){
this.url = url;
}
protected Void doInBackground (Void... voids) {
//Create JSoup connection
try{
Document doc = Jsoup.connect("url").get();
//Gets title
String link = doc.select("h2#s-result-count").first().text();
System.out.println(link);
listSize=Integer.parseInt(link.substring(0,1));
System.out.println(listSize);
try{
int listSize= Integer.parseInt(link.substring(0,2));
System.out.println(listSize);
}catch(Exception e){}
}catch (Exception e){}
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
getListSize();
}
public int getListSize(){
return listSize;
}
}
所有建議,將不勝感激,感謝您的時間和幫助!
請嘗試以下代碼 Product product = new Product(itemURL); product.execute() –