2013-11-01 98 views
0

如果doc不爲null,我想將所有數據從doc放到ListView中,怎麼做? 如果寫入Element = doc.select(「someSelector」);那麼我不能把它放在ListView中;Android:Jsoup:GET將所有項目放在ListView上

對不起,我的英語(我'俄羅斯)

代碼:

package com.example.phpfunctions; 

import java.io.IOException; 
import java.util.Locale; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.select.Elements; 

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.Menu; 
import android.widget.AutoCompleteTextView; 
import android.widget.ListView; 
import android.widget.Toast; 

public class MainActivity extends Activity { 

    private final String lang = Locale.getDefault().getLanguage(); 
    private final String functions_list = "someURL"; 
    private final ListView lv = (ListView) findViewById(R.id.listView1); 
    Document doc = null; 
    AutoCompleteTextView input; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     new getData().execute(functions_list); 

     if(doc != null) 
     { 

      //--Write code here--// 

     } 
     else 
      Toast.makeText(this, "error", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 


    class getData extends AsyncTask<String, Void, Document> { 

     protected Document doInBackground(String... urls) { 

      try { 
       Document data = Jsoup.connect(urls[0]).get(); 
       return data; 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 

       return null; 
      } 



     } 

     protected void onPreExecute() { 
     } 

     protected void onPostExecute(Document result) { 
      doc = result; 
     } 

    } 

} 

回答

0

您可以從一個頁面,如果你打電話時使用*作爲通配符選擇所有元素doc.select()。要將所有元素添加到ListView,您需要將每個元素保存到某種類型的數組中,例如一個ArrayList並且還使用一個ArrayAdapter

例如:

ArrayList<String> htmlElements = new ArrayList<String>(); 

    if(doc != null) 
    { 
     //--Write code here--// 
     Elements elements = doc.select("*"); // select all elements from that page 

     for (Element e : elements) { 
      htmlElements.add(e.html()); // or e.text(), depends on what you require 
     } 

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, htmlElements); 
     lv.setAdapter(adapter); 
    } 

如果你只想列出從文檔的主體元素,叫doc.body().select("*")代替。 documentation值得一讀其他技巧。

相關問題