Clear all markers when refresh google maps - Android - android

I want to remove all the markers and remove setInfoWindowAdapter when i refresh the maps. But the app will crash if i refresh it.
Here's my code
private final BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
//Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
new GetInfo().execute(Config.INFO_URL);
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
//Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
new GetInfo().execute(Config.INFO_URL);
}
}
}
};
class GetInfo extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MapsActivity.this);
dialog.setMessage("Mohon tunggu");
dialog.setTitle("Mendapatkan data...");
dialog.show();
dialog.setCancelable(true);
}
#Override
protected Boolean doInBackground(String... urls) {
array.clear();
mMarkersHashMap.clear();
mMyMarkersArray.clear();
markerPoints.clear();
targets.clear();
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray konten = jsono.getJSONArray("konten");
mMarkersHashMap = new HashMap<Marker, MyMarker>();
for (int i = 0; i < konten.length(); i++) {
HashMap<String,String> newMap=new HashMap<String,String>();
JSONObject object = konten.getJSONObject(i);
newMap.put("nama", object.getString("nama"));
newMap.put("deskripsi",object.getString("deskripsi"));
newMap.put("foto",object.getString("foto"));
newMap.put("marker", object.getString("marker"));
newMap.put("lat",object.getString("lat"));
newMap.put("lng",object.getString("lng"));
array.add(newMap);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(final Boolean result) {
dialog.cancel();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!result) {
//Toast.makeText(getApplicationContext(), "Tidak dapat mengambil data dari server, silahkan cek koneksi internet anda", Toast.LENGTH_LONG).show();
showInfo();
}
else {
for (int i = 0; i < array.size(); i++) {
HashMap<String, String> newMap = new HashMap<String, String>();
newMap = array.get(i);
mMyMarkersArray.add(new MyMarker(newMap.get("nama"), newMap.get("deskripsi"), newMap.get("foto"), newMap.get("marker"), Double.parseDouble(newMap.get("lat")), Double.parseDouble(newMap.get("lng"))));
}
plotMarkers(mMyMarkersArray);
}
}
});
}
}
Here's the plotMarkers
public void plotMarkers(ArrayList<MyMarker> markers) {
if(markers.size() > 0) {
for (MyMarker myMarker : markers)
{
dest = new LatLng(myMarker.getmLatitude(), myMarker.getmLongitude());
markerOption = new MarkerOptions().position(dest);
location_marker = mMap.addMarker(markerOption);
Target target = new PicassoMarker(location_marker);
targets.add(target);
ImageView image = new ImageView(this);
image.setImageResource(R.mipmap.marker);
int width = image.getDrawable().getIntrinsicWidth();
int height = image.getDrawable().getIntrinsicHeight();
Picasso.with(MapsActivity.this).load(myMarker.getmIcon()).resize(width, height).onlyScaleDown().into(target);
mMarkersHashMap.put(location_marker, myMarker);
i = getIntent();
if(i.getBooleanExtra("maps", true)) {
location_marker.setTitle(i.getStringExtra("nama"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dest, 16));
}
else {
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
}
Here's the refresh menu on action bar
case R.id.action_refresh:
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
return true;
What's wrong with my code?

I'm assuming you still have similar implementation from before.. In order to remove all Markers. You could just call Marker.remove() on the marker instance. In your case, you put the marker instance in a HashMap. So what you could do is something like this:
private void removeAllMarkers() {
// hmap here is the HashMap you have.
for (HashMap.Entry<Marker, MyMarker> entry : hmap.entrySet()) {
entry.getKey().remove();
}
}
This iterates over the HashMap where you add the Markers in plotMarkers function and remove them all. Just call this function in the code where you refresh the Map.
Regarding your concern with the setInfoWindowAdapter, if you're pertaining to the InfoWindow of the Marker, I think so long as you are able to remove the Marker itself, you'll no longer have a problem with it.
Found this answer that shows how to remove a marker. I think this post on iterating over hashmaps would also be helpful for you.

Related

MapsActivity marker won't displayed for second time

I have a MapsActivity in my app which starts by clicking on a button in MainActivity and when activity started I will get markers coordinates by JSON and show them in MapsActivity, but this will happen only in first time and once I press back and go to MainActivity and press the button again MapsActivity starts but markers won't be displayed in that . I tried to finish or destroy activity but that didn't help.
any help will be much appreciated
this is my MapsActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
check_activity = 1;
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
ma_fin = this;
MainActivity.maps_adv = 1;
if (flag == 1) {
map_update();
maps_adv = 0;
}
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
checkLocationPermission();
setUpMapIfNeeded();
map_update();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your Location");
mMap.addMarker(options);
float zoomLevel = 13.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
final ArrayList myList;
if (checker==0) {
myList = (ArrayList<Object>) getIntent().getSerializableExtra("maps");
}
else
{
checker = 0;
myList = maps;
}
mMap = googleMap;
mMap.clear();
for (int i = 0; i < myList.size(); i++) {
LatLng sydney = new LatLng(((Double) (((ArrayList) myList.get(i))).get(2)).doubleValue(), ((Double) (((ArrayList) myList.get(i))).get(3)).doubleValue());
mMap.addMarker(new MarkerOptions().position(sydney).title((String) (((ArrayList) myList.get(i))).get(1)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String position = "0";
String title = marker.getTitle();
for (int i = 0; i < myList.size(); i++) {
if (title.equals(((ArrayList) myList.get(i)).get(1).toString())) {
position = ((ArrayList) myList.get(i)).get(0).toString();
titlename = ((ArrayList) myList.get(i)).get(1).toString();
address = ((ArrayList) myList.get(i)).get(4).toString();
}
}
foo = Integer.valueOf(position);
a = ((ArrayList) myList.get(foo)).get(0).toString();
backgroundTask = new BackgroundTask(textView);
backgroundTask.execute();
map_check = 1;
MainActivity.maps_adv = 0;
return true;
}
});
} catch (RuntimeException e) {
e.printStackTrace();
}
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
jsonobj = new JSONObject();
jsonobj.put("hotel_id_post", foo);
Log.i("EEE", a);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
nameValuePairs.add(new BasicNameValuePair("func", "2"));
nameValuePairs.add(new BasicNameValuePair("adv", MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date", MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", "1"));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServerhotel = str.getStringFromInputStream(inputStream);
Log.e("responseqqqqqqq", "response -----" + responseServerhotel);
HotelList.jsonroom = new JSONObject(responseServerhotel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
if (responseServerhotel.equals("{\"types\":null}"))
{
MainActivity.nothing = "no room to show";
Intent intent = new Intent(MapsActivity.this,Nothing.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(MapsActivity.this, RoomList.class);
startActivity(intent);
}
}
}
private class BackgroundTask1 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask1(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
//mMap.clear();
jsonadv = new JSONObject();
jsonadv_cont = new JSONObject();
jsonobj = new JSONObject();
jsonads = new JSONObject();
MainActivity.features = "";
features_count = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("func", "11"));
nameValuePairs.add(new BasicNameValuePair("adv",
MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" +
features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date",
MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", num));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.e("response", "response -----" + responseServer);
jsonmap = new JSONObject(responseServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (backgroundTask != null) {
backgroundTask.cancel(true);
}
if (backgroundTask1 != null) {
backgroundTask1.cancel(true);
}
if (backgroundTask2 != null) {
backgroundTask2.cancel(true);
}
finish();
}
private class BackgroundTask2 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask2(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MainActivity.url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray mapsarr = jsonmap.getJSONArray("maps");
for (int i = 0; i < mapsarr.length(); i++) {
ArrayList<Object> mapping = new ArrayList<>();
JSONObject c = mapsarr.getJSONObject(i);
String id = c.getString("hotel_id");
String name = c.getString("hotel_name");
Double x = c.getDouble("hotel_x");
Double y = c.getDouble("hotel_y");
String address = c.getString("hotel_address");
mapping.add(0, id);
mapping.add(1, name);
mapping.add(2, x);
mapping.add(3, y);
mapping.add(4, address);
maps.add(i, mapping);
}
Log.i("MAPTEST", mapsarr.toString());
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
onMapReady(mMap);
checker = 1;
}
}
public static class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
}
public void map_update() {
maps.clear();
backgroundTask1 = new BackgroundTask1(textView);
backgroundTask1.execute();
}
public static void refresh()
{
flag = 0;
MapsActivity ma = new MapsActivity();
ma.map_update();
}

Nothing happens in the try

In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.

How to place multiple markers using lat long from JSON

In my app I want to show the multiple marker using latitude and longitude from JSON but when I run the application it only shows one marker, other markers are not shown. Please help - here is my code:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Loading...", "Please wait for few seconds");
// dialog = new ProgressDialog(getActivity().this);
// dialog.setMessage("Loading, please wait");
// dialog.setTitle("Connecting server");
// dialog.show();
// dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// Date a = new Date();
// a.setTime(System.currentTimeMillis()-(60*60*1000));
// Log.e("onehourback",""+a);*/
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("SingleIMEs");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Log.e("object",""+object);
/*try {
array.add(jarray.getJSONObject(i));
Log.e("array",""+array);
} catch (JSONException e)
{
e.printStackTrace();
}*/
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
}
}
//}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
/* adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
*/
}
}
private void setUpMapIfNeeded(View inflatedView) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(latt,lng)).title("eee"));
Log.e("lat",""+latt);
Log.e("lon",""+lng);
mMap.setMyLocationEnabled(true);
if (mMap != null) {
//setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("WePOP"));
// mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position( new LatLng(Double.parseDouble(datas.get("Lat")), Double.parseDouble(datas.get("Long")))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
It looks like you're overwriting your latt and lng variables multiple times in this code:
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
I would suggest you create a List that holds some sort of object containing latt and lng information (something like List positions).
Then modify your code in setUpMapIfNeeded to cycle through all your LatLngs. Something like this:
for(LatLng latlng: positions) {
mMap.addMarker(new MarkerOptions().position(new LatLng(latlng.getLat(),latlng.getLng())).title("eee"));
Log.e("Added marker at lat: " + latlng.getLat() + ", lng: " + latlng.getLng());
}
Notice: It's been quite some time since i've used android and google maps, so the code i've written here probably isn't perfect - but the idea should be good :-)

