android Error inflating class fragment when used with map fragment - android

I'm trying to display a google map inside a fragment.The location is plotted correctly inside map but when i press back after mapping the location it shows another fragment and again press back showing an inflate exception.
Note:-
I have used only one activity and all other pages are fragments.
The below given is the code snippet for fragment(for displaying gmap)
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map_container"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
logcat:-
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.integral.loqal, PID: 15338
android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979)
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670)
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #84: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979) 
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670) 
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.IllegalArgumentException: Binary XML file line #84: Duplicate id 0x7f0b0119, tag null, or parent id 0x7f0b00bb with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at com.integral.loqal.Fragment.AddLocationFragment.onCreateView(AddLocationFragment.java:111) 
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) 
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:979) 
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1670) 
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:577) 
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) 
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
java code:-
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.integral.loqal.CheckNetworkConnection;
import com.integral.loqal.Model.LocationItems;
import com.integral.loqal.PlaceDetailsJSONParser;
import com.integral.loqal.PlaceJSONParser;
import com.integral.loqal.R;
import com.integral.loqal.SessionManager;
import com.integral.loqal.Util.Utility;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
public class AddLocationFragment extends Fragment implements OnMapLongClickListener, OnMarkerDragListener {
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_google_map, container, false);
mapTextView = (TextView) v.findViewById(R.id.mapTextView);
doneTextView = (TextView) v.findViewById(R.id.doneTextView);
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container)).getMap();
googleMap.setOnMarkerDragListener(this);
googleMap.setOnMapLongClickListener(this);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
atvPlaces = (AutoCompleteTextView) v.findViewById(R.id.searchLoc);
atvPlaces.setThreshold(1);
atvPlaces.showDropDown();
latlong = latitude + "," + longitude;
LatLng latLng = new LatLng(latitude, longitude);
marker = googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
backarrowImageView = (ImageView) v.findViewById(R.id.backArrowImageView);
Bundle bundle = this.getArguments();
int myInt = bundle.getInt("key", 0);
if (myInt != 0 && myInt == 1) {
mapTextView.setVisibility(View.INVISIBLE);
backarrowImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStack();
});
doneTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean inet = new CheckNetworkConnection().isNetworkAvailable(getContext());
if (inet == true) {
if (atvPlaces.getText().toString().equals("")) {
Toast.makeText(getContext(), "Please choose a location", Toast.LENGTH_SHORT).show();
} else {
updateLocation();
utility.registerUserResponse(jsonObject, UserLocationSet_URL,
"UserLocationSet", getContext());
}
} else {
Toast.makeText(getContext(), "Check your internet connection", Toast.LENGTH_SHORT).show();
}
}
});
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long id) {
ListView lv = (ListView) arg0;
SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container)).getMap();
public String getAutoCompleteUrl(String place) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=";
// place to be be searched
String input = "input=" + place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;
return url;
}
private String getPlaceDetailsUrl(String ref) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=";
// reference of place
String reference = "reference=" + ref;
Log.d("TAg", reference);
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;
return url;
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
String s[] = data.split(",");
String pl = s[0];
System.out.println(pl);
br.close();
} catch (Exception e) {
// Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onMapLongClick(LatLng arg0) {
if (marker != null) {
marker.remove();
}
marker = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(arg0.latitude,
arg0.longitude))
.draggable(true).visible(true));
}
#Override
public void onMarkerDragStart(Marker arg0) {
}
#Override
public void onMarkerDrag(Marker arg0) {
}
#Override
public void onMarkerDragEnd(Marker arg0) {
LatLng dragPosition = arg0.getPosition();
latitude = dragPosition.latitude;
longitude = dragPosition.longitude;
dataloc = latitude + "," + longitude;
String name = getCompleteAddressString(latitude, longitude);
editor.putString("latitudeKey", Double.toString(latitude));
editor.putString("longitudeKey", Double.toString(longitude));
editor.putString("LocationName", name);
editor.commit();
latlong = latitude + "," + longitude;
Log.i("info", "on drag end :" + latitude + " dragLong :" + longitude);
Toast.makeText(getContext(), "Marker Dragged..!", Toast.LENGTH_SHORT).show();
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
System.out.println(list);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
try {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{android.R.id.text1};
if (getActivity() != null) {
adapter = new SimpleAdapter(getActivity(), result, android.R.layout.simple_list_item_1, from, to);
atvPlaces.setAdapter(adapter);
}
break;
case PLACES_DETAILS:
HashMap<String, String> hm = result.get(0);
// Getting latitude from the parsed data
double newlatitude = Double.parseDouble(hm.get("lat"));
// Getting longitude from the parsed data
double newlongitude = Double.parseDouble(hm.get("lng"));
latlong = newlatitude + "," + newlongitude;
// Getting reference to the SupportMapFragment of the activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_container);
// Getting GoogleMap from SupportMapFragment
googleMap = fm.getMap();
LatLng point = new LatLng(newlatitude, newlongitude);
CameraUpdate cameraPosition = CameraUpdateFactory.newLatLng(point);
CameraUpdate cameraZoom = CameraUpdateFactory.zoomBy(15);
dataloc = latitude + "," + longitude;
// Utility.locationChange = latlong;
System.out.println(atvPlaces.getText().toString());
String s = atvPlaces.getText().toString();
String p[] = s.split(",");
String pla = p[0];
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, zoomLevel));
MarkerOptions options = new MarkerOptions();
options.position(point);
options.title("Position");
options.snippet("Latitude:" + newlatitude + ",Longitude:" + newlongitude);
if (marker != null)
marker.remove();
// Adding the marker in the Google Map
marker = googleMap.addMarker(options);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void onBackPressed() {
getFragmentManager().popBackStack();
}
#Override
public void onResume() {
super.onResume();
}
}
I dont know why it is showing the error.Can someone help me to find a solution? 

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map_container"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Please checkout this link for GOOGLE MAP DOCUMENTATION
Activity Class
/**
* init map fragment and get map async task
*/
private void initMapFragment() {
AppUtils.showLog(TAG, "initMapFragment");
try {
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} catch (Exception ex) {
ex.printStackTrace();
}
}
XML File
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mapwithmarker.MapsMarkerActivity" />

