0

I am developing an android application which displays a map. When it loads, it displays some addresses and sets markers for them.

When I click on any marker it should display a value in a custom view. But the custom text which is received from a json parser, gets a null value. When I click on the marker again, it sets correct value.

When I click on second marker it display 1st marker value. When I click on 2nd marker again it displays correct value. This process continues

Here's my code:

    private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
        private Context mainContxt;
        Geocoder geocoder;
        public GeocoderTask(Context con){
        mainContxt=con;

        } 

        @Override
        protected List<Address> doInBackground(String... locationName) {
             Geocoder geocoder = new Geocoder(mainContxt);
                List<Address> addresses = null;
                try {
                    addresses = geocoder.getFromLocationName(locationName[0],1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return addresses;
        }


        @Override
        protected void onPostExecute(List<Address> addresses) { 

       for(int i=0;i<addresses.size();i++){             

                Address address = (Address) addresses.get(i);
                latLng = new LatLng(address.getLatitude(), address.getLongitude());

                String addressText = String.format("%s, %s",
                        address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                        address.getCountryName());

                markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title(addressText);
                if(i==0)    {
                    googleMap.animateCamera(CameraUpdateFactory.zoomBy(14),2000,null);
                    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 
                }
                googleMap.addMarker(markerOptions);

            }
       googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker_address) {
                    location=marker_address.getTitle();
                    Toast.makeText(getApplicationContext(),location, Toast.LENGTH_LONG).show();
                new LoadSingleProperty().execute();
                //new LoadImage().execute();
                return false;

            }
        });

        googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }
            @Override
            public View getInfoContents(Marker marker) {

                View myContentView = getLayoutInflater().inflate(
                        R.layout.custom_marker, null);
                tempnew_price=getPrice(temptotal_price+"" +email);
                TextView tvTitle = ((TextView) myContentView
                        .findViewById(R.id.title));
               // tvTitle.setText(location);
                tvSnippet = ((TextView) myContentView
                        .findViewById(R.id.snippet));

               ivProperty = ((ImageView) myContentView
                        .findViewById(R.id.image_property));

               tvTitle.setText(tempcovered_area+ " "+tempnew_price+System.getProperty("line.separator")+templocation);

               tvSnippet.setText("A "+ tempbedroom + " "+tempproperty_type);


              // new LoadImage().execute();
            ivProperty.setImageBitmap(bmp); 
                    return myContentView;


            }
        });
        googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

            @Override
            public void onInfoWindowClick(Marker arg0) {
                Intent intent = new Intent(getBaseContext(),
                        search_property_activity.class);
                intent.putExtra("Email", email);
                startActivity(intent);
            }
        });
    }
    }

this is my loadsingle class coding.....

    class LoadSingleProperty extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivityMap.this);
            pDialog.setMessage("Loading Location. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        protected String doInBackground(String... args) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
            if(location!=null && !location.equals("")){
                params.add(new BasicNameValuePair("Location", location));
                json= jsonParser.makeHttpRequest(url_loc_address, "GET", params);
            }
            Log.d("MyLocation: ", json.toString());

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    address = json.getJSONArray(TAG_ALL_ADDRESS);
                    //for (int i = 0; i < address.length(); i++) {
                        JSONObject c = address.getJSONObject(0);
                        templocation = c.getString(TAG_LOCATION);
                        tempcovered_area=c.getString(TAG_COVERED_AREA);
                        temptotal_price=c.getString(TAG_Total_Price);

                        tempbedroom=c.getString(TAG_BEDROOM);
                        tempproperty_type=c.getString(TAG_PROPERTY_TYPE);
                        tempemail=c.getString(TAG_EMAIL);
                        //} 
                } else {

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



    protected void onPostExecute(String file_url) {
        pDialog.dismiss();  
        new GeocoderTask(MainActivityMap.this).execute(location);
        }


    }

Help me friends ...thx in advance

