1

Hi guys I'm developing an app with a map and I did custom infowindow with four TextView and an ImageView. Now I know that an InfoWindow is a pre-rendered image and so my issue is that I want to appear a personalized image for every marker: All it works but on first tap there is only a blank space on second tap the image appears successfully.

First tap: first_tap

Then when I tap for the second time on the marker: second_tap

I obviously wanna avoid to tap two times to make the pic show..it's a big problem. I use Picasso library to load image from the web and I keep Images URLs from four xml files. So I understood the problem was that, when the system make cache of images the system can load the Images. So I thought to this workaround: I put when the app start a call to an Asynctask to load images on invisible Imageview, but this work only for the last URL it keep from the xml and not for others marker. So I wanna ask you if you have some ideas to do this.

Below my codes:

At the beginning I call the AsyncTask:

View v = this.getWindow().getDecorView().findViewById(R.id.immaginenascosta);
CacheTask cacheTask = new CacheTask(v);
cacheTask.execute();

CacheTask, the class that extend AsyncTask download xml files from the Internet and save them on the SDcard (on Background), then it read from xml (on SDcard) and load images on Gone ImageView:

CacheTask

public class CacheTask extends AsyncTask<Void, Void, Void>{

    String [] imgurlarray = {};
    int dim = 0;

    String root = "http://www.emmebistudio.com/markers_Predappio_living/";
    String [] arraymarkers = {"markers_history.xml","markers_hotel.xml","markers_restaurant.xml","markers_souvenir.xml"};

    String pathdirectory = "/sdcard/PredappioLiving";

    private View view;


    public CacheTask(View view){
        this.view = view;

    }

    public void MakeCache (View v)
    {

    }


    @Override
    protected Void doInBackground(Void... params) {


        for (int i = 0; i < arraymarkers.length; i++)
        {
            String urlcompleta = root+arraymarkers[i];

            //Estraggo la stringa del nome dall'url--------------------------------------------------------------

            String stringurl = urlcompleta.toString();          // Prende: http://www.emmebistudio.com/Predappio_living/markers.xml e lo mette in array
            String [] urlarray = stringurl.split("/");  //           ^   ^          ^                 ^             ^
                                                        //           |   |          |                 |             |
                                                        //           |   |          |                 |             |
            String nomefile = urlarray[4];              //           0   1          2                 3             4  

            //Adattare a seconda della posizione definitiva dei file XML

            //----------------------------------------------------------------------------------------------------


            try {
                URL url = new URL(urlcompleta);

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);
                urlConnection.connect();

                File dir = new File(pathdirectory);
                dir.mkdirs();

                File fileWithinMyDir = new File(dir, nomefile);
                FileOutputStream fileOutput = new FileOutputStream(fileWithinMyDir);

                InputStream inputStream = urlConnection.getInputStream();

                int totalSize = urlConnection.getContentLength();   //mi salvo la lunghezza del file da salvare
                int downloadedSize = 0;
                byte[] buffer = new byte[1024];
                int bufferLength = 0;   //per salvare usiamo una dimensione temporanea del buffer
                                        // salvo attraverso il buffer di input e scrivo il contenuto nel file.
                while((bufferLength = inputStream.read(buffer)) > 0){
                    fileOutput.write(buffer,0,bufferLength);
                    downloadedSize += bufferLength;
                    int progress = (int)(downloadedSize*100/totalSize);
                }

                fileOutput.close();
            }

            catch(Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        for (int i = 0; i < arraymarkers.length; i++)
        {
            String urlcompleta = root+arraymarkers[i];

            //Estraggo la stringa del nome dall'url--------------------------------------------------------------

            String stringurl = urlcompleta.toString();          // Prende: http://www.emmebistudio.com/Predappio_living/markers.xml e lo mette in array
            String [] urlarray = stringurl.split("/");  //           ^   ^          ^                 ^             ^
                                                        //           |   |          |                 |             |
                                                        //           |   |          |                 |             |
            String nomefile = urlarray[4];              //           0   1          2                 3             4  

            //Adattare a seconda della posizione definitiva dei file XML

            //----------------------------------------------------------------------------------------------------

            try{
                /* * * * *   Inizio Parsing    * * * * */
                /***************************************/
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new FileInputStream(pathdirectory+"/"+nomefile));
                doc.getDocumentElement().normalize();

                NodeList markers = doc.getElementsByTagName("marker");

                ImageView []image = new ImageView[100];
                image[i]=(ImageView) view.findViewById(R.id.immaginenascosta);
                //ImageView image = (ImageView) view.findViewById(R.id.immaginenascosta);
                for (int j=0; j<markers.getLength(); j++){
                    Element item = (Element) markers.item(i);
                    String urlimmagine = item.getAttribute("immagine");

                    Picasso.with(view.getContext())
                        .load(urlimmagine)
                        .error(R.drawable.ic_launcher)  //in caso di errore fa vedere questa immagine (un triangolo penserei)
                        .resize(150, 110)
                        .into(image[i]);                    

                }
            /***************************************/
                /* * * * *    Fine Parsing     * * * * */
            }catch(Exception e){
                e.printStackTrace();
            }


        super.onPostExecute(result);
    }
}
}