Related

how add marker on map onmaplong click?

Address Dailoge This is an Fragment when I click on image another activity (Location Activity)start in which Google map open.
Here is code of Address Dailoge fragment
when map open i want show the Current Location of user and user select the location from map using map picker
when user select the Location i want to take the Addresses of the street zipcode,state,country set it to the form.
public class AddressDialog extends DialogFragment {
public interface AddressListener {
void address(Address address);
void editedAddress(Address locationModel, int index);
}
private static final String TAG = "AddressDialog";
#BindView(R.id.addresslineone)
FormAnimationView addresslineone;
private GoogleApiClient mClient;
#BindView(R.id.addresslinetwo)
FormAnimationView addresslinetwo;
#BindView(R.id.city)
FormAnimationView cityView;
#BindView(R.id.state)
FormAnimationView stateView;
#BindView(R.id.country)
FormAnimationView countryView;
private boolean isfromEdit;
#BindView(R.id.pincode)
FormAnimationView pincode;
#BindView(R.id.edit_spinner_1)
EditSpinner mEditSpinner1;
private Address address = new Address();
private AddressListener addressListener;
private int index;
#OnClick(R.id.closedialog)
public void closeClick() {
this.dismiss();
}
#BindView(R.id.searchmap)
ImageView openmap;
#OnClick(R.id.searchmap)
public void searchmapclick() {
startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);
}
#OnClick(R.id.addaddressimg)
public void addClick() {
if (addressListener != null && address != null) {
if (!TextUtils.isEmpty(mEditSpinner1.getText()) &&
!TextUtils.isEmpty(addresslineone.getText())
&& !TextUtils.isEmpty(addresslinetwo.getText())
&& !TextUtils.isEmpty(cityView.getText())
&& !TextUtils.isEmpty(stateView.getText())
&& !TextUtils.isEmpty(pincode.getText())
&& !TextUtils.isEmpty(countryView.getText())) {
//locationModel.setAddressType(mEditSpinner1.getText().toString());
//address.setCountry(addresslinetwo.getText().toString());
// address.setLocality();
//address.setLocality("");
address.setRegion(stateView.getText().toString());
address.setFormatted(addresslineone.getText().toString());
address.setFormatted(addresslinetwo.getText().toString());
address.setCountry(countryView.getText().toString());
address.setLocality(cityView.getText().toString());
// address.setState(stateView.getText().toString());
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
address.setType(mEditSpinner1.getText().toString());
// address.setRegion();
if (!isfromEdit) {
addressListener.address(address);
} else {
addressListener.editedAddress(address, address.getIndex());
}
this.dismiss();
} else {
Toast.makeText(getActivity(), "All fields are mandetory", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStart() {
super.onStart();
mClient.connect();
}
#Override
public void onStop() {
mClient.disconnect();
super.onStop();
}
// #Override
// public void onAttach(Context context) {
// super.onAttach(context);
// //addressListener = (AddressListener) context;
// }
public void setListener(AddressListener addressListener) {
this.addressListener = addressListener;
}
/* #NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view = View.inflate(getActivity(), R.layout.address_selection_view, null);
Dialog dialog = new Dialog(getActivity(), R.style.DialogFragment);
dialog.setContentView(view);
return dialog;
}*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// getDialog().getWindow().getWindowStyle().gets;
View rootView = inflater.inflate(R.layout.address_selection_view, container, false);
// getDialog().setTitle("Simple Dialog");
ButterKnife.bind(this, rootView);
mClient = new GoogleApiClient
.Builder(getContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
try {
Address locationModel = (Address) getArguments().get("data");
if (locationModel != null) {
// getAddressDetails(locationModel.getAddress());
address.setAddressId(locationModel.getAddressId());
address.setFormatted("");
address.setCountry(addresslinetwo.getText().toString());
address.setLocality("");
address.setRegion("");
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
addresslineone.setText(locationModel.getStreetAddress());
addresslinetwo.setText(locationModel.getStreetAddress());
/*addresslinetwo.setText(locationModel.getCountry());*/
pincode.setText(locationModel.getPostalCode());
mEditSpinner1.setText(locationModel.getType());
countryView.setText(locationModel.getCountry());
stateView.setText(locationModel.getRegion());
cityView.setText(locationModel.getLocality());
isfromEdit = true;
}
} catch (Exception e) {
}
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
addresslineone.setHintMessage("Address Line 1 (Street / landmark)");
addresslineone.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslineone.setTintColor(Color.parseColor("#de3f5abd"));
addresslineone.setFontStyle("fonts/Helvetica.otf");
addresslinetwo.setHintMessage("Address Line 2 (City / Country)");
addresslinetwo.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslinetwo.setTintColor(Color.parseColor("#de3f5abd"));
addresslinetwo.setFontStyle("fonts/Helvetica.otf");
pincode.setHintMessage("Post / Zip / Pin Code");
pincode.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
pincode.setFontStyle("fonts/Helvetica.otf");
pincode.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setInputType(InputType.TYPE_CLASS_TEXT);
stateView.setHintMessage("State");
stateView.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setFontStyle("fonts/Helvetica.otf");
countryView.setInputType(InputType.TYPE_CLASS_TEXT);
countryView.setHintMessage("Country");
countryView.setTintColor(Color.parseColor("#de3f5abd"));
countryView.setFontStyle("fonts/Helvetica.otf");
cityView.setInputType(InputType.TYPE_CLASS_TEXT);
cityView.setHintMessage("City");
cityView.setTintColor(Color.parseColor("#de3f5abd"));
cityView.setFontStyle("fonts/Helvetica.otf");
ListAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.edits_array_1));
mEditSpinner1.setAdapter(adapter);
}
public void getAddressDetails(String address) {
StringBuilder stringBuilder = new StringBuilder();
if (address != null) {
String[] addressSlice = address.toString().split(", ");
String country = addressSlice[addressSlice.length - 1];
if (country != null) {
addresslinetwo.setText(country);
countryView.setText(country);
}
stringBuilder.append("Country:" + country);
if (addressSlice.length > 1) {
String[] stateAndPostalCode = addressSlice[addressSlice.length - 2].split(" ");
if (stateAndPostalCode.length > 1) {
String postalCode = stateAndPostalCode[stateAndPostalCode.length - 1];
String state = "";
for (int i = 0; i < stateAndPostalCode.length - 1; i++) {
state += (i == 0 ? "" : " ") + stateAndPostalCode[i];
}
stringBuilder.append("PostalCode:" + postalCode);
stringBuilder.append("State:" + state);
if (postalCode != null) {
pincode.setText(postalCode);
}
if (state != null) {
stateView.setText("" + state);
// pincode.setText(pincode.getText() + "," + state);
}
} else {
String state = stateAndPostalCode[stateAndPostalCode.length - 1];
stringBuilder.append("State:" + state);
stateView.setText("" + state);
}
}
String city = null;
if (addressSlice.length > 2)
city = addressSlice[addressSlice.length - 3].toString();
if (city != null) {
cityView.setText("" + city);
// addresslinetwo.setText(addresslinetwo.getText() + "," + city);
stringBuilder.append("City:" + city);
}
String stAddress1 = "";
if (addressSlice.length == 4)
stAddress1 = addressSlice[0];
else if (addressSlice.length > 3) {
String stAddress2 = addressSlice[addressSlice.length - 4];
for (int i = 0; i < addressSlice.length - 4; i++) {
stAddress1 += (i == 0 ? "" : ", ") + addressSlice[i];
}
}
stringBuilder.append("Address1:" + stAddress1);
if (stAddress1 != null) {
addresslineone.setText(stAddress1);
// addresslineone.getText().replaceAll("null", "");
}
}
// if(place.getLatLng()!=null)
// {
// String latitude = "" + place.getLatLng().latitude;
// String longitude = "" + place.getLatLng().longitude;
// }
Log.e(TAG, "getAddressDetails: " + stringBuilder.toString());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Log.e(TAG, "onActivityResult: " + requestCode);
if (requestCode == 100) {
try {
if (data.getExtras() != null && data.getExtras().getSerializable("data") != null) {
LocationModel locationModel = (LocationModel) data.getExtras().getSerializable("data");
if (locationModel != null) {
// addresslineone.setText(locationModel.getLocationname());
getAddressDetails(locationModel.getAddress());
//latitude = String.valueOf(locationModel.getLatitude());
//longitude = String.valueOf(locationModel.getLongitude());
}
}
} catch (Exception e) {
}
}
}
}
Here is the code of Location Activity
Map
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.planfisheye.fisheye.BaseActivity;
import com.planfisheye.fisheye.R;
import com.planfisheye.fisheye.adapters.NearByGetLocationParser;
import com.planfisheye.fisheye.adapters.PlacesAutoCompleteAdapter;
import com.planfisheye.fisheye.adapters.PlacesModel;
import com.planfisheye.fisheye.helper.CustomDialog;
import com.planfisheye.fisheye.models.LocationModel;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by venkateshmurthy on 24/12/16.
*/
public class LocationActivity extends BaseActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, PlaceSelectionListener {
private static final String TAG = "LocationActivity";
MapView mapView;
GoogleMap map;
private GoogleApiClient mClient;
#BindView(R.id.autocompletesearch)
AutoCompleteTextView autoSearch;
private static final int REQUEST_SELECT_PLACE = 1000;
private LatLng latlangObj;
private String address;
private String locationname;
private CustomDialog mCustomDialog;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#OnClick(R.id.doneclick)
public void doneClick() {
if(latlangObj!=null) {
LocationModel locationModel=new LocationModel();
locationModel.setLatitude(latlangObj.latitude);
locationModel.setLongitude(latlangObj.longitude);
locationModel.setLocationname(locationname);
locationModel.setAddress(address);
Intent intent=new Intent();
intent.putExtra("data",locationModel);
setResult(13, intent);
finish();
}else {
finish();
}
overridePendingTransition(R.anim.enter, R.anim.exit);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_select);
ButterKnife.bind(this);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mCustomDialog=new CustomDialog(this);
// try {
// Intent intent = new PlaceAutocomplete.IntentBuilder
// (PlaceAutocomplete.MODE_OVERLAY)
// // .setBoundsBias(BOUNDS_MOUNTAIN_VIEW)
// .build(this);
// startActivityForResult(intent, REQUEST_SELECT_PLACE);
// } catch (GooglePlayServicesRepairableException |
// GooglePlayServicesNotAvailableException e) {
// e.printStackTrace();
// }
// PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
// getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// autocompleteFragment.setOnPlaceSelectedListener(this);
// autocompleteFragment.setHint("Search a Location");
mClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.addApi(Places.PLACE_DETECTION_API)
.build();
mClient.connect();
autoSearch.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.autocomplete_list_item));
autoSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
autoSearch.setText("");
}
});
autoSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//CommonUtils.hideKeyBoard(getActivity());
mCustomDialog.show();
final PlacesModel hm = (PlacesModel) autoSearch.getAdapter().getItem(position);
Log.e("place_id", "" + hm.getPlaceid());
// placetext.setText("" + hm.getDescription());
//AIzaSyA9_CVo9IETbjjqqBHC1eEYesVsaMPflIk
String[] codeInfo =
TextUtils.split(hm.getDescription(), ",");
// getLatLng(hm.getPlaceid());
Places.GeoDataApi.getPlaceById(mClient, hm.getPlaceid())
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
mCustomDialog.dismiss();
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
//getAddressDetails(myPlace);
Log.e("name", "Place found: " + myPlace.getName() + "\t" + myPlace.getAddress()+"\t"+myPlace.getLatLng());
if(myPlace.getAddress()!=null) {
address = myPlace.getAddress().toString();
}
latlangObj= myPlace.getLatLng();
locationname=hm.getDescription();
Log.e("latitude:", "" + latlangObj.latitude);
Log.e("longitude:", "" + latlangObj.longitude);
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(latlangObj.latitude, latlangObj.longitude))
.title("" + hm.getDescription()));
marker.showInfoWindow();
marker.setDraggable(true);
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
Log.e("place", "Place not found");
}
places.release();
}
});
autoSearch.setText(""+hm.getDescription());
autoSearch.setSelection(autoSearch.getText().length());
}
});
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this);
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mClient.disconnect();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.map = googleMap;
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
private class NearbyLatlngTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
GetLatLngTask parserTask = new GetLatLngTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class GetLatLngTask extends AsyncTask<String, Integer, List<HashMap<String, Double>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, Double>> doInBackground(String... jsonData) {
List<HashMap<String, Double>> places = null;
NearByGetLocationParser nearPlaceJsonParser = new NearByGetLocationParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = nearPlaceJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, Double>> list) {
// Clears all the existing markers
// mGoogleMap.clear();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, Double> hmPlace = list.get(i);
// Getting latitude of the place
double lat = hmPlace.get("lat");
// Getting longitude of the place
double lng = hmPlace.get("lng");
Log.e("lat", "lat" + lat);
Log.e("long", "long" + lng);
Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
//Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private void getLatLng(String placeID) {
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID);
sb.append("&key=AIzaSyBiV3T00af_2jM0Vinlcws2Gc6K7ktVp38");
NearbyLatlngTask placesTask = new NearbyLatlngTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Check this,
map.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
addMarker();
}
});
add this is addMarker method,
private void addMarker() {
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
googleMap.addMarker(marker);
}

