Search code examples
androidgoogle-mapsrefreshreloadlistview-adapter

Refresh GoogleMap on Android from the ListviewAdapter


I am currently creating a google maps app and I am trying to get it to refresh after the user clicks on an item in a listview. However with the listviewadapter being in a different part of the code this is not going as planned. I've tried multiple ways including turning certain parts of the code to static however this only breaks the google maps code.

Here is the code from my main activity where the map is:

public class MainActivity extends ActionBarActivity {

GoogleMap googleMap;

// products JSONArray
JSONArray locations = null;

ListView townList;
ListViewAdapter townAdapter;
String[] townID;    
String[] townName;
ArrayList<TownSelector> arraylist = new ArrayList<TownSelector>();
public static String currentLocationID;

public String getLocationID()
{
    return this.currentLocationID;
}
public static String setLocationID(String l)
{
    return currentLocationID = l;
}

public static boolean refreshMap = false;

public boolean getRefreshMap()
{
    return this.refreshMap;
}
public static boolean setRefreshMap(Boolean m)
{
    return refreshMap = m;
}

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

    // Locate the ListView in listview_main.xml
    townList = (ListView) findViewById(R.id.listview);
}

private void setUpMap() {
    // enable MyLocation Layer of the Map
    googleMap.setMyLocationEnabled(true);

    // get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    //set map type
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    // Get lattitude of the current location
    double latitude = myLocation.getLatitude();

    //get longitude of the current location
    double longitude = myLocation.getLongitude();

    //Create a LatLong object for the current location
    LatLng latLng = new LatLng(latitude,longitude);

    // show the current location in google map
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the map
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
    //googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude)).title("Location").snippet("You're here"));
}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllInfo extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Loading Bars. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters            
        List<NameValuePair> paramsLocations = new ArrayList<NameValuePair>();
        // getting JSON string from URL            
        JSONObject jsonLocations = jParser.makeHttpRequest(url_all_locations, "GET", paramsLocations);

        //Get all Locations
        if(jsonLocations != null)
        {
            // Check your log cat for JSON reponse
            Log.d("All Locations: ", jsonLocations.toString());
            try {

                // Checking for SUCCESS TAG
                int success = jsonLocations.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Locations
                    locations = jsonLocations.getJSONArray(TAG_LOCATIONS);

                    // looping through All Offers
                    for (int i = 0; i < locations.length(); i++) {
                        JSONObject c = locations.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_LID);
                        String locationName = c.getString(TAG_LNAME);

                        // creating new HashMap
                        HashMap<String, String> locationsListMap = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        locationsListMap.put(TAG_LID, id);
                        locationsListMap.put(TAG_LNAME, locationName);

                        // adding HashList to ArrayList
                        locationList.add(locationsListMap);

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

        return null;            
    } 

    }

}

}

Here is the code from the ListViewAdapter activity:

 view.setOnClickListener(new OnClickListener() { 
        @Override
        public void onClick(View arg0) {            

            MainActivity.setLocationID(locationlist.get(position).getID());
            MainActivity.setRefreshMap(true);
        }
    });

    return view;
}

Any suggestions? I am tempted to add an update feature which will check for a static boolean to be turned from false to true when the user clicks a list item, however I believe there should be an easier way than this

EDIT: I have added the setOnItemClickListenerin the main activity and have entered a Log.d string just to see if it worked and I don't recieve any things after hitting any of the four Town names I have in the list

    townList.setOnItemClickListener(new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
           Log.d("Hello","Why?");            
       } 
    });

Solution

  • I got the fix thanks to Chitrang's comments above. First I added:

    townList.setOnItemClickListener(new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
           Log.d("Hello","Why?");            
       } 
    });
    

    And then when he mentioned I needed to remove some focus in the adapter I realized I hadn't deleted the previous setOnClickListener that I had left in the listviewadapter code.