Tufan
  • 2,789
  • 4
  • 34
  • 52
  • if anyone have answer then help me???? – Tufan Apr 01 '15 at 06:39
  • if i call new GeocoderTask(MainActivityMap.this).execute(location); from loadsinglepropery on background ...nothing is changed – Tufan Apr 01 '15 at 06:50
  • hi .....my suggestion is .. see what value you are getting in 'locatiion'...? i think some thing went wrong here? – GvSharma Apr 01 '15 at 06:56
  • @gvsharma this is my json response when i clicked 1st time 04-01 12:39:10.469: D/MyLocation:(2534): {"address_all":[{"email_id":"asddd@a.bn","location":"Bokaro Steel City, Jharkhand, India","covered_area":"100sq-m","sell_type":"SELL","property_type":"House","total_price":"789","bedroom":"3BHK"}],"success":1} that time all the field of custom view is null – Tufan Apr 01 '15 at 07:14
  • Check if marker's info window is getting displayed before your json parsing is done – random Apr 01 '15 at 07:34
  • yeh @random that is right ..but how to solve it – Tufan Apr 01 '15 at 08:54
  • you're trying to set title tvTitle with a class level variable tempcovered_area inside infowindowadapter tvTitle.setText(tempcovered_area+ " "+tempnew_price+System.getProperty("line.separator")+templocation); You should not set the text until you get the value for tempcovered_area – random Apr 01 '15 at 09:02
  • but m getting value when i click 2nd time in marker @random – Tufan Apr 01 '15 at 09:08
  • that's because the first time you click your marker, and the async task completes, it set the value for tempcovered_area. The second time you click it, this previous value is displayed – random Apr 01 '15 at 09:10
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/74245/discussion-between-tufan-and-random). – Tufan Apr 01 '15 at 09:13
  • so @random how i can solve it acording to #gvsharma comment i had tried that too ..but nthnhg changed – Tufan Apr 01 '15 at 09:17
  • hey @random now check my edited code – Tufan Apr 01 '15 at 09:22

2 Answers2

0
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
    private Context mainContxt;
    Geocoder geocoder;

    public GeocoderTask(Context con) {
        mainContxt = con;

    }

    @Override
    protected List<Address> doInBackground(String... locationName) {
        Geocoder geocoder = new Geocoder(mainContxt);
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocationName(locationName[0], 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addresses;
    }

    @Override
    protected void onPostExecute(List<Address> addresses) {

        for (int i = 0; i < addresses.size(); i++) {

            Address address = (Address) addresses.get(i);
            latLng = new LatLng(address.getLatitude(),
                    address.getLongitude());

            String addressText = String.format(
                    "%s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address
                            .getAddressLine(0) : "", address
                            .getCountryName());

            markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title(addressText);
            if (i == 0) {
                googleMap.animateCamera(CameraUpdateFactory.zoomBy(14),
                        2000, null);
                googleMap.animateCamera(CameraUpdateFactory
                        .newLatLng(latLng));
            }
            googleMap.addMarker(markerOptions);
        }
    }
}

Then you write below code

googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

    @Override
    public boolean onMarkerClick(Marker marker_address) {
        location = marker_address.getTitle();
        new LoadSingleProperty().execute();

        return false;

    }
});

Take another customeWindowAdapter or else use the present one only and set that in onPostExecute() method of 'LoadSingleProperty' AsyncTask.. This will solve that. ping here you have any queries

GvSharma
  • 2,632
  • 1
  • 24
  • 30
0

Create a constructor for LoadSingleProperty

class LoadSingleProperty extends AsyncTask<String, String, String> {
    Marker mMarker;

    public LoadSingleProperty(Marker marker){
      mMarker = marker;
    }

    .
    .
    .
}

and pass your marker object to it.

new LoadSingleProperty(marker_address).execute();

Once parsing is done set your marker's title using setTitle() method for the marker

mMarker.setTitle(c.getString(TAG_PROPERTY_TYPE));

where you currently do this

tempproperty_type=c.getString(TAG_PROPERTY_TYPE);

Don't forget to refresh your info window once title is reset

How to force refresh contents of the markerInfoWindow

You may also want to show some sort of a loading icon till this time since you're performing a network request.

EDIT:

In case you're using a custom titleview, get a reference to InfoWindowAdapter object before setting as a adapter to googleMap

InfoWindowAdapter infoWindowAdapter = new InfoWindowAdapter() {...

Once parsing is complete, get info window view for mMarker object by calling

infoWindowAdapter.getInfoWindow(mMarker);

Find your textView from the view obtained above and set its text. Then refresh your info window by calling showInfoWindow() to update the info window.

Also please refer this link.

The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow()

Community
  • 1
  • 1
random
  • 10,238
  • 8
  • 57
  • 101