populating json data inside Googlemap

I made a lot of research on this topic but couldn't find an appropriate solution.
I simply have an api which include school name and its latitude,longitude.
[
{
"id":1,
"name":"Little Angels Higher Secondary School",
"latitude":27.6514,
"longitude":85.3359
},
{
"id":6,
"name":"Baltimore Secondary School",
"latitude":27.6514,
"longitude":85.3359
}
]
I parsed this api data.Using GPStracker class I successfully included a marker on google map at my current location.Now I want to add a marker to all the school location in that google map so that I can know the nearest school to me once I open the google map.This is all what I did how ever it shows null pointer exception.
package com.example.user.educationhunt.fragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.user.educationhunt.R;
import com.example.user.educationhunt.SchoolDetails;
import com.example.user.educationhunt.adapter.CustomListAdapter;
import com.example.user.educationhunt.pojos.AppController;
import com.example.user.educationhunt.pojos.FeeClass;
import com.example.user.educationhunt.pojos.GpsLocation;
import com.example.user.educationhunt.pojos.MySchool;
import com.example.user.educationhunt.pojos.OurSchool;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NearMe extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
GpsLocation gpsLocation;
double longitude, latitude;
private ProgressDialog pDialog;
private RadioButton radioSexButton;
ArrayList al = new ArrayList();
MySchool mySchool;
Marker place;
LatLng current_location ;
private static final String TAG = NearMe.class.getSimpleName();
private static final String url = "http://www.myeducationhunt.com/api/v1/schools";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_near_me, container, false);
radioSexButton = (RadioButton) v.findViewById(R.id.radioSchool);
if (isConnected()) {
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
gpsLocation = new GpsLocation(getContext());
if (gpsLocation.canGetLocation()) {
longitude = gpsLocation.getLongitude();
latitude = gpsLocation.getLatitude();
Toast.makeText(getContext(), "latitude:" + latitude + "Longitude:" + longitude, Toast.LENGTH_LONG).show();
}
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Loading…");
pDialog.show();
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
mySchool = new MySchool();
mySchool.setId(""+obj.getInt("id"));
mySchool.setName(""+obj.getString("name"));
mySchool.setLatitude(Double.parseDouble(""+obj.getDouble("latitude")));
mySchool.setLongitude(Double.parseDouble(""+obj.getDouble("longitude")));
al.add(mySchool);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng latlng = new LatLng(mySchool.getLatitude(), mySchool.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).title(mySchool.getName()));
CameraPosition cameraPosition1 = new CameraPosition.Builder().target(latlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition1));
}
});
} else {
Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
}
return v;
}
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
Is there any one to help me?Please Help.Thanks in advance
This is MySchool class
package com.example.user.educationhunt.pojos;
/**
* Created by user on 12/28/2016.
*/
public class MySchool {
String id;
String name;
double latitude;
double longitude;
public String getId() {
return id;
}
public String getName() {
return name;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public void setId(String id) {
this.id = id;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setName(String name) {
this.name = name;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
This is my error log
FATAL EXCEPTION: main
Process: com.example.user.educationhunt, PID: 20472
java.lang.NullPointerException: Attempt to invoke virtual method 'double com.example.user.educationhunt.pojos.MySchool.getLatitude()' on a null object reference
at com.example.user.educationhunt.fragment.NearMe$3.onMapReady(NearMe.java:159)
at com.google.android.gms.maps.MapView$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:387)
at zu.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.t$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
12-28 10:06:05.046 20472-21276/com.example.user.educationhunt I/qtaguid: Untagging socket 81
Your school marker should run after google complete initialized. Below are the code sample.
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
drawSchoolMarker();
}
});
Create new method in the class
private void drawSchoolMarker(){
JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MySchool school = new MySchool();
school.setId(""+obj.getInt("id"));
school.setName(""+obj.getString("name"));
school.setLatitude(Double.parseDouble(""+obj.getDouble("latitude")));
school.setLongitude(Double.parseDouble(""+obj.getDouble("longitude")));
al.add(school);
} catch (JSONException e) {
e.printStackTrace();
}
}
//iterate from arraylist
for(MySchool school : al){
LatLng latlng = new LatLng(school.getLatitude(), school.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latlng).title(school.getName()));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(schoolRequest);
}
I didn't test the code but it should work.
After reading all school locations do some thing like by using your Array List
Marker place;
LatLng current_location ;
for(int i = 0; i < al.size(); i++){
current_location = new LatLng(Double.parseDouble(al.get(i).getLatitude()),Double.parseDouble(al.get(i).getLongitude()));
place= map.addMarker(new MarkerOptions().position(current_location).title("school name here"));
}
You should get NullPointerException in the line:
LatLng latlng = new LatLng(ourSchool.latitude, ourSchool.longitude);
because ourSchool is pointing to Null. You have added all the ourSchool objects in the ArrayList "al" like : al.add(ourSchool)
now try to iterate from the ArrayList "al" after adding the data in the ArrayList.
Also your below code is running before the getting response from the url and your "ourSchool" not initialise till that time.
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LatLng schoollatlng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(schoollatlng).title("MyLocation"));
CameraPosition cameraPosition = new CameraPosition.Builder().target(schoollatlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LatLng latlng = new LatLng(ourSchool.latitude, ourSchool.longitude);
googleMap.addMarker(new MarkerOptions().position(latlng).title(ourSchool.schoolName));
CameraPosition cameraPosition1 = new CameraPosition.Builder().target(latlng).zoom(10).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition1));
}
});
OurSchool class:
class OurSchool{
String id;
String name;
double latitude;
double longitude;
public void setId(String id){
this.id=id;
}
public String getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setLatitude(double latitude){
this.latitute=latitude;
}
public double getLatitude(){
return latitude;
}
public void setLongitude(String longitude){
this.longitude=longitude;
}
public double getLongitude(){
return longitude;
}
}
then set value in OurSchool class object like:
ourSchool.setId(""+obj.getInt("id"));
in place of
ourSchool.schoolId = obj.getInt("id");
same way set values for other also

