Rinomancer
Rinomancer

Reputation: 59

android html parsing with jsoup

Trying to parse an html pages like http://www.ts.kg/serials/ on android. Tried to do it with htmlcleaner, but it didnot work. Trying to do it with jsoup. In the begining was my code to complex. Here is the shortest code. The same thing works on java Please help. My Logs http://smartpics.kz/imgs/1361209668WW5O.JPG Here is my class:

public class MainActivity extends Activity {

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

    String[] names= {};
    String url = "http://www.ts.kg/mults/";

    try {
        Document doc = Jsoup.connect(url).get();
        Element e = doc.body();
        Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
        for (int i =0;i<ggg.size();i++) {
            Element linkk = ggg.get(i);
            if(linkk.getElementsByTag("a")!=null){
                Element atom = linkk.getElementsByTag("a").first();
                String n = atom.getElementsByTag("span").first().text();
                names[i] = n;
            }

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ListView lvMain = (ListView) findViewById(R.id.listViewData);

    // создаем адаптер
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, names);

    // присваиваем адаптер списку
    lvMain.setAdapter(adapter);
}

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

}

posted 20.feb.2013:

tryed to do it as it was proposed by Shoshy (thanks for your answer), but it didn't work (perhaps because of my not-from-right-place-growing hands). Here is my modified code: public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    url = "http://www.ts.kg/mults/";
    pd = ProgressDialog.show(MainActivity.this, "Working...", "request to server", true, false);
    //Запускаем парсинг
    new AsyncExecution().execute();
}
private ProgressDialog pd;
String url;;
String names[];

private class AsyncExecution extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {
          // here your task will be done in seperate thread from UI thread
          // and if you want to use the variables (that will be modifed here)
          // from anywhere in MainActivity, then you should declare them as global
          // variable in MainActivity. remember you cannot update UI from here , like
          // Toast message. if you want to do that you can use OnPostExecute 
          // method bellow .
               try {
                  ArrayList<String> array = new ArrayList<String>();
                  Document doc = Jsoup.connect(url).get();
                  Element e = doc.body();
                  Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
                  for (int i =0;i<ggg.size();i++) {
                      Element linkk = ggg.get(i);
                      if(linkk.getElementsByTag("a")!=null){
                          Element atom = linkk.getElementsByTag("a").first();
                          String n = atom.getElementsByTag("span").first().text();
                          array.add(n);
                      }

                  }
                  for (int i = 0;i<array.size();i++){
                      names[i]=array.get(i);
                  }
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
            return null;
    }

    @Override
    protected void onPostExecute(Void result) {         
        //Убираем диалог загрузки
        pd.dismiss();
        //Находим ListView
        ListView listview = (ListView) findViewById(R.id.listViewData);
        //Загружаем в него результат работы doInBackground
        listview.setAdapter(new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, names));

       }
}

}

Upvotes: 0

Views: 1636

Answers (1)

Shoshi
Shoshi

Reputation: 2254

you have to make the request for getting the page in another thread from UI thread. you can use AsyncTask. i am giving some example by editing your code : the link about AsyncTask is : about AsynckTask

public class MainActivity extends Activity {

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

    //the class is defined bellow
    new AsyncExecution().execute();

    //other codes.....
     .......................
}
/// your other codes .....


    // you need to add this class
    private class AsyncExecution extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {
          // here your task will be done in seperate thread from UI thread
          // and if you want to use the variables (that will be modifed here)
          // from anywhere in MainActivity, then you should declare them as global
          // variable in MainActivity. remember you cannot update UI from here , like
          // Toast message. if you want to do that you can use OnPostExecute 
          // method bellow .
               try {
                  Document doc = Jsoup.connect(url).get();
                  Element e = doc.body();
                  Elements ggg = e.getElementsByAttributeValue("class", "categoryblocks");
                  for (int i =0;i<ggg.size();i++) {
                      Element linkk = ggg.get(i);
                      if(linkk.getElementsByTag("a")!=null){
                          Element atom = linkk.getElementsByTag("a").first();
                          String n = atom.getElementsByTag("span").first().text();
                          names[i] = n;
                      }

                  }
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
    }

    @Override
    protected void onPostExecute(Void result) {

        }

}

Upvotes: 1

Related Questions