开发者

Help with Jsoup usage in Android

I am trying to connect to a website and pull off some specific information. I was using HTMLCleaner and xpath but it doesnt seem to support all the xpath queries I need.

I am trying to use Jsoup now, after reading the good reviews. But the problem is whenever I run the program it force closes. Following is my trial program. Please let me know where I am going wrong. (I have Internet P开发者_StackOverflow社区ermission set in the manifest file).

Thank you.

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;

public class jTrial extends Activity {
     /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        String myString = null;     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        try{
            Document doc = Jsoup.connect("http://google.com/").get();

            Elements divs = doc.select("div");

            for (Element div : divs) {
                myString=div.text();
            }
        }
        catch(IOException e){
            myString=e.getMessage();
        }
        TextView tv=new TextView(this);
        tv.setText(myString);
        //this.setContentView(tv);
    }
}

Thanks.


You probably getting Exception when you try to (Since, you havent posted the LogCat)

    for (Element div : divs) 
    {
       myString=myString+" " +div.text();  //if it was like you did, than you'll see only the last element or use div.getElementsByTag("div"); 
    }
    TextView tv=new TextView(this);
            tv.setText(myString);

If you want to parse the <divs from the html probably you should use div.getElementsByTag("div") because you are searching for HTML tag and then parsing. Either you get the TextView wrong or your myString is null (might be NullPointerException).

Try rewriting that part like (I hope you have TextView in your search.xml)

TextView tv=(TextView)findViewById(R.id.yourTextView);
if(myString!=null)  // if it is null you'll know that something with the Jsoup isnt right
{
       tv.setText(myString);
}else { 
tv.seText("myString is null");
}


You should download the Jsoup jar file from http://jsoup.org/download

Create a new directory "libs" in the project directory, and copy this jar file into the libs directory. Creating the "libs" in the res folder gives an error since res Folder are only allowed to be those defined by Android. Then Right click on the project and open Build path -> configure build path. Select Libraries tab and add jars. Navigate to your project libs directory and add the Jsoup jar file. Reimport all the packages again.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