Refresh Android Google maps v2 after adding markers

I have an app which takes android map marker locations (lat/long) from mysql database. And user from my app can add markers too. The problem is that when user adds location of the new marker it does not appear on map. However the lat and long values appear in mysql database and if i reinstall the app it will show added location. Issue here seems to be that i have to refresh the map and i don't know how to do it in google maps v2. I found some answers that i should clear all markers and then load them again like this:
googleMap.clear();
But sadly it did not work. I found that in version one there was this method
map.invalidate();
Sadly in Google Maps v2 there is no such method. Has anyone have any idea how to refresh Google Maps v2 when i reactivate activity or if i press refresh button, any suggestion will be appreciated.
Update
Code:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.wunderlist.slidinglayer.SlidingLayer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import app.AppController;
import util.Content;
public class MainActivity extends Activity {
private GoogleMap googleMap;
// json object response url
private String urlJsonObj = "alsodontneedthis.json";
// json array response url
private String urlJsonArry = "dontneedthis";
private static String TAG = MainActivity.class.getSimpleName();
// Progress dialog
private ProgressDialog pDialog;
Content content = new Content();
public static String valueEntered;
// temporary string to show the parsed response
private String jsonResponse;
private SlidingLayer mSlidingLayer;
private TextView swipeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings();
googleMap.getUiSettings().setZoomControlsEnabled(true);
bindViews();
initState();
mSlidingLayer.bringToFront();
redirect();
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
mSlidingLayer.openLayer(true);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
/**
* View binding
*/
private void bindViews() {
mSlidingLayer = (SlidingLayer) findViewById(R.id.slidingLayer1);
// swipeText = (TextView) findViewById(R.id.swipeText);
}
/**
* Initializes the origin state of the layer
*/
private void initState() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setupSlidingLayerPosition(prefs.getString("layer_location", "right"));
setupShadow(prefs.getBoolean("layer_has_shadow", false));
setupLayerOffset(prefs.getBoolean("layer_has_offset", false));
setupPreviewMode(prefs.getBoolean("preview_mode_enabled", false));
}
private void setupSlidingLayerPosition(String layerPosition) {
LayoutParams rlp = (LayoutParams) mSlidingLayer.getLayoutParams();
int textResource;
Drawable d;
// if (layerPosition.equals("right")) {
textResource = R.string.swipe_right_label;
d = getResources().getDrawable(R.drawable.container_rocket_right);
mSlidingLayer.setStickTo(SlidingLayer.STICK_TO_RIGHT);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
// swipeText.setCompoundDrawables(null, d, null, null);
// swipeText.setText(getResources().getString(textResource));
mSlidingLayer.setLayoutParams(rlp);
}
private void setupShadow(boolean enabled) {
if (enabled) {
mSlidingLayer.setShadowSizeRes(R.dimen.shadow_size);
mSlidingLayer.setShadowDrawable(R.drawable.sidebar_shadow);
} else {
mSlidingLayer.setShadowSize(0);
mSlidingLayer.setShadowDrawable(null);
}
}
private void setupLayerOffset(boolean enabled) {
int offsetDistance = enabled ? getResources().getDimensionPixelOffset(R.dimen.offset_distance) : 0;
mSlidingLayer.setOffsetDistance(offsetDistance);
}
private void setupPreviewMode(boolean enabled) {
int previewOffset = enabled ? getResources().getDimensionPixelOffset(R.dimen.preview_offset_distance) : -1;
mSlidingLayer.setPreviewOffsetDistance(previewOffset);
}
public void buttonClicked(View v) {
switch (v.getId()) {
// case R.id.buttonOpen:
// mSlidingLayer.openLayer(true);
// break;
case R.id.buttonClose:
mSlidingLayer.closeLayer(true);
break;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mSlidingLayer.isOpened()) {
mSlidingLayer.closeLayer(true);
return true;
}
default:
return super.onKeyDown(keyCode, event);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addNewEvent:
Intent intent = new Intent(this, AddEvent.class);
startActivity(intent);
;
}
return true;
}
private void redirect() {
//showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
Content content = new Content();
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String name = person.getString("nosaukums");
String email = person.getString("nosaukums");
String relation = person.getString("nosaukums");
Double lat=person.getDouble("latCo");
Double lng=person.getDouble("longCo");
content.setName(name);
content.setPopulation(email);
content.setlat(lat);
content.setlng(lng);
content.setRelation(relation);
System.out.println("name="+content.getName()+content.getlat());
LatLng lt = new LatLng(content.getlat(), content.getlng());
content.setLatlng(lt);
//valueEntered=lt.toString();
System.out.println("address="+content.getLatlng());
/*String home = latlng.getLong("home");
String mobile = phone.getString("mobile");*/
System.out.println("relation="+content.getRelation());
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Population: " + email + "\n\n";
jsonResponse += "Latitude: " + lat + "\n\n";
jsonResponse += "Longitude: " + lng + "\n\n\n";
jsonResponse += "Relation" + relation +"\n\n\n";
if(content.getRelation().equals("son"))
{
googleMap.addMarker(new MarkerOptions()
.position(lt)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_son))
.snippet(email)
.title(content.getName())).showInfoWindow();
}
else
{
googleMap.addMarker(new MarkerOptions()
.position(lt)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_daughter))
.title(content.getName())).showInfoWindow();
}
CameraPosition cameraPosition = new CameraPosition.Builder().target(lt).zoom(15.0f).build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
googleMap.moveCamera(cameraUpdate);
}
//txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
//hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
//hidepDialog();
}
});
// Adding request to request queue
//AppController.getInstance() == null;
AppController.getInstance().addToRequestQueue(req);
}
}
Since googleMap.appMarker() seems not to get called, you propaply catch an Exception when calling content.getRelation().equals("son").