How not to affect the UI when executing an AsyncTask?

I have an issue, which is not that big, but to the user it is bad.
The app basically gets the user's input of some place and, when the user clicks on the button, a URL to the Google API with the place on its parameter is sent to an AsyncTask, where it sends this URL via HttpGet and is returned a JSONArray with everything needed. The problem is, when I click on the button and the internet is not that good, the button seems to "freeze" like this:
My activity code is below:
public class MainActivity extends Activity{
...
protected void onCreate(Bundle savedInstanceState){...}
public void onResume()}
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
try{
List<Location> locations = new SearchTask(MainActivity.this).execute(strSearch).get();
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
...
}
}
}
}
}
}
My AsyncTask class code is below:
public class SearchTask extends AsyncTask<String, Void, List<Location>>{
...
protected List<Location> doInBackground(String... params){
if(isNetworkAvailable()){
HttpGet httpGet = null;
HttpClient client = null;
HttpResponse response = null;
StringBuilder builder = null;
try{
String param = URLDecoder.decode(params[0], "UTF-8").replace(" ", "%20");
httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?address=" + param + "&sensor=false");
client = new DefaultHttpClient();
builder = new StringBuilder();
}
catch(UnsupportedEncodingException e){
Log.i("Error", e.getMessage());
}
try{
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int val;
while((val = br.read()) != -1){
builder.append((char) val);
}
}
catch(IOException e){
Log.i("Error", e.getMessage());
}
JSONObject jsonObject = new JSONObject();
List<Location> listLocation = new ArrayList<Location>();
int countJson = 0;
try{
jsonObject = new JSONObject(builder.toString());
JSONArray jArray = jsonObject.getJSONArray("results");
countJson = jArray.length();
for(int i = 0; i < countJson; i++){
Location location = new Location();
String formattedAddress = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getString("formatted_address");
double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
location.setFormattedAddress(formattedAddress);
location.setLat(lat);
location.setLng(lng);
listLocation.add(location);
}
}
catch(JSONException e){
Log.i("Error", e.getMessage());
}
return listLocation;
}
else{
return null;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected void onPostExecute(List<Location> result){
super.onPostExecute();
progress.dismiss();
}
private boolean isNetworkAvailable(){
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
return info != null && info.isConnected();
}
}
The ListView is on the same xml of the EditView and the Button.
Is there a way to improve it in order to make the UI not behave like this?
Thanks!
Try this:
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
new SearchTask(MainActivity.this).execute(strSearch);
}
}
#Override
protected void onPostExecute(List<Location> locations){
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
}
progress.dismiss();
}

