create itinary google maps android - java

After using gps for geolocalization, i want to create an line to show the itinary between two points. I know i need to use the polyline but after the JSON parsing, I don't know how to use the polyline options and I don't know how to use the part of Json named "steps". For the Http conection, i use the Volley Library. This my code:
public void geoLocate(View view){
String start = start_address.getText().toString();
String destination = destination_address.getText().toString();
Geocoder gc = new Geocoder(getActivity());
try {
List<android.location.Address> list = gc.getFromLocationName(start,1);
final Address adress1 = list.get(0);
String start_adress = adress1.getLocality();
double lat_start = adress1.getLatitude();
double lng_start = adress1.getLongitude();
list = gc.getFromLocationName(destination,1);
Address adress2 = list.get(0);
String destination_adress = adress2.getLocality();
double lat_destination = adress2.getLatitude();
double lng_destination = adress2.getLongitude();
if (start_marker != null || destination_marker != null){
start_marker.remove();
destination_marker.remove();
}
options_start = new MarkerOptions()
.title(start_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(new LatLng(lat_start, lng_start));
start_marker = mGoogleMap.addMarker(options_start);
options_destination = new MarkerOptions()
.title(destination_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(new LatLng(lat_destination, lng_destination));
destination_marker = mGoogleMap.addMarker(options_destination);
reservation.setClickable(true);
reservation.setEnabled(true);
reservation.setTextColor(getResources().getColor(R.color.white));
reservation.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
if(reservation.isClickable()) {
reservation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(start_marker.getPosition());
builder.include(destination_marker.getPosition());
LatLngBounds bounds = builder.build();
final StringBuilder url = new StringBuilder("http://maps.googleapis.com/maps/api/directions/json?sensor=false&language=fr");
url.append("&origin=");
url.append(start.replace(" ", "+"));
url.append("&destination=");
url.append(destination.replace(" ", "+"));
final Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String status = jsonResponse.getString("status");
if (status.equals("OK")){
JSONArray parentArray = jsonResponse.getJSONArray("routes");
JSONObject routes = parentArray.getJSONObject(0);
if(routes != null){
JSONArray legsArray = routes.getJSONArray("legs");
JSONObject legsObject = legsArray.getJSONObject(0);
if (legsObject != null){
JSONObject distance = legsObject.getJSONObject("distance");
if (distance != null){
String distanceText = distance.getString("text");
distance_matrix.append(" "+distanceText);
}
JSONArray stepsArray = legsObject.getJSONArray("steps");
JSONObject stepsObject = stepsArray.getJSONObject(0);
if (stepsObject != null){
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ItineraireRequest itineraireRequest = new ItineraireRequest(url.toString(), responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(itineraireRequest);
int padding = 125; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mGoogleMap.animateCamera(cu);
} catch (IOException e) {
e.printStackTrace();
}
}
Can you give a solution adapted to my code to make that, please?

I think this could help, the "getDocument()" do all the work
#Override
public void onMapReady(GoogleMap googleMap) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(formatAddress(ORIGIN_TEXT, formatAddress(DESTINATION_TEXT, MODE, getApplicationContext());
if (doc != null) {
int duration = md.getDurationValue(doc);
if (duration > 0) {
try {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(9).color(R.color.splash_blue).geodesic(true);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
AccessLocationActivity.this.mMap.addPolyline(rectLine);
} catch (Exception e) {
e.printStackTrace();
}
}
UPDATED
try this
public void geoLocate(View view){
String start = start_address.getText().toString();
String destination = destination_address.getText().toString();
Geocoder gc = new Geocoder(getActivity());
try {
List<android.location.Address> list = gc.getFromLocationName(start,1);
final Address adress1 = list.get(0);
String start_adress = adress1.getLocality();
double lat_start = adress1.getLatitude();
double lng_start = adress1.getLongitude();
list = gc.getFromLocationName(destination,1);
Address adress2 = list.get(0);
String destination_adress = adress2.getLocality();
double lat_destination = adress2.getLatitude();
double lng_destination = adress2.getLongitude();
if (start_marker != null || destination_marker != null){
start_marker.remove();
destination_marker.remove();
}
options_start = new MarkerOptions()
.title(start_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(new LatLng(lat_start, lng_start));
start_marker = mGoogleMap.addMarker(options_start);
options_destination = new MarkerOptions()
.title(destination_adress)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(new LatLng(lat_destination, lng_destination));
destination_marker = mGoogleMap.addMarker(options_destination);
reservation.setClickable(true);
reservation.setEnabled(true);
reservation.setTextColor(getResources().getColor(R.color.white));
reservation.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
if(reservation.isClickable()) {
reservation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(start_marker.getPosition());
builder.include(destination_marker.getPosition());
LatLngBounds bounds = builder.build();
final StringBuilder url = new StringBuilder("http://maps.googleapis.com/maps/api/directions/json?sensor=false&language=fr");
url.append("&origin=");
url.append(start.replace(" ", "+"));
url.append("&destination=");
url.append(destination.replace(" ", "+"));
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(formatAddress(start), formatAddress(destination), GMapV2Direction.MODE_DRIVING, getApplicationContext());
if (doc != null) {
int duration = md.getDurationValue(doc);
if (duration > 0) {
try {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(9).color(R.color.colorPrimary).geodesic(true);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
mGoogleMap.addPolyline(rectLine);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}

This is a great wrapper on top of the Google DirectionsAPI if you are willing to give it a shot.
More detailed explanation here.

Related

how to get url with different ids in android (async task)

EDIT: Found the solution to my problem.
The json string output returned the wrong url for my local images.
i am barely new to android and struggle with asyncTask.
What i want is to get the corresponding image to a marker on a map.
every entry on this map has its own image which has to be loaded from server via json.
the image load works fine but i dont get the right workflow to get the image i need for one entry.
by now i have one solution to load an async task in a for-loop, but this cant be the right way because the app refuses to go on after 43 tasks and stops with
"ECONNECTION TIMEOUT"
so how can get the asynctask out of the loop?
hope anyone can help? thank you!
here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
public class MapImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
String url, userId, contentId, title;
LatLng location;
BufferedReader reader = null;
public MapImageLoadTask(String url, String userId, String contentId, String title, LatLng location) {
this.url = url;
this.userId = userId;
this.contentId = contentId;
this.title = title;
this.location = location;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(title).position(location).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
hashMap.put(m, contentId);
}
}
}
Your problem maybe AsyncTask limitations. In android.os.AsyncTask.java you will see core size and blockingqueue size(128), should use counter for asynctask and debug it(Problem is, lots of async tasks or other).
AsyncTask.java
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
...}
Change Your Code Use Buffer(RequestData) And Use Only One Async Task. Update Market instance every publishProgress in onProgressUpdate
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
List<RequestData> datas = new ArrayList<RequestData>();
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
RequestData data = new RequestData();
data.url = "http://192.168.63.35:1234/rest_app_users/getImage/";
data.userId = userId;
data.contentId = contentId;
data.contentTitle = contentTitle;
data.latlng = latlng;
datas.add(data);
//new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
new MapImageLoadTask(datas).execute();
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
static class RequestData{
public String url;
public String userId;
public String contentId;
public String contentTitle;
public LatLng latLng;
public Bitmap bmp;
}
public class MapImageLoadTask extends AsyncTask<Void, RequestData, Void> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
BufferedReader reader = null;
List<RequestData> dataSet;
public MapImageLoadTask(List<RequestData> dataSet) {
this.dataSet = dataSet;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
for(RequestData item : dataSet){
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//
item.bmp = bmp;
publishProgress(item);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPublishProgress(RequestData item){
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(item.title).position(item.location).icon(BitmapDescriptorFactory.fromBitmap(item.bmp)));
hashMap.put(m, contentId);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}

draw path in Google Map fragment, and display it, and calculate the distance

I am a newbie in android and here is my code, the problem is this code is not able to draw the path on the map.
This my main activity
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.w3c.dom.Document;
import java.util.ArrayList;
public class servicing extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
protected GoogleMap mMap;
String lang = "english";
String test = "test";
protected LocationManager locationManager;
Route route = new Route();
LatLng latLng1 = new LatLng(26.903291,75.792482);
LatLng latLng2 = new LatLng(26.907708,75.806044);
ArrayList<LatLng> points = new ArrayList<>(2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_servicing);
//GMapV2Direction md = new GMapV2Direction();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
/*Document doc = md.getDocument(latLng1, latLng2,
GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);*/
points.add(latLng1);
points.add(latLng2);
route.drawRoute(mMap, this, points, true, lang, false);
Toast.makeText(getApplicationContext(),driverdata.extrastmt,Toast.LENGTH_LONG).show();
//route.drawRoute(mMap,this,latLng1,latLng2,lang);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom((latLng1),15);
mMap.animateCamera(cameraUpdate);
//route.drawRoute(mMap, this, points, true, lang, false);
}
#Override
public void onProviderEnabled(String provider) {
(Toast.makeText(getApplication(), "Reconnecting", Toast.LENGTH_LONG)).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplication(),"Connection Failed! Check Network!",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
#Override
public void onLocationChanged(Location location) {
Log.d("Latitude", "status");
}
}
And this my route class
public class Route {
GoogleMap mMap;
Context context;
String lang;
static String LANGUAGE_SPANISH = "es";
static String LANGUAGE_ENGLISH = "en";
static String LANGUAGE_FRENCH = "fr";
static String LANGUAGE_GERMAN = "de";
static String LANGUAGE_CHINESE_SIMPLIFIED = "zh-CN";
static String LANGUAGE_CHINESE_TRADITIONAL = "zh-TW";
static String TRANSPORT_DRIVING = "driving";
static String TRANSPORT_WALKING = "walking";
static String TRANSPORT_BIKE = "bicycling";
static String TRANSPORT_TRANSIT = "transit";
public boolean drawRoute(GoogleMap map, Context c, ArrayList<LatLng> points, boolean withIndications, String language, boolean optimize)
{
mMap = map;
context = c;
lang = language;
if(points.size() == 2)
{
String url = makeURL(points.get(0).latitude,points.get(0).longitude,points.get(1).latitude,points.get(1).longitude,"driving");
new connectAsyncTask(url,withIndications).execute();
return true;
}
else if(points.size() > 2)
{
String url = makeURL(points,"driving",optimize);
new connectAsyncTask(url,withIndications).execute();
return true;
}
return false;
}
private String makeURL (ArrayList<LatLng> points, String mode, boolean optimize){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append( points.get(0).latitude);
urlString.append(',');
urlString.append(points.get(0).longitude);
urlString.append("&destination=");
urlString.append(points.get(points.size()-1).latitude);
urlString.append(',');
urlString.append(points.get(points.size()-1).longitude);
urlString.append("&waypoints=");
if(optimize)
urlString.append("optimize:true|");
urlString.append( points.get(1).latitude);
urlString.append(',');
urlString.append(points.get(1).longitude);
for(int i=2;i<points.size()-1;i++)
{
urlString.append('|');
urlString.append( points.get(i).latitude);
urlString.append(',');
urlString.append(points.get(i).longitude);
}
urlString.append("&sensor=true&mode="+mode);
return urlString.toString();
}
private String makeURL (double sourcelat, double sourcelog, double destlat, double destlog,String mode){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString
.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString
.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode="+mode+"&alternatives=true&language="+lang);
return urlString.toString();
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
boolean steps;
connectAsyncTask(String urlPass, boolean withSteps){
url = urlPass;
steps = withSteps;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
driverdata.extrastmt = result;
drawPath(result, steps);
//makeT(result);
}else{
driverdata.extrastmt="null";
}
}
}
private void drawPath(String result, boolean withSteps) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(4)
.color(Color.BLUE).geodesic(true));
}
if(withSteps)
{
JSONArray arrayLegs = routes.getJSONArray("legs");
JSONObject legs = arrayLegs.getJSONObject(0);
JSONArray stepsArray = legs.getJSONArray("steps");
//put initial point
for(int i=0;i<stepsArray.length();i++)
{
Step step = new Step(stepsArray.getJSONObject(i));
mMap.addMarker(new MarkerOptions()
.position(step.location)
.title(step.distance)
.snippet(step.instructions)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
}
catch (JSONException e) {
}
}
/**
* Class that represent every step of the directions. It store distance, location and instructions
*/
private class Step
{
public String distance;
public LatLng location;
public String instructions;
Step(JSONObject stepJSON)
{
JSONObject startLocation;
try {
distance = stepJSON.getJSONObject("distance").getString("text");
startLocation = stepJSON.getJSONObject("start_location");
location = new LatLng(startLocation.getDouble("lat"),startLocation.getDouble("lng"));
try {
instructions = URLDecoder.decode(Html.fromHtml(stepJSON.getString("html_instructions")).toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and finally JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
URL urlnew = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlnew.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.d("JSON_RUTA", json);
return json;
}
}
Please I need assistance, and moreover it fetches the data but on the map activity i.e, servicing activity the toast delivers nothing, once you press back and then again on button to start servicing activity, the toast delivers previous results, but no route can be seen on map.
I found solution, basically, I was calling route.drawroute(), before adding the points to the list, so it was returning null.

Google Places Details search System.err

I'm attempting to locate a restaurant by name using an AutoCompleteTextView which successfully obtains the places id. I've also checked the http request manually in my browser which responds with the correct information. When this code is executed, a system.err is shown in the LogCat console in Eclipse. My code below;
public class AdvancedSearch extends Activity implements OnItemClickListener {
private static final String LOG_TAG = "com.lw276.justdine";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
// ------------ make your specific key ------------
private static final String API_KEY = "MyAPIKEY";
private Activity context = this;
static HashMap<String, String> place;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_advanced_search);
final AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this,
R.layout.list_item));
autoCompView.setOnItemClickListener(this);
Button btnAdvancedSearch = (Button) findViewById(R.id.advanced_search_btn);
btnAdvancedSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str = autoCompView.getText().toString();
if(place.containsKey(str)){
String placeId = place.get(str);
Log.d("advancedSearchBtn: placeId = ", placeId);
Log.i("advancedSearchBtn", "Search button has been pressed");
Intent i = new Intent(context, GoogleMap.class);
i.putExtra("advancedSearch", placeId);
startActivity(i);
} else {
Toast.makeText(context, "Please select an item from the autocomplete list", Toast.LENGTH_SHORT).show();
}
}
});
}
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
// String str = (String) adapterView.getItemAtPosition(position);
// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE
+ TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: " + url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
resultList = new ArrayList<String>(predsJsonArray.length());
place = new HashMap<String, String>();
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString(
"description"));
System.out
.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString(
"description"));
String description = predsJsonArray.getJSONObject(i).getString("description");
String placeId = predsJsonArray.getJSONObject(i).getString("place_id");
place.put( description, placeId);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String>
implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context,
int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
// #Override
// public HashMap<String, String> getItem(int index) {
// return resultList.get(index);
// }
#Override
public String getItem(int index){
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
The googlePlaces example =
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJCSWGvY-FdUgRpGdg10FTIIg&key="MY_API_KEY"
Is it obvious to anyone why no markers are being placed on my map fragment?
Errors from LogCat:
http://pastebin.com/T1AFbw3s
Google Maps and Markers class:
http://pastebin.com/hT2XwuE2
The error you are having is due to parsing the Json incorrectly at line 193 of GoogleMap activity:
JSONArray placesArray = resultObject.getJSONArray("results");
I believe the key is result instead of results.
I can give you a better explanation if I could see the json response. Meanwhile,
I would also suggest you to use Gson Library to parse the json responses to objects instead of mapping them manually. It would be alot easier.
Markers need to be added manually:
private void addMarker(String name, double lat, double long){
LatLng latlong = LatLng.newInstance(lat, long);
MarkerOptions markerOptions = MarkerOptions.newInstance();
markerOptions.setIcon(Icon.newInstance("/img/icon.png"));
markerOptions.setTitle(name);
Marker marker = new Marker(latlong, markerOptions);
map.addOverlay(marker);
}
It turns out that because I was using the same code to add markers onto the Map, when the detail search was used to identify a single place, the JSONArray type was incompatible with the result set... If that makes sense.
I had to separate the two by checking if a nearby search was being performed or a details search. Below was the code for the details search only:
resultObject = resultObject.getJSONObject("result"); // <---
places = new MarkerOptions[1];
LatLng placeLL = null;
String placeName = "";
String vicinity = "";
try {
JSONObject placeObject = resultObject;
JSONObject loc = placeObject.getJSONObject(
"geometry").getJSONObject("location");
placeLL = new LatLng(Double.valueOf(loc
.getString("lat")), Double.valueOf(loc
.getString("lng")));
vicinity = placeObject.getString("vicinity");
placeName = placeObject.getString("name");
} catch (JSONException jse) {
missingValue = true;
jse.printStackTrace();
}
if (missingValue){
result = null;
} else {
places[0] = new MarkerOptions().position(placeLL)
.title(placeName).snippet(vicinity);
}

Problems while displaying path between two points in google maps

This problem may sound a little weird, but whenever I run the app it crashes and when I change the name of LatLang variable in the function private LatLng getCurrentLocation(), It starts working. But when I change anything(even in any other file) it crashes and I have to keep changing the variable names to keep it running.
I am sure of the problem, it is something related to LatLang variable.
GetApproxTimeMaps.java
public class GetApproxTimeMaps extends FragmentActivity {
private static double destiLatitude;
private static double destiLongitude;
GoogleMap mMap;
GMapV2Direction md;
LatLng userLocation;
LatLng destination;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_approx_time_maps);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
userLocation = getCurrentLocation();
double lati = userLocation.latitude;
double longi = userLocation.longitude;
JSONObject jasonObject = getLocationInfo("Infosys");
boolean value = getLatLong(jasonObject);
System.out.println("value is: "+ value);
destination = new LatLng(destiLatitude, destiLongitude);
System.out.println("destination latitude :" + destiLatitude);
System.out.println("destination longitude :" + destiLongitude);
md = new GMapV2Direction();
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
double toZoomLat = (destination.latitude + userLocation.latitude)/2;
double toZoomLon = (destination.longitude + userLocation.longitude)/2;
LatLng coordinates = new LatLng(toZoomLat, toZoomLon);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 12));
mMap.addMarker(new MarkerOptions().position(userLocation).title("Start"));
mMap.addMarker(new MarkerOptions().position(destination).title("End"));
Document doc = md.getDocument(userLocation, destination, GMapV2Direction.MODE_DRIVING);
int duration = md.getDurationValue(doc);
String distance = md.getDistanceText(doc);
String start_address = md.getStartAddress(doc);
String copy_right = md.getCopyRights(doc);
System.out.println(duration);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);
for(int i = 0 ; i < directionPoint.size() ; i++) {
rectLine.add(directionPoint.get(i));
}
mMap.addPolyline(rectLine);
}
private LatLng getCurrentLocation(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userlocat = new LatLng(location.getLatitude(),location.getLongitude());
return userlocat;
}
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
public static boolean getLatLong(JSONObject jsonObject) {
try {
destiLongitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
destiLatitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
return false;
}
return true;
}

Force Close During ArrayList Implementation - Android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm coming across an issue where I'm getting a null pointer exception (and force close) on the line:
nameArr = handler.getnameArr();
...in ConfigFinalActivity (shown below). I've attempted to debug different values
ConfigFinalActivity Source Code Snippet:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button mXButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private Button mReadAgainButton = null;
private int mInstructionNumber = 0;
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
public static int count;
public static int TotalSteps = 8;
int i, g = 0, result = 0;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static final String Base_URL = "https://test.testsite555.com/REST/phoneSettings";
public static InputStream stream = null;
UpdateActivity update;
public static String status, queryResult = "";
/** Called when the activity is first created. */
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
update = new UpdateActivity();
getArrayLists();
/*
* boolean deleted = deleteFile("settings.xml");if(deleted){
* Log.v("settings.xml","deleted"); }else
* Log.v("settings.xml","failed to delete the file");
*/
if (ApnArr.isEmpty() || mmscArr.isEmpty()) {
// tryagain();
} else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Update APN table
try {
result = updateTable();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// Settings updated with this atomic call
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result != -1) {
status = "success";
} else {
status = "failure";
}
if (status.equals("success")) {
completeUpdate();
} else if (status.equals("failure")) {
// tryagain();
// showAlert(getString(R.string.unchanged_dialog));
}
} else {// ICS and later versions
// Reduce number of steps to 6
TotalSteps = 6;
setContentView(R.layout.assist_instructions);
String assistUpdate = getString(R.string.instructions_1);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
private void getArrayLists() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
I know the application is crashing because of a null value in the code shown above - but I need a bit of assistance figuring out what might be causing it to be null.
I believe the issue is stemming from a problem in the following activity (but I'm not sure at this point - any debugging/breakpoint suggestions would be incredibly helful):
Update Activity:
public class UpdateActivity extends Activity {
private TelephonyManager tm;
AlertDialog mConfirmAlert = null;
NetworkTask task;
ImageView image, text;
AlertDialog mErrorAlert = null;
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
public static int count;
public AnimationDrawable mTextAnimation = null;
TextView mUpdatetext;
public static InputStream stream = null;
int version;
public static BigInteger iD1, iD2, mdN1, mdN2;
BigInteger[] id, mdnId;
public static String ICCID, MDN;
public static String caR;
public static int result;
private static final String LOG_TAG = "DataSettings";
public static final String Base_URL = "https://someurl.testsite555.com/REST/phoneSettings";
public static XmlParserHandlerFinal handler;
public static int TotalSteps = 8;
public FileInputStream fis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// instance for xml parser class
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
version = android.os.Build.VERSION.SDK_INT;
// to get MDN(MCC+MNC) of the provider of the SIM and ICCID (Serial
// number of the SIM)
// and to check for the Carrier type
getImpVariablesForQuery();
task = new NetworkTask();
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo or ATT network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo & ATT MNC MCC present
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Device has T-Mo or ATT network SIM card MCC and MNC correctly
// populated
TotalSteps = 6;
setContentView(R.layout.updating);
// image = (ImageView) findViewById(R.id.updating_image);
// text = (ImageView) findViewById(R.id.updating_text);
//
// text.setBackgroundResource(R.drawable.animation);
// mTextAnimation = (AnimationDrawable) text.getBackground();
// AsyncTask to call the web service
task.execute("");
}
}
// #Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// // Animate GO button when corresponding window is in focus
// Animation a = AnimationUtils.loadAnimation(getBaseContext(),
// R.anim.image);
// a.setDuration(1000);
// a.setInterpolator(new Interpolator() {
// private final int frameCount = 16;
//
// #Override
// public float getInterpolation(float input) {
// return (float) Math.floor(input * frameCount) / frameCount;
// }
// });
// image.startAnimation(a);
//
// mTextAnimation.start();
// }
private void getImpVariablesForQuery() {
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
// to get MDN
MDN = tm.getLine1Number();
// MDN = "7862125102";
if (MDN.equals("")) {
mdN1 = null;
mdN2 = null;
} else {
Log.d("MDN", MDN);
BigInteger bInt = new BigInteger(MDN);
mdnId = bInt.divideAndRemainder(divisor);
// to retrieve ICCID number of the SIM
mdN1 = mdnId[1];
System.out.println("MDN%1234 = " + mdN1);
mdN2 = mdnId[0];
System.out.println("MDN/1234 = " + mdN2);
}
ICCID = tm.getSimSerialNumber();
if (ICCID.equals("")) {
iD1 = null;
iD2 = null;
} else {
Log.d("ICCID", ICCID);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
iD1 = id[1];
System.out.println("ICCID%1234 = " + iD1);
iD2 = id[0];
System.out.println("ICCID/1234 = " + iD2);
}
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
caR = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
caR = "ATT";
}
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
public ArrayList<String> getnameArr() {
return nameArr;
}
public ArrayList<String> getApnArr() {
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public int getCount() {
return count;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
// AsyncTask to call web service
private class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
/*
* query the server for the data settings put the returned data
* settings into values
*/
// String charset = "UTF-8";
// String param1 = "mdn1=";
// String param2 = "&mdn2=";
// String param3 = "&car=";
// String param4 = "&id1=";
// String param5 = "&id2=";
// String parameters = param1 + Mdn1 + param2 + Mdn2 + param3
// + Car + param4 + iD1 + param5 + iD2;
// String parameters = param1 + Mdn1 + param2 + Mdn2 ;
// URL = Base_URL + URLEncoder.encode(parameters, charset);
Log.i("url...", Base_URL);
stream = getQueryResults(Base_URL);
} catch (IOException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
try {
// HttpsURLConnection https = null;
String uri = urlQueryString;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// BasicNameValuePair username = new
// BasicNameValuePair("username",
// "nmundru");
// BasicNameValuePair password = new
// BasicNameValuePair("password",
// "abc123");
BasicNameValuePair mdn1, mdn2,id1,id2;
if (MDN.equals("")) {
mdn1 = new BasicNameValuePair("mdn1", null);
mdn2 = new BasicNameValuePair("mdn2", null);
} else {
mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());
}
BasicNameValuePair car = new BasicNameValuePair("car", caR);
if (ICCID.equals("")) {
id1 = new BasicNameValuePair("id1", null);
id2 = new BasicNameValuePair("id2", null);
} else {
id1 = new BasicNameValuePair("id1",
iD1.toString());
id2 = new BasicNameValuePair("id2",
iD2.toString());
}
// nameValuePairs.add(username);
// nameValuePairs.add(password);
nameValuePairs.add(mdn1);
nameValuePairs.add(mdn2);
nameValuePairs.add(car);
nameValuePairs.add(id1);
nameValuePairs.add(id2);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairs, "ISO-8859-1");
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
HttpClient httpClient = new DefaultHttpClient(ccm, params);
params = httpClient.getParams();
HttpClientParams.setRedirecting(params, true);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Authorization",
getB64Auth("nmundru", "abc123"));
httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.v("httpPost", httpPost.toString());
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("response...." + httpResponse.toString());
Log.v("response...", httpResponse.toString());
stream = httpResponse.getEntity().getContent();
// save the InputStream in a file
try {
FileOutputStream fOut = openFileOutput("settings.xml",
Context.MODE_WORLD_READABLE);
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine); //to print the response
// in logcat
fOut.write(strLine.getBytes());
}
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fis = openFileInput("settings.xml");
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
// e.printStackTrace();
tryagain();
} finally {
// https.disconnect();
}
return stream;
}
private String getB64Auth(String login, String pass) {
String source = login + ":" + pass;
String ret = "Basic "
+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
| Base64.NO_WRAP);
return ret;
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
}
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void tryagain() {
// Displaying final layout after failure of pre-ICS automatic settings
// update
// setContentView(R.layout.tryagain);
// String tryAgainText = "";
// CharSequence styledTryAgainText;
//
// tryAgainText = String.format(getString(R.string.tryagain_text1),
// TotalSteps);
// styledTryAgainText = Html.fromHtml(tryAgainText);
// TextView tryAgain1 = (TextView) findViewById(R.id.tryagain_text1);
// tryAgain1.setText(styledTryAgainText);
//
// tryAgainText = String.format(getString(R.string.tryagain_text2),
// TotalSteps);
// styledTryAgainText = Html.fromHtml(tryAgainText);
// TextView tryAgain2 = (TextView) findViewById(R.id.tryagain_text2);
// tryAgain2.setText(styledTryAgainText);
//
// tryAgainText = String.format(getString(R.string.tryagain_text3),
// TotalSteps);
// styledTryAgainText = Html.fromHtml(tryAgainText);
// TextView tryAgain3 = (TextView) findViewById(R.id.tryagain_text3);
// tryAgain3.setText(styledTryAgainText);
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
public int getResult() {
return result;
}
}
If you are sure that this line
nameArr = handler.getnameArr();
gives the NPE then you know the problem must be that handler is null at this point. That is the only way this line will throw a NPE. And from looking at that massive code, it definitely looks like handler is not instantiated before you call the method that uses it (getArrayLists();). You declare it here
XmlParserHandlerFinal handler;
but you never give it a value before trying to use it.
You will need to instantiate it in this Activity before calling a method on it such as getnameArr();. You instantiate it in the other Activity but not in this one.

Categories