Android map: How to process the order between get current location and calculate the distance between two locations

I'm using the Baidu map SDK to get my current location, and success get the latitude and longitude.
I stored the store location(latitude and longitude) in server side[this is the shop location, i will calculate the distance between my current location and shop location]
What i need to do is get my current latitude and longitude, store in two double type variables, and then read every shop's information from server-side, and calculate the distance, after that, show the distance in order in a TextView
in this code, i didn't calculate the distance, just shows the latitude in the TextView to test whether there is a problem here.
here is my code:
package com.ecnu.vendingmachine.personal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.ecnu.vendingmachine.MyApplication;
import com.ecnu.vendingmachine.R;
import com.ecnu.vendingmachine.widgets.JSONParser;
public class CouponOrderActivity extends ListActivity {
private static final String TAG = "CouponOrderActivity";
private static final String TAG_SUCCESS = "success";
private ListView listView;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
JSONArray vendingmachine = null;
ArrayList<HashMap<String, String>> vendinglist;
protected Context mContext;
public LocationClient mLocationClient = null;
public BDLocationListener myListener = new MyLocationListener();
private double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vending_select);
mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
mLocationClient.setAccessKey("BpGYSXjAPeGID253M5UpDw0K");
mLocationClient.registerLocationListener(myListener); // 注册监听函数
setLocationOption();
mLocationClient.start();// 开始定位
Log.i(TAG, "latitude -> " + String.valueOf(latitude));
Log.i(TAG, "longitude -> " + String.valueOf(longitude));
vendinglist = new ArrayList<HashMap<String, String>>();
mContext = getApplicationContext();
listView = getListView();
new get_all_vendingmachine().execute();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mLocationClient.stop();// 停止定位
}
/**
* 设置相关参数
*/
private void setLocationOption() {
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);
option.setIsNeedAddress(true); // 返回的定位结果包含地址信息
option.setAddrType("all"); // 返回的定位结果包含地址信息
option.setCoorType("bd09ll"); // 返回的定位结果是百度经纬度,默认值gcj02
option.setScanSpan(5000); // 设置发起定位请求的间隔时间为5000ms
option.disableCache(true); // 禁止启用缓存定位
option.setPoiNumber(5); // 最多返回POI个数
option.setPoiDistance(1000); // poi查询距离
option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
mLocationClient.setLocOption(option);
}
public class MyLocationListener implements BDLocationListener {
#Override
public void onReceiveLocation(BDLocation location) {
if (location == null)
return;
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i(TAG,
"latitude in onReceiveLocation-> "
+ String.valueOf(latitude));
Log.i(TAG,
"longitude in onReceiveLocation-> "
+ String.valueOf(longitude));
}
public void onReceivePoi(BDLocation poiLocation) {
// 将在下个版本中去除poi功能
if (poiLocation == null) {
return;
}
}
}
class get_all_vendingmachine extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CouponOrderActivity.this);
pDialog.setMessage("loading vending machine..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// url to get all products list
MyApplication myApplication = (MyApplication) getApplication();
String url_all_vendingmachine = myApplication.getIP()
+ "vendingmachine/vending_distance.php";
JSONObject json = jsonParser.makeHttpRequest(
url_all_vendingmachine, "GET", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Getting Array of vendingmachine
vendingmachine = json.getJSONArray("vendings");
vendinglist.clear();
// looping through All vendingmachine
for (int i = 0; i < vendingmachine.length(); i++) {
JSONObject c = vendingmachine.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("VMid");
String name = c.getString("Name");
String address = c.getString("Address");
Log.i(TAG,
"latitude in display -> "
+ String.valueOf(latitude));
Log.i(TAG,
"longitude in display-> "
+ String.valueOf(longitude));
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("VMid", id);
map.put("Name", name);
map.put("Address", address);
map.put("distance", String.valueOf(latitude));
// adding HashList to ArrayList
vendinglist.add(map);
}
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
// updating listview
// HashMap<String, String>中的key
String[] from = { "Name", "Address", "VMid", "distance" };
// list_item.xml中对应的控件ID
int[] to = { R.id.vending_name, R.id.vending_address,
R.id.vending_id, R.id.distanceText };
SimpleAdapter adapter = new SimpleAdapter(mContext,
vendinglist, R.layout.vending_list, from, to);
listView.setAdapter(adapter);
}
});
}
}
}
according to the logcat,
in line 81, 82, the logcat is 0
Log.i(TAG, "latitude -> " + String.valueOf(latitude));
Log.i(TAG, "longitude -> " + String.valueOf(longitude));
in line 125,126, the logcat is my current location, is what i want
Log.i(TAG, "latitude in onReceiveLocation-> " + String.valueOf(latitude));
Log.i(TAG, "longitude in onReceiveLocation-> " + String.valueOf(longitude));
in line 179, 180, the logcat is 0
Log.i(TAG, "latitude in display -> " + String.valueOf(latitude));
Log.i(TAG, "longitude in display-> " + String.valueOf(longitude));
I think it's the problem about execute order, once the onCreate method be called, before getting my current location, the
new get_all_vendingmachine().execute();
is running. so it just use the
latitude, longitude = 0
to calculate the distance.
what should i do???
The AsyncTask is being run before you get your location. You should move your async task to your onConnected of your location client so you know you can get a location from now on
Baidu documentation for distance calculation can be found at
http://lbsyun.baidu.com/index.php?title=androidsdk/guide/tool/calculation
I also use auto translate in Chrome when opening the Baidu documentation.
//Calculate the straight line distance between p1, p2, unit: meters
DistanceUtil . getDistance ( p1 , p2 );

