Antes de seguir con este artículo recomiendo que lean primeramente este artículo. Ahí van a poder encontrar ejemplos y mucho más.
IDE utilizado: Eclipse + ADT.
– Lo primero que se debe de hacer es agregar la librería (.jar) al proyecto android deseado en la carpeta “libs”, posteriormente se debe hacer click derecho al proyecto y luego click izquierdo a la opción Refresh.
– Luego abrir desde el eclipse el archivo MainActivity.java que se encuentra en la carpeta src y dejarlo de esta manera:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | /* * Utilizar JSOUP en Android * www.programacion.com.py - Recursos y documentación para desarrolladores - By Rodrigo Paszniuk * PD: Para agregar una libreria .jar cualquiera al proyecto solamente se debe agregar a la carpeta libs del mismo. * Para actualizar cambios hacer click derecho al proyecto y luego click izquierdo a Refresh. */ import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { //Declarar variables y componentes que se van a utilizar. private String title; private String titleid; private TextView tit; private TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Vincular textviews a utilizar //Siempre se debe de buscar el id del componente definido en el res/layout/activity_main.xml (en este caso). tit = (TextView)findViewById(R.id.tit); text = (TextView)findViewById(R.id.text); //Crear un nuevo hilo, ya que el hilo principal no permite que se realicen tareas largas o con acceso a internet. new Thread( new Runnable() { public void run() { //En esta sección realizar todo el trabajo pesado, ya que es el comienzo de un nuevo hilo creado Document doc; try { //necesitará protocolo http //doc trae el html completo de la url que se le agregue .userAgent( "Mozilla" ) .get(); //La función title() lo que hace es buscar el atributo <title> y lo trae en forma de string. title = doc.title(); //Utilizar Element para buscar un elemento en especial, en este caso el id hplogo que se encuentra dentro de un <div>. Element image = doc.select( "div[id=hplogo]" ).first(); //Buscamos el atributo style y lo convertimos a string, el atributo style utiliza el Element image titleid=image.attr( "style" ).toString(); } catch (IOException e) { e.printStackTrace(); } //Mostrar los resultados. runOnUiThread( new Runnable() { public void run() { //Como ya se vincularon los componentes, se podrá utilizar sin problemas. //En esta parte siempre mostrar los resultados. tit.setText(title); text.setText(titleid); Toast.makeText(MainActivity. this , "Tarea finalizada!" , Toast.LENGTH_SHORT).show(); } }); } }).start(); } @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 ; } } |
– Abrir desde el eclipse el archivo string.xml que se encuentra en la carpeta res/values y dejarlo de esta manera:
1 2 3 4 5 6 7 8 9 10 11 12 | </ pre > <? xml version = "1.0" encoding = "utf-8" ?> < resources > < string name = "app_name" >HtmlParser</ string > < string name = "action_settings" >Settings</ string > < string name = "hello_world" >< b >Traer el título y el atributo style del id hplogo de Google: </ b ></ string > < string name = "title" >< b >Título: </ b ></ string > < string name = "desc" >< b >Attr style de id hplogo: </ b ></ string > </ resources > < pre > |
– Abrir desde el eclipse el archivo activity_main.xml que se encuentra en la carpeta res/layout y dejarlo de esta manera:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | android:layout_width = "match_parent" android:layout_height = "match_parent" android:paddingBottom = "@dimen/activity_vertical_margin" android:paddingLeft = "@dimen/activity_horizontal_margin" android:paddingRight = "@dimen/activity_horizontal_margin" android:paddingTop = "@dimen/activity_vertical_margin" tools:context = ".MainActivity" > < TextView android:id = "@+id/textView2" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "@string/hello_world" /> < TextView android:id = "@+id/textView1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignLeft = "@+id/textView2" android:layout_below = "@+id/textView2" android:layout_marginTop = "30dp" android:text = "@string/title" /> < TextView android:id = "@+id/textView3" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignLeft = "@+id/textView1" android:layout_below = "@+id/textView1" android:layout_marginTop = "36dp" android:text = "@string/desc" /> < TextView android:id = "@+id/tit" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignBottom = "@+id/textView1" android:layout_alignRight = "@+id/textView3" android:text = "TextView" /> < TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignBaseline = "@+id/textView3" android:layout_alignBottom = "@+id/textView3" android:layout_marginLeft = "20dp" android:layout_toRightOf = "@+id/textView3" android:text = "TextView" /> </ RelativeLayout > |
– Posteriormente se debe de agregar el permiso para poder acceder a INTERNET, para eso se debe de agregar al AndroidManifest.xml el siguiente código (debajo del tag </application>):
1 | < uses-permission android:name = "android.permission.INTERNET" /> |