Using AsyncTasnk and return value and compare with other value

I want to return a value from AsyncTask and I want to compare with the value contents and at the and if they match I want to send the value where I take it from AsyncTasnk to the other intent. I hope I explained it properly.
and this is the code :
public class MainActivity extends Activity {
Button ButtonClick;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView txt = (TextView) findViewById(R.id.textView1);
ButtonClick = (Button) findViewById(R.id.qrReader);
ButtonClick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
GetProduts GP = new GetProduts();
txt.setText(GP.execute().toString());
}
});
// Intent i = new Intent(MainActivity.this,IndexActivity.class);
// startActivity(i);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
final String contents = intent.getStringExtra("SCAN_RESULT");
//I want to compare this value
}
} else if (resultCode == RESULT_CANCELED) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class GetProduts extends AsyncTask<ArrayList<Product>, Void, ArrayList<Product>> {
Product p;
final ArrayList<Product> productIdList = new ArrayList<Product>();
#Override
protected ArrayList<Product> doInBackground(ArrayList<Product>... params) {
HttpClient httpclient = new DefaultHttpClient();
GeneralConstans GC = new GeneralConstans();
// Products will be stated in memory
HttpPost httpget = new HttpPost(GC.UrlProducts);
HttpResponse response;
String result = null;
try {
HttpContext ctx = new BasicHttpContext();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));
response = httpclient.execute(httpget, ctx);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity);
JSONArray arr = new JSONArray(result);
Gson gson = new Gson();
if (arr.length() > 0) {
for (int j = 0; j < arr.length(); j++) {
p = gson.fromJson(arr.getString(j), Product.class);
productIdList.add(p);
}
}
return productIdList;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException e) {
/*
* if (checkAbortStatus(e.getMessage()) == true) {
* handler.sendEmptyMessage(0); }
*/
} catch (IOException e) {
/*
* if (checkAbortStatus(e.getMessage()) == true) {
* handler.sendEmptyMessage(0); }
*/
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Product> result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
}
Declare contents under Button ButtonClick; as:
String contents = "";
In onActivityResult(), replace:
final String contents = intent.getStringExtra("SCAN_RESULT");
with:
contents = intent.getStringExtra("SCAN_RESULT");
result in onPostExecute(ArrayList<Product> result) is productIdList. Change your onPostExecute() to:
#Override
protected void onPostExecute(ArrayList<Product> result) {
super.onPostExecute(result);
if (result != null) {
for (int i = 0; i < result.size(); i++) {
if(result.get(i).toString().equals(contents) {
// Do something
}
}
}
}
Also, the following doesn't look correct:
public void run() {
GetProduts GP = new GetProduts();
txt.setText(GP.execute().toString());
}
Instead try this:
public void run() {
new GetProduts().execute();
}
And declare txt as TextView txt; under Button ButtonClick;. Now, add the following line to your onPostExecute():
txt.setText(....); // Replace .... with whatever you are trying to set.
Edit 1:
To start another activity:
if(result.get(i).toString().equals(contents) {
// Change "OtherActivity" to the name of the activity you want to start
Intent newIntent = new Intent(MainActivity.this, OtherActivity.class);
newIntent.putExtra("My_Extra", result.get(i).toString());
startActivity(newIntent);
}
To retrieve this String in the other activity:
String extraString = getIntent().getStringExtra("My_Extra");

Categories

Resources