Doing multiple overlay dynamically in Android and parsed XML latitude and longitude

I am writing an Android application that essentially parses XML data using Fwix's API. The parsing part is working fine. Here's my class, Parser:
package com.magadistudio_student_connect_2011.com;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import android.util.Xml;
public class Parser {
//Feed Parsing Method
public ArrayList<Bakery> parse(String url) {
//Array of Episode Objects
ArrayList<Bakery> bakeries = null;
try {
//Encode the URL into a URL Object
URL bakery_feed_url = new URL(url);
//Open a Connection to the feed
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(bakery_feed_url.openConnection().getInputStream(), null);
}
finally {
}
int event_type = parser.getEventType();
Bakery current_bakery = null;
boolean done = false;
//Parse the feed, start reading throughout the feed from top to bottom
while (event_type != XmlResourceParser.END_DOCUMENT && !done) {
String tag_name = null;
switch (event_type) {
//Found the start of the feed
case XmlResourceParser.START_DOCUMENT:
bakeries = new ArrayList<Bakery>();
break;
//Found a start tag
case XmlResourceParser.START_TAG:
//apply the data to our Episode object based on the tag name
tag_name = parser.getName();
if (tag_name.equalsIgnoreCase("place")) {
current_bakery = new Bakery();
}
else if(current_bakery != null) {
if (tag_name.equalsIgnoreCase("phone_number")){
current_bakery.setPhone(parser.nextText());
}else if(tag_name.equalsIgnoreCase("city")){
current_bakery.setCity(parser.nextText());
}else if(tag_name.equalsIgnoreCase("province")){
current_bakery.setState(parser.nextText());
}else if(tag_name.equalsIgnoreCase("address")){
current_bakery.setAddress(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lat")){
current_bakery.setLatitude(parser.nextText());
//lat = Integer.parseInt(parser.getAttributeValue(null,"lat"));
}else if(tag_name.equalsIgnoreCase("postal_code")){
current_bakery.setZip(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lng")){
current_bakery.setLongitude(parser.nextText());
//lon = Integer.parseInt(parser.getAttributeValue(null,"lng"));
}else if(tag_name.equalsIgnoreCase("name")){
current_bakery.setPlace_name(parser.nextText());
}
}
break;
//An end tag has been reached
case XmlResourceParser.END_TAG:
tag_name = parser.getName();
//End of an Episode Item
if (tag_name.equalsIgnoreCase("place") && current_bakery != null) {
bakeries.add(current_bakery);
//Reached the end of all bakeries, no more data to collect
}
else if (tag_name.equalsIgnoreCase("places")){
done = true;
}
break;
}
event_type = parser.next();
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
//Return the Episode Array
return bakeries;
}
}
And here is my overlay class, Overlay:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class StudentItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public StudentItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public StudentItemizedOverlay(Drawable defaultMarker, Context context){
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
// Toast.makeText(StudentItemizedOverlay.this, "Hello", Toast.LENGTH_LONG).show();
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
And here is class BakeryActivity:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class BakeryActivity extends Activity implements OnItemClickListener {
//RSS Feed URL
private final String CGR_FEED_URL = "http://www.codinggreenrobots.com/episodes/rss.xml";
//xml new feed
private final String SCHOOLS_URL = "http://www.fizber.com/xml_data/xml_school_data.xml?state=wa&city=spokane";
private final String BAKERY_RSS = "apigoeshere";
//XML Widgets
private ListView listview_bakery;
private ProgressBar progress_bar;
//Arrays of Episode Data
private ArrayList<String> bakery_name;
private ArrayList<String> bakery_address;
private ArrayList<String> bakery_phone;
private ArrayList<String> bakery_latitude;
private ArrayList<String> bakery_longitude;
private ArrayList<String> bakery_state;
private ArrayList<String> bakery_zip;
private ArrayList<String> bakery_city;
/*private ArrayList<String> school_latitude;
private ArrayList<String> school_longitude;
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bakery_view);
//XML Widgets by ID
listview_bakery = (ListView) findViewById(R.id.listview_bakeries);
listview_bakery.setOnItemClickListener(this);
/* ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.drawable.colors));
listview_bakery.setDivider(sage);
listview_bakery.setDividerHeight(1);*/
progress_bar = (ProgressBar) findViewById(R.id.progress_bar_bakery);
//Make Progress Bar Invisible
progress_bar.setVisibility(ProgressBar.INVISIBLE);
//Initialize Arrays
bakery_name = new ArrayList<String>();
bakery_address = new ArrayList<String>();
bakery_phone = new ArrayList<String>();
bakery_latitude = new ArrayList<String>();
bakery_longitude = new ArrayList<String>();
bakery_state = new ArrayList<String>();
bakery_zip = new ArrayList<String>();
bakery_city = new ArrayList<String>();
//school_latitude = new ArrayList<String>();
//school_longitude = new ArrayList<String>();
downloadBakeries(BAKERY_RSS);
}
private void downloadBakeries(String Url) {
//Make Progress Bar Visible While Downloading Feed
progress_bar.setVisibility(ProgressBar.VISIBLE);
Log.d("CGRParser", "Downloading Feed");
//Start an ASync Thread to take care of Downloading Feed
new DownloadBakeries().execute(Url);
}
private class DownloadBakeries extends AsyncTask<String, Integer, ArrayList<Bakery>> {
#Override
protected ArrayList<Bakery> doInBackground(String... url) {
//Download and Parse Feed
Parser parser = new Parser();
ArrayList<Bakery> bakeries = new ArrayList<Bakery>();
bakeries = parser.parse(url[0]);
return bakeries;
}
#Override
protected void onPostExecute(ArrayList<Bakery> result) {
//Feed has been Downloaded and Parsed, Display Data to User
Log.d("CGRParser", "Feed Download Complete");
//Toast.makeText(BakeryActivity.this, "onPost", Toast.LENGTH_SHORT).show();
displayBakeries(result);
}
}
private void displayBakeries(ArrayList<Bakery> bakeries) {
//Create String Arrays to seperate titles and dates
Log.d("CGRParser", "Displaying Episode Titles To User");
ArrayList<String> bakery_name = new ArrayList<String>();
ArrayList<String> bakery_address = new ArrayList<String>();
ArrayList<String> bakery_phone = new ArrayList<String>();
ArrayList<String> bakery_latitude = new ArrayList<String>();
ArrayList<String> bakery_longitude = new ArrayList<String>();
ArrayList<String> bakery_state = new ArrayList<String>();
ArrayList<String> bakery_zip = new ArrayList<String>();
ArrayList<String> bakery_city = new ArrayList<String>();
//ArrayList<String> school_longitude = new ArrayList<String>();
for (Bakery bakery : bakeries) {
//Log.d("CGRParser", "Episode Title: " + episode.getTitle());
bakery_phone.add(bakery.getPhone());
bakery_name.add(bakery.getPlace_name());
bakery_address.add(bakery.getAddress());
bakery_latitude.add(bakery.getLatitude());
bakery_longitude.add(bakery.getLongitude());
bakery_state.add(bakery.getState());
bakery_zip.add(bakery.getZip());
bakery_city.add(bakery.getCity());
//school_longitude.add(episode.getLongitude());
}
//Toast.makeText(BakeryActivity.this, "DisplayBakeries", Toast.LENGTH_SHORT).show();
this.bakery_phone = bakery_phone;
this.bakery_name = bakery_name;
this.bakery_address = bakery_address;
this.bakery_latitude = bakery_latitude;
this.bakery_longitude = bakery_longitude;
this.bakery_state = bakery_state;
this.bakery_zip = bakery_zip;
this.bakery_city = bakery_city;
//int myNum = 0; try { myNum = Integer.parseInt(bakery_latitude.getText().toString()); } catch(NumberFormatException nfe) { System.out.println("Could not parse " + nfe); }
//Create a ListAdapter to Display the Titles in the ListView
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.bakery_row, R.id.title, bakery_name);
listview_bakery.setAdapter(adapter);
//Set Progress Bar Invisible since we are done with it
progress_bar.setVisibility(ProgressBar.INVISIBLE);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(BakeryActivity.this, Map.class));
//Display the Title and Date to the user when they click on an episode
Toast.makeText(this, "Name:" + bakery_name.get(position) + "\nphone: " + bakery_phone.get(position)+
"\nState: "+ bakery_state.get(position) + "\nAddress: "+ bakery_address.get(position)
+ "\nZip: "+ bakery_zip.get(position)+ "\nLat: " +bakery_latitude.get(position)+ "\nlon: "+ bakery_longitude.get(position), Toast.LENGTH_LONG).show();
}
}
I am able to do the XML parsing work fine, but THE PROBLEM is I can't figure out how to get the "lat" and "lng" that I have parsed (and put then into an ArrayList of Strings) and convert them into integers so I can show markers of the respective latitude and longitude location on the map.
OK, so Android's Google Maps native location API uses integers with 6 digits following the decimal point. Therefore, you want to remove the "." from the strings of integers you parsed out. Then, simply do a parseInt to attain the coordinates. With that, drop them into GeoPoints and add them to the overlay. It should be no problem.
Unless I'm missing something here, which is possible.

Categories

Resources