2

I can't find any solution for this!! I need parsing a html page with jsoup and i need parse the image too but i can't do it! This is my MainActivity

public class MainActivity extends Activity {
    public static final String TAG_TITOLI = "titoli";
    private static final String TAG_CONTENT = "content";
    ListView lista;
    static final String BLOG_URL = "http://www.multiplayer.it";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lista = (ListView)this.findViewById(R.id.main_lista);//recupero lista da id

        //creo ed eseguo l'asynctask
        ParsingPaginaWeb parsing = new ParsingPaginaWeb();
        parsing.execute("");



         // Launching new screen on Selecting Single ListItem
            lista.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting values from selected ListItem
                    String titoli = ((TextView) view.findViewById(R.id.riga_listview_titolo)).getText().toString();
                    //String cont = ((TextView) view.findViewById(R.id.riga_descrizione)).getText().toString();
                    //String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

                    // Starting new intent
                    Intent in = new Intent(getApplicationContext(), SingleActivity.class);
                    in.putExtra(TAG_TITOLI, titoli);
                    //in.putExtra(TAG_CONTENT, cont);
                    //in.putExtra(TAG_PHONE_MOBILE, description);
                    startActivity(in);

                }
            });

    }

    private class ParsingPaginaWeb extends AsyncTask<String,String,String> {

        ArrayList<String> titoli; //lista dei titoli
        //ArrayList<String> content; //lista delle descrizioni

        @Override
        protected void onPreExecute()
        {   
            Toast.makeText(MainActivity.this ,"Caricamento lista titoli...", Toast.LENGTH_SHORT).show();
            //prima di eseguire il parsing inizializzo gli arraylist
            titoli = new ArrayList<String>();
            //content = new ArrayList<String>();
        }

        @Override
        protected String doInBackground(String... params) {
            try {

                Document doc = Jsoup.connect(BLOG_URL).get();
                Elements nodeBlogStats = doc.select("div.news-col-0 h3"); //per multiplayer.it Elements nodeBlogStats = doc.select("div.news-col-0 h3"); per ftv #comunePartINI > option
                for(Element sezione : nodeBlogStats)
                {
                    titoli.add(sezione.text());
                }
            } catch (Exception e) {
                // In caso di errore
                Log.e("ESEMPIO", "ERRORE NEL PARSING");
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result)
        {
            // dopo che ho eseguito il parsing mostro i dati nella listview
            // usando il custom array adpater ParsingArrayAdapter
            ParsingArrayAdapter adapter = new ParsingArrayAdapter(MainActivity.this, titoli);
            lista.setAdapter(adapter);
        }


    }

}

In which i can parse the titles and dispaly them in a ListView.. This is the Adapter:

public class ParsingArrayAdapter extends ArrayAdapter<String>{

    //riferimenti statici alle risorse e agli id
    private final static int LAYOUT = R.layout.riga_listview;
    private final static int TITOLO = R.id.riga_listview_titolo;
    //private final static int DESCRIZIONE = R.id.riga_listview_descrizione;

    ArrayList<String> titoli; //lista dei titoli

    Context c; //context
    LayoutInflater inflater; //layout inflater

    public ParsingArrayAdapter(Context context,ArrayList<String> titoli)
    {
        super(context,TITOLO);
        this.c = context;
        this.titoli = titoli;
        this.inflater = LayoutInflater.from(c);
    }

    @Override
    public int getCount()
    {
        return titoli.size(); //ritorno lunghezza lista ( = numero dei titoli)
    }

    //quando la lista richiede una view
    @Override
    public View getView(int pos,View view,ViewGroup parent)
    {
        CacheRiga cache; //cache
        if(view==null)//se è la prima volta che viene richiesta la view
        {
            // creo la view ma non l'attacco alla lista in quanto devo ancora modificare
            // i testi delle textview
            view = inflater.inflate(LAYOUT, parent,false); 
            cache = new CacheRiga(); //inizializzo la cache
            cache.titolo = (TextView) view.findViewById(TITOLO); //collego titolo
            //cache.descrizione = (TextView) view.findViewById(DESCRIZIONE);//collego descrizione
            view.setTag(cache);//collego view con cache
        }
        else
        {
            cache = (CacheRiga) view.getTag(); //altrimenti prendo la cache dalla view
        }

        cache.titolo.setText(titoli.get(pos)); //imposto il titolo

        return view;
    }