And this is the layout of the "Gone" ImageView:

<ImageView 
    android:id="@+id/immaginenascosta"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:visibility="gone"/>

And this is the setInfoWindowAdapter:

map.setInfoWindowAdapter(new InfoWindowAdapter() {

    View v = getLayoutInflater().inflate(R.layout.custom_info_window, null);



    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {

    //Prova immagine custom
    /***********************************/
    //final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "Attendere...", "Caricamento delle immagini in corso..", true);

    BuildInfoMatrix req = new BuildInfoMatrix();

    String nome = marker.getTitle();
    String currentUrl = "";
    //String currentUrl=req.findImageUrl(nome);
    int vuoto = -15;
    try{
        currentUrl=req.findImageUrl(nome);
    }catch(Exception e){
        currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png";
    }
    if (currentUrl == null)
    {
        currentUrl = "http://upload.wikimedia.org/wikipedia/commons/b/bb/XScreenSaver_simulating_Windows_9x_BSOD.png";
    } 
    ImageView image;
    image = (ImageView) v.findViewById(R.id.image_nuvoletta);

    Picasso.with(v.getContext())
        .load(currentUrl)
        .error(R.drawable.ic_launcher)  //in caso di errore fa vedere questa immagine (un triangolo penserei)
        .resize(150, 110)
        .into(image, new Callback(){

        @Override
        public void onSuccess(){

        }

        @Override
        public void onError(){

        }
}); 


    /***********************************/


    /* Distanza a piedi e macchina sulla nuvoletta */
    /***********************************************/
    GPSTracker gpsTracker = new GPSTracker(MainActivity.this);

    if (gpsTracker.canGetLocation())
    {
        String stringLatitude = String.valueOf(gpsTracker.latitude);
        String stringLongitude = String.valueOf(gpsTracker.longitude);
        double currentLat = Double.parseDouble(stringLatitude);
        double currentLng = Double.parseDouble(stringLongitude);

        double destLat = marker.getPosition().latitude;
        double destLng = marker.getPosition().longitude;

        final float[] results = new float[3];
        Location.distanceBetween(currentLat, currentLng, destLat, destLng, results);

        float metri = results[0];
        float km = Math.round((double)metri/1000);

        int minuti_persona = (int)Math.round(metri/125);    //125 metri al minuto -> velocità media di 2,5 m/s
        int minuti_auto = (int)Math.round(km/0.7);          //700 metri al minuto -> velocità media di 42 km/h 


        /***********************************************/



        TextView tvTitle = (TextView) v.findViewById(R.id.title);
        TextView tvSnippet = (TextView) v.findViewById(R.id.snippet);
        tvSnippet.setTypeface(tvSnippet.getTypeface(), Typeface.ITALIC); //indirizzo in corsivo
        TextView tvPedonal_distance = (TextView) v.findViewById(R.id.pedonal_time);
        TextView tvCar_distance = (TextView) v.findViewById(R.id.car_time);
        tvTitle.setText(marker.getTitle());
        tvSnippet.setText(marker.getSnippet());

        if(minuti_persona <=0)          // Stampa tempo per coprire la distanza
        {
            tvCar_distance.setText("A piedi: meno di un minuto");
        }else
        {
            tvPedonal_distance.setText("A piedi: "+minuti_persona+ " minuti");
        }

        if(minuti_auto <= 0)
        {
            tvCar_distance.setText("In auto: meno di un minuto");                                   
        }else
        {
            tvCar_distance.setText("In auto: " +minuti_auto+ " minuti");
        }

        return v;
   }else
   {
        TextView tvTitle = (TextView) v.findViewById(R.id.title);
        TextView tvSnippet = (TextView) v.findViewById(R.id.snippet);
        tvTitle.setText(marker.getTitle());
        tvSnippet.setText(marker.getSnippet());
        return v;
   }

}

});

Thank you everyone.

Pierpaolo Ercoli
  • 1,028
  • 2
  • 11
  • 32

1 Answers1

0

Because of the asynchronous nature of image loading, the trick is to 'invalidate' the displayed info window once an image has been loaded into memory. In order to do this, you'll have to keep track of the marker that was last tapped and check whether it's still displaying its info window. Then call showInfoWindow() again to force a visual update of the info window:

if (markerShowingInfoWindow != null && markerShowingInfoWindow.isShowingInfoWindow()) {
    markerShowingInfoWindow.showInfoWindow();
}

For more details, refer to:

Community
  • 1
  • 1
MH.
  • 45,303
  • 10
  • 103
  • 116