    private class CacheRiga { // classe per la cache delle righe
        public TextView titolo; // cache titolo
        //public TextView descrizione; // cache descrizione
    }

}

How can i insert the images for each article? I can't simply parse the div of image because i display a string of characters.. Is there a way to insert it in the listview? Thanks. Ah if needs, this is the riga_listview.xml in which, i suppose, i need insert the ImageView part.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/riga_listview_titolo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:layout_margin="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>
David_D
  • 1,404
  • 4
  • 31
  • 65
  • 3
    You'd get the url from JSOUP and then download the image and display or use something like Universal Image Loader library. And yes you will need to have an `ImageView` inside your `ListView` item layout. – hypd09 Jan 17 '14 at 09:05
  • can you help me to do it? Because i'm trying from about 1 mounth without success! It's frustrating. – David_D Jan 17 '14 at 09:06
  • Actually if i write: `Elements nodeBlogStats = doc.select("img[src~=(?i)\\.(jpe?g)]");` and `titoli.add(sezione.attr("src"));` i can display the url of the images but not the images itself! How can i display them from the textview to the imageview? What have i to change? And how can i display both thing! Titles and images? – David_D Jan 17 '14 at 09:33

2 Answers2

1

Break it into pieces -

  1. Get the url of the image from div tag
  2. Show that image in the list view

Now for "1", you can use jsoup and parse the url of the image

For "2", first add image view to your list view xml Then create an asynctask, pass image url to it and reference of image view and set its value in onPostExecute. You said that website sets image dynamically, in that case every time on the get view method of list view adapter, you have to parse the webpage. Although this sounds very inefficient and intensive, but I don't think there is any other way. If somehow you can know when is the image going to change, then you can do this processing on that event. Anyway, this is the code of the asynctask to download the image from a url and set it to image view

public class ThumbnailDownloader extends AsyncTask<String, Integer, Bitmap>{

ImageView imview;
Context ctx;

public ThumbnailDownloader(Context c, ImageView imview){
    this.imview = imview;
    this.ctx = c;
}

@Override
protected Bitmap doInBackground(String... urls) {
        try{
            HttpURLConnection connection = (HttpURLConnection)new URL(getThumbUrl(urls[0])).openConnection();

            connection.connect();
            InputStream input= connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
        return bitmap;

        }
        catch (Exception f) {
            // TODO Auto-generated catch block
            f.printStackTrace();
        }
    return null;
}

@Override
protected void onPostExecute(Bitmap result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    if(result != null && imview!=null){
        imview.setImageBitmap(result);
    }
}

public String getThumbUrl(String videoUrl){
    return "http://img.youtube.com/vi/"+videoUrl+"/default.jpg";
}
}

The getThumbUrl method you have to modify according to your need. The one specified above is used to download youtube video thumbnails.

Anurag
  • 1,521
  • 2
  • 17
  • 34
0

check thease links:

how-can-i-download-an-image-using-jsoup

download-images-from-a-website-using-jsoup

Community
  • 1
  • 1
muhammedabuali
  • 611
  • 3
  • 15
  • Nothing :( so you suggest to download the images in the device and then display them? – David_D Jan 17 '14 at 10:08
  • I think you have to according to [android hive](http://www.androidhive.info/2012/07/android-loading-image-from-url-http/) – muhammedabuali Jan 17 '14 at 11:00
  • Well, yeah maybe could be a solution.. But the "problem" is that i can't know the url of all images. The website load the articles dynamically and every time there is a new image for each article. Here in this post you suggested me, the developer knows the absolute url path of the image. I can't find a solution really.. Can you help me with my project? – David_D Jan 19 '14 at 11:28
  • if you want all images , then [check this](http://stackoverflow.com/questions/19800906/getting-image-url-using-jsoup) – muhammedabuali Jan 19 '14 at 15:14