how to get driving alternative routes in google map direction api v2 - java

I just want to show driving mode alternative routes in my android app. I done a single shortest route but I want multiple driving routes.
My code is here
my mapsavtivity class
package com.example.sherazahmed.itis;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
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.ArrayList;
import java.util.HashMap;
public class onNotificationClick extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
static LatLng current=new LatLng(0,0);
static LatLng destination=new LatLng(0,0);
public void onNotificationClick(LatLng current,LatLng destination){
this.current=current;
this.destination=destination;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_notification_click);
// 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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.addMarker(new MarkerOptions().position(current).title("current location"));
mMap.addMarker(new MarkerOptions().position(destination).title("destination"));
DownloadTask downloadTask;
String url=null;
String mode = "mode=driving";
String mode1 = "mode=bicycling";
String mode2 = "mode=walking";
url = getDirectionsUrl(current, destination,mode);
downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
//2
url = getDirectionsUrl(current, destination,mode2);
downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
//3
url = getDirectionsUrl(current, destination,mode1);
downloadTask=new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
private String getDirectionsUrl(LatLng origin,LatLng dest, String mode){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
String alter="Alternative=true";
// Travelling Mode
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+mode+"&"+alter;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data =new String();
InputStream iStream = new InputStream() {
#Override
public int read() throws IOException {
return 0;
}
};
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 in down url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data =new String();
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<LatLng>();
PolylineOptions lineOptions = new PolylineOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(4);
// Changing the color polyline according to the mode
}
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points", Toast.LENGTH_SHORT).show();
return;
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
}
DirectionJSONParser class
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject) ((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google- maps-direction-api-with-java
* */
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

String alter="Alternatives=true";
is the way to do this thing, i just forgot to place
"s" in alternative in above code !
cheers !

Related

Calculate Time and distance and draw a path between two draggable markers in Google maps v2

Need your help!!..I am building an android app using Google API V2. I have managed to place two markers on the map and also get there location. What I mainly want to do now is to calculate their distance and time like we do in the Google maps and draw a path between them. How can I achieve that?
a-) Can I do it without using JSON? I just know JAVA not java script so help please.
b-) Who ever answer it, Please if you can, Elaborate the steps taken in the code comments?
Here is my Maps ACtivity
--
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,LocationListener,GoogleMap.OnMarkerClickListener, GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener {
private GoogleApiClient mGoogleApiClient;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
private LocationRequest LocationDrop;
// TextView currentloc;
String filterAddress = "";
String DropoffAdress = "";
String DraggedDroppOff= "";
String dragendaddress = "";
// TextView dropOffaddress;
double currentLatitude;
double currentLongitude;
double draglat;
double draglng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// tvLocInfo = (TextView) findViewById(R.id.locinfo);
mMap.setOnMapLongClickListener(this);
mMap.setOnMarkerDragListener(this);
mMap.setOnMarkerClickListener(this);
// LocationDrop = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10 * 1000).setFastestInterval(1 * 1000);
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
// mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Pick Me").snippet(filterAddress));
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
}
else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions optionsA = new MarkerOptions().position(latLng).title("Pick Me").snippet(filterAddress).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMap.addMarker(optionsA).setDraggable(false);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
// mMap.moveCamera(center);
mMap.animateCamera(zoom);
// mMap.setOnMarkerDragListener();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(currentLatitude,currentLongitude,1);
// List<Address> dropaddress = geoCoder.getFromLocation(laterLongitut,laterlatitude,1);
if (addresses.size() > 0) {
for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
filterAddress += addresses.get(0).getAddressLine(i) + " ";
Log.e("My current address is 2", filterAddress );
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
// currentloc = (TextView) findViewById(R.id.txmarker);
// currentloc.setText("Address" + filterAddress);
Log.e("My current address is 1", filterAddress);
// Log.e("My later address is 2", DropoffAdress );
Toast.makeText(getBaseContext(),filterAddress,Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public void onBackPressed(){
Intent intent = new Intent(this,TurnOnGps.class);
startActivity(intent);
setContentView(R.layout.activity_turn_on_gps);
}
#Override
public void onInfoWindowClick(Marker marker) {
marker.setTitle(filterAddress);
}
#Override
public void onMapLongClick(LatLng latLng) {
MarkerOptions options2 = new MarkerOptions();
options2.position(latLng);
options2.title("Drop ME").snippet("Dragg Me ");
options2.draggable(true);
mMap.addMarker(options2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
Toast.makeText(getBaseContext(),"Please Drag Marker to set your Drop OFF",Toast.LENGTH_LONG).show();
// mMap.moveCamera(center);
mMap.animateCamera(zoom);
/* double updateddroplat = latLng.latitude;
double updateddroplng = latLng.longitude;
//Converting the latlngs to a string through geoencoder
LatLng latLng1 = new LatLng(updateddroplat,updateddroplng);
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(updateddroplat,updateddroplng,1);
if(addresses.size() > 0){
for (int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
DropoffAdress += addresses.get(0).getAddressLine(i) + "";
Log.e("My DroppOff Location is" , DropoffAdress);
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
Log.e("My DropOff Location is" , DropoffAdress);
Toast.makeText(getBaseContext(),DropoffAdress,Toast.LENGTH_LONG).show();
*/
}
#Override
public void onMarkerDragStart(Marker marker) {
marker.setSnippet("Please Drag me to set your Drop OFF");
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
DropoffAdress = dragendaddress;
Log.e("My DroppOff Location is" , DraggedDroppOff);
LatLng dragposition = marker.getPosition();
draglat = dragposition.latitude;
draglng = dragposition.longitude;
LatLng latLng1 = new LatLng(draglat, draglng);
marker.getId();
// marker.getSnippet();
marker.setSnippet(dragendaddress);
marker.setTitle("Drop ME");
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(draglat,draglng,1);
if(addresses.size() > 0){
for (int i=0; i < addresses.get(0).getMaxAddressLineIndex(); i++){
dragendaddress += addresses.get(0).getAddressLine(i) + "";
Log.e("My DroppOff Location is", dragendaddress);
}
Toast.makeText(getBaseContext(),dragendaddress,Toast.LENGTH_LONG).show();
}
}catch (IOException ex){
ex.printStackTrace();
}catch (Exception e2){
e2.printStackTrace();
}
}
#Override
public boolean onMarkerClick(Marker marker ) {
Log.e("am in markerclick event","");
String Title = marker.getTitle();
String Snippet = marker.getSnippet();
Log.e("I am in onMarkerClick", Title);
if(Title.equals("Pick Me")){
marker.setSnippet(filterAddress);
Toast.makeText(getBaseContext(),filterAddress,Toast.LENGTH_LONG).show();
Log.e("I am in onMarkerClick", Title);
}else if(Title.equals("Drop ME")){
marker.setSnippet(dragendaddress);
Toast.makeText(getBaseContext(),dragendaddress,Toast.LENGTH_LONG).show();
}
try {
Polyline polyline = mMap.addPolyline(new PolylineOptions().add(new LatLng(currentLatitude, currentLongitude), new LatLng(draglat, draglng)).width(10).color(Color.RED));
}catch (Exception e){
e.printStackTrace();
}
return false;
}
calculating the distance ::
public float distance (LatLng point1, LatLng point2 )
{
double earthRadius = 3958.75;
double latDiff = Math.toRadians(point2.latitude - point1.latitude);
double lngDiff = Math.toRadians(point2.longitude - point2.longitude);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(point1.latitude)) * Math.cos(Math.toRadians(point2.latitude)) *
Math.sin(lngDiff /2) * Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance).floatValue();
}
and to draw a line add the points to a list then use the polyline function .
Ok Firstly thanks all you guys for being a support. I finally got the solution to my problem with blessings and a bit of my own RND..
http://wptrafficanalyzer.in/blog/route-between-two-locations-with-waypoints-in-google-map-android-api-v2/
This greatly solved the Direction Parsing issue.
And i molded my code and added the methods from the Maps activity and JSON class.
Which solved the problem.
Happy :)
Thanks for taking the time..
+Any one having the same issue can post there problem in the comments i would try to answer it. Through what ever small i have learnt from solving this problem..
You can use code here. In this code distanceText gives distance between two points and timeText gives travelling time.

java.lang.nullpointerexception attempt to invoke method 'int java.util.List.size()' [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Main Activity
trying to add google map please help as soon as u can
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
public class OnscreenActivity extends FragmentActivity {
private static final LatLng sydney = new LatLng(30.8894669, 75.8246729);
private static final LatLng connct = new LatLng(30.8914863, 75.874398);
GoogleMap googleMap;
final String TAG1 = "PathGoogleMapActivity";
public static final String TAG = OnscreenActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment1);
googleMap = fm.getMap();
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG, currentUser.getUsername());
}
ActionBar actionbar = getActionBar();
actionbar.show();
MarkerOptions options = new MarkerOptions();
options.position(sydney);
options.position(connct);
googleMap.addMarker(options);
String url = getMapsApiDirectionsUrl();
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(connct, 16));
addMarkers();
}
private void addMarkers() {
// TODO Auto-generated method stub
if (googleMap != null) {
googleMap.addMarker(new MarkerOptions().position(sydney).title(
"First Point"));
googleMap.addMarker(new MarkerOptions().position(connct).title(
"Second Point"));
}
}
private String getMapsApiDirectionsUrl() {
String waypoints = "waypoints=optimize:true|" + sydney.latitude + ","
+ sydney.longitude + "|" + "|" + connct.latitude + ","
+ connct.longitude;
String sensor = "sensor=false";
String params = waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
private class ReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJsonParser parser = new PathJsonParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
// traversing through routes
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(2);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
}
private void navigateToLogin() {
Intent intent = new Intent(this, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
if (itemId == R.id.options) {
Intent intent = new Intent(this, UserOptions.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
return super.onOptionsItemSelected(null);
}
}
It is impossible for us to tell you exactly why the routes List is null in your onPostExecute in the ParserTask, but it is.
If it is intended that your doInBackground in ParserTask can return null, you should at least check if the routes variable is null before you attempt to do anything with it. This will not fix the error and might result in your app not doing what it should, but as I mentioned previously, it's impossible to tell you any more without the full log.
if (routes == null) return; will suppress the error, but only solve your problem if you read multiple json files and some of them actually parse.

AsyncTask doesn't call onPostExecute(Result result)

I m trying here to display a 7 day weather forecast from OWM API using AsyncTask.
doInBackground(String...param) method is also working fine. I have checked the LOGCAT.
After the async has finished the execution. I tried to refresh the ListView on refresh button in the menu. But it seems the onPostExecute() does care all about.
ForecastFragment.java
package com.example.sunshine;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForeCastAdapter;
public String[] forecastArray;
public ForecastFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new FetchWeatherTask().execute("44700");
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onPostExecute(String[] result) {
if (result != null) {
Log.v("msg", result[0]);
mForeCastAdapter.clear();
// forecastArray = result;
for (String dayForecastStr : result) {
mForeCastAdapter.add(dayForecastStr);
// mForeCastAdapter.notifyDataSetChanged();
}
}
mForeCastAdapter.notifyDataSetChanged();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
String[] list = { "1", "2", "3" };
List<String> weekForeCast = new ArrayList<String>(
Arrays.asList(list));
mForeCastAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.list_item_forecast, R.id.list_item_forecast_textview,
weekForeCast);
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
ListView weekList = (ListView) rootView
.findViewById(R.id.list_item_forecast);
weekList.setAdapter(mForeCastAdapter);
return rootView;
}
}
class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
protected ArrayAdapter<String> mForeCastAdapter;
/*
* The date/time conversion code is going to be moved outside the asynctask later, so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time) {
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to
// valid date.
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a
// degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
for (int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read
// "1400356800" as
// "this saturday".
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1
// element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER)
.getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name
// variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast
.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
for (String s : resultStrs)
{
Log.v(LOG_TAG, "Forecast Array : " + s);
}
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params)
{
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
// URL url = new
// URL("http://api.openweathermap.org/data/2.5/forecast/daily?" +
// "q=94043&mode=json&units=metric&cnt=7");
final String FORECAST_BASE_URL= ="http://api.openweathermap.org/
data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String MODE_PARAM = "mode";
final String UNIT_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri urlBuild = Uri
.parse(FORECAST_BASE_URL)
.buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(MODE_PARAM, format)
.appendQueryParameter(UNIT_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(urlBuild.toString());
//Log.v(LOG_TAG, "Build URL " + urlBuild.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
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) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
// Log.v(LOG_TAG, "Forecast JSON String" + forecastJsonStr);
}
catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no
// point in attemping
// to parse it.
return null;
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
}catch(JSONException e){
Log.e(LOG_TAG,e.getMessage(), e);
e.printStackTrace();
}
return null;
}
}
Try using the method onPostExecute in your AsyncTask class rather than your Fragment class. The AsyncTask class looks like this:
private class MyTask extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
}
#Override
protected void onPostExecute(String result[]) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
For your case, you will want to put the onPostExecute method inside your FetchWeatherTask class as such:
class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
....
#Override
protected void onPostExecute(String result[]) {
if (result != null) {
Log.v("msg", result[0]);
mForeCastAdapter.clear();
//forecastArray = result;
for (String dayForecastStr : result) {
mForeCastAdapter.add(dayForecastStr);
//mForeCastAdapter.notifyDataSetChanged();
}
}
mForeCastAdapter.notifyDataSetChanged();
}
....
}
You should be overriding the OnPostExecute() in your FetchWeatherTask the same way you are overriding doInBackground()
The async task doesm't have an onPostExecute() method. You have a method called onPostExecute() in your fragment but not in asynctask.
Note that your IDE didn't auto-complete #Override there. If you added it there yourself, you'd get an error about not overriding a base class method.
First time solved the answer on my own by proper use of LogCat - This is great
The error was causing due to double declaration of public static ArrayAdapter<String> mForeCastAdapter=null.
Solved it using the line numbers given along each error.
P.S: I was searching for answers for about 4 hours before I posted the question. I guess it was for some good reason.

Putting current location into maps application

I am trying to add a way of viewing my current location to my application and can't figure out how to do it without getting errors. I currently have the two incorrectly stored in separate activities (Markers locations in one activity and my location in other activity) and can't seem to combine them.
Sorry about the poor attempt at describing my problem, hopefully this code will help more.
MainActivity
package com.kieranmaps.v2maps;
import java.util.Hashtable;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.app.ActivityManager;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
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.kieranmaps.v2maps.R;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.FIFOLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
public class MainActivity extends FragmentActivity {
private GoogleMap googleMap;
private final LatLng OREILLYS = new LatLng(53.348347, -6.254119);
private final LatLng LAGOONA = new LatLng(53.349810, -6.243160);
private final LatLng COPPERS = new LatLng (53.335356, -6.263481);
private final LatLng WRIGHTS = new LatLng (53.445491, -6.223857);
private final LatLng ACADEMY = new LatLng (53.348045,-6.26198);
private final LatLng DICEYS = new LatLng (53.347250, -6.254198);
private final LatLng PYGMALION = new LatLng (53.342183,-6.262358);
private final LatLng FIBBERS = new LatLng (53.352799,-6.260412);
// private final LatLng TEST = new LatLng (5352799,-6.260412);
private Marker marker;
private Hashtable<String, String> markers;
private ImageLoader imageLoader;
private DisplayImageOptions options;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
initImageLoader();
markers = new Hashtable<String, String>();
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher) // Display Stub Image
.showImageForEmptyUri(R.drawable.ic_launcher) // If Empty image found
.cacheInMemory()
.cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565).build();
if ( googleMap != null ) {
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
final Marker oreillys = googleMap.addMarker(new MarkerOptions().position(OREILLYS)
.title("O Reillys"));
markers.put(oreillys.getId(), "http://img.india-forums.com/images/100x100/37525-a-still-image-of-akshay-kumar.jpg");
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(OREILLYS, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
final Marker coppers = googleMap.addMarker(new MarkerOptions().position(COPPERS)
.title("Coppers"));
markers.put(coppers.getId(), "http://f3.thejournal.ie/media/2011/11/coppers1-390x285.png");
final Marker wrights = googleMap.addMarker(new MarkerOptions().position(WRIGHTS)
.title("The Wright Venue"));
markers.put(wrights.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker lagoona = googleMap.addMarker(new MarkerOptions().position(LAGOONA)
.title("The Lagoona"));
markers.put(lagoona.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker academy = googleMap.addMarker(new MarkerOptions().position(ACADEMY)
.title("The Academy"));
markers.put(academy.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker pygmalion = googleMap.addMarker(new MarkerOptions().position(PYGMALION)
.title("The Pygmalion"));
markers.put(pygmalion.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker fibbers = googleMap.addMarker(new MarkerOptions().position(FIBBERS)
.title("Fibbers"));
markers.put(fibbers.getId(), "http://www.turbosound.com/public/images/news_img_thumbs/Wright_Venue_Dancefloor-thumb.jpg");
final Marker diceys = googleMap.addMarker(new MarkerOptions().position(DICEYS)
.title("Dicey's"));
markers.put(diceys.getId(), "https://dublinnow.files.wordpress.com/2012/05/diceys.jpg");
/* final Marker diceys = googleMap.addMarker(new MarkerOptions()
.position(DICEYS)
.title("Diceys")
.snippet("Drink Deal: 3.50. Adm: 5, Performance: Gen"));
Marker marker = GoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Title")
.snippet("Snippet")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker))); */
//marker.showInfoWindow();
}
}
private class CustomInfoWindowAdapter implements InfoWindowAdapter {
private View view;
public CustomInfoWindowAdapter() {
view = getLayoutInflater().inflate(R.layout.custom_info_window,
null);
}
#Override
public View getInfoContents(Marker marker) {
if (MainActivity.this.marker != null
&& MainActivity.this.marker.isInfoWindowShown()) {
MainActivity.this.marker.hideInfoWindow();
MainActivity.this.marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(final Marker marker) {
MainActivity.this.marker = marker;
String url = null;
if (marker.getId() != null && markers != null && markers.size() > 0) {
if ( markers.get(marker.getId()) != null &&
markers.get(marker.getId()) != null) {
url = markers.get(marker.getId());
}
}
final ImageView image = ((ImageView) view.findViewById(R.id.badge));
if (url != null && !url.equalsIgnoreCase("null")
&& !url.equalsIgnoreCase("")) {
imageLoader.displayImage(url, image, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view,
loadedImage);
getInfoContents(marker);
}
});
} else {
image.setImageResource(R.drawable.ic_launcher);
}
//
final String title = marker.getTitle();
final TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
titleUi.setText(title);
} else {
titleUi.setText("");
}
final String snippet = marker.getSnippet();
final TextView snippetUi = ((TextView) view
.findViewById(R.id.snippet));
if (snippet != null) {
snippetUi.setText(snippet);
} else {
snippetUi.setText("");
}
return view;
}
}
private void initImageLoader() {
int memoryCacheSize;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
int memClass = ((ActivityManager)
getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
memoryCacheSize = (memClass / 8) * 1024 * 1024;
} else {
memoryCacheSize = 2 * 1024 * 1024;
}
final ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).threadPoolSize(5)
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(memoryCacheSize)
.memoryCache(new FIFOLimitedMemoryCache(memoryCacheSize-1000000))
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
ImageLoader.getInstance().init(config);
}
}
NewActivity:
package com.kieranmaps.v2maps;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class NewActivity extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
private double sourceLatitude, sourceLongitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 0,
mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
10, 0, mlocListener);
// // Setting onclick event listener for the map
// map.setOnMapClickListener(new OnMapClickListener() {
//
// #Override
// public void onMapClick(LatLng point) {
//
// Toast.makeText(getApplicationContext(), "Clicked !", Toast.LENGTH_SHORT).show();
//
// // Already two locations
// if(markerPoints.size()>1){
// markerPoints.clear();
// map.clear();
// }
//
// // Adding new item to the ArrayList
// markerPoints.add(point);
//
// // Creating MarkerOptions
// MarkerOptions options = new MarkerOptions();
//
// // Setting the position of the marker
// options.position(point);
//
// /**
// * For the start location, the color of marker is GREEN and
// * for the end location, the color of marker is RED.
// */
// if(markerPoints.size()==1){
// options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// }else if(markerPoints.size()==2){
// options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// }
//
//
// // Add new marker to the Google Map Android API V2
// map.addMarker(options);
//
// // Checks, whether start and end locations are captured
// if(markerPoints.size() >= 2){
// LatLng origin = markerPoints.get(0);
// LatLng dest = markerPoints.get(1);
//
// // Getting URL to the Google Directions API
// String url = getDirectionsUrl(origin, dest);
//
// DownloadTask downloadTask = new DownloadTask();
//
// // Start downloading json data from Google Directions API
// downloadTask.execute(url);
// }
//
// }
// });
}
private void sourceTodestination() {
// Source
LatLng point = new LatLng(sourceLatitude, sourceLongitude);
// Destination
double destLatitude = 23.7383;
double destLongitude = 90.3958;
LatLng point1 = new LatLng(destLatitude, destLongitude);
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng((sourceLatitude + destLatitude)/2, (sourceLongitude + destLongitude)/2));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(13);
map.moveCamera(center);
map.animateCamera(zoom);
// Adding new item to the ArrayList
markerPoints.add(point);
markerPoints.add(point1);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
MarkerOptions options1 = new MarkerOptions();
options1.position(point1);
options1.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
// Add new marker to the Google Map Android API V2
map.addMarker(options);
map.addMarker(options1);
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/** 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;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#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;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
sourceLatitude = loc.getLatitude();
sourceLongitude = loc.getLongitude();
sourceTodestination();
Toast.makeText(getApplicationContext(), sourceLatitude + " - " + sourceLongitude,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
android.util.Log.v("", "Latitud = ");
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
android.util.Log.v("", "status = ");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSON Parser
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.model.LatLng;
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
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;
}
}
Forgive me for my ignorance but I can't figure out how to get it working with both of these. Any tips appreciated! thanks
edit: More details, I can only get this working showing the locations but I can't get it to show my current location and route to those destinations
Your current location is the loc from this method
public void onLocationChanged(Location loc)
apply accuracy to your loc location to get a accurate location. accuracy threshold is up to you. less than 30m is fine.

JSON parsing with Java

I created an android app involving JSON parsing. When I run the application in my emulator it worked, but when I run it in my android phone it outputs an error "Unfortunately has stopped".
This is my JSON class:
package com.example.uichandbook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
Button copy;
Button search;
int final_id = 0;
int final_id2 = 0;
int large1 = 0;
int large2 = 0;
int counter2;
int counter1;
String parse;
// url to make request
private static String url = "http://lynda.byethost32.com/UICHandbook/contents.json";
private static String url2 = "http://lynda.byethost32.com/UICHandbook/sub_contents.json";
int id;
DatabaseHandler db = new DatabaseHandler(this);
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (DetectConnection
.checkInternetConnection(MainActivity.this) == true) {
Toast.makeText(MainActivity.this,
"You have Internet Connection", Toast.LENGTH_LONG)
.show();
updates();
}
DatabaseHandler db = new DatabaseHandler(this);
List<data2> contacts = db.getAllContent();
for (data2 cn : contacts) {
LinearLayout lnr = (LinearLayout) findViewById(R.id.container);
lnr.setPadding(1, 1, 1, 1);
b1 = new Button(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // Verbose!
lp.weight = 1.0f; // This is critical. Doesn't work without it.
b1.setId(cn.getid());
final int _id = b1.getId();
b1.setText(cn.getcontentname());
lnr.addView(b1, lp);
copy = ((Button)findViewById(_id));
copy.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, subcontent.class);
intent.putExtra("id", _id);
startActivity(intent);
}
});
}
db.close();
}
public void getjson()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String jsonreader = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(jsonreader);
contacts = jsonObject.getJSONArray("tbl_content");
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
Log.d("contact", c.getString("content_name"));
Log.d("contact", c.getString("content"));
Log.d("contact", c.getString("content_id"));
Log.d("contact", c.getString("book_id"));
DatabaseHandler db = new DatabaseHandler(this);
db.addcontent(new data2(c.getInt("content_id"), c.getString("content_name"),c.getString("content"),c.getInt("book_id")));
}
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
}
public void getjson2()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url2);
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url2);
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String jsonreader = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(jsonreader);
contacts = jsonObject.getJSONArray("subcontent");
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
Log.d("contact", c.getString("subcontent_name"));
Log.d("contact", c.getString("subcontent"));
Log.d("contact", c.getString("subcontent_id"));
Log.d("contact", c.getString("content_id"));
DatabaseHandler db = new DatabaseHandler(this);
db.subaddcontent(new data3(c.getInt("subcontent_id"), c.getString("subcontent_name"),c.getString("subcontent"),c.getInt("content_id")));
}
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
}
final static String SYSTEM_NEWLINE = "\n";
final static float COMPLEXITY = 5.12f; //Reducing this will increase effici ency but will decrease effectiveness
final static Paint p = new Paint();
public static void justifyText(final TextView tv, final float origWidth){
String s = tv.getText().toString();
p.setTypeface(tv.getTypeface());
String [] splits = s.split(SYSTEM_NEWLINE);
float width = origWidth - 5;
for(int x = 0; x<splits.length;x++)
if(p.measureText(splits[x])>width){
splits[x] = wrap(splits[x], width, p);
String [] microSplits = splits[x].split(SYSTEM_NEWLINE);
for(int y = 0; y<microSplits.length-1;y++)
microSplits[y] = justify(removeLast(microSplits[y], " "), width, p);
StringBuilder smb_internal = new StringBuilder();
for(int z = 0; z<microSplits.length;z++)
smb_internal.append(microSplits[z]+((z+1<microSplits.length) ? SYSTEM_NEWLINE : ""));
splits[x] = smb_internal.toString();
}
final StringBuilder smb = new StringBuilder();
for(String cleaned : splits)
smb.append(cleaned+SYSTEM_NEWLINE);
tv.setGravity(Gravity.LEFT);
tv.setText(smb);
}
private static String wrap(String s, float width, Paint p){
String [] str = s.split("\\s"); //regex
StringBuilder smb = new StringBuilder(); //save memory
smb.append(SYSTEM_NEWLINE);
for(int x = 0; x<str.length; x++){
float length = p.measureText(str[x]);
String [] pieces = smb.toString().split(SYSTEM_NEWLINE);
try{
if(p.measureText(pieces[pieces.length-1])+length>width)
smb.append(SYSTEM_NEWLINE);
}catch(Exception e){}
smb.append(str[x] + " ");
}
return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
}
private static String removeLast(String s, String g){
if(s.contains(g)){
int index = s.lastIndexOf(g);
int indexEnd = index + g.length();
if(index == 0) return s.substring(1);
else if(index == s.length()-1) return s.substring(0, index);
else
return s.substring(0, index) + s.substring(indexEnd);
}
return s;
}
private static String justifyOperation(String s, float width, Paint p){
float holder = (float) (COMPLEXITY*Math.random());
while(s.contains(Float.toString(holder)))
holder = (float) (COMPLEXITY*Math.random());
String holder_string = Float.toString(holder);
float lessThan = width;
int timeOut = 100;
int current = 0;
while(p.measureText(s)<lessThan&&current<timeOut) {
s = s.replaceFirst(" ([^"+holder_string+"])", " "+holder_string+"$1");
lessThan = p.measureText(holder_string)+lessThan-p.measureText(" ");
current++;
}
String cleaned = s.replaceAll(holder_string, " ");
return cleaned;
}
private static String justify(String s, float width, Paint p){
while(p.measureText(s)<width){
s = justifyOperation(s,width, p);
}
return s;
}
public void updates()
{
DatabaseHandler db = new DatabaseHandler(this);
db.deletetable1();
db.deletetable2();
getjson();
//getjson2();
}
}
You are doing all your operation on Activity's Main Thread. Please use AsyncTask to download your data from web.
From Android 4.0 + Version, it is mandatory to use Worker Thread.
Async Task documentation Link: AsyncTask
ur executing network call on mainthread in android which is pausing mainthread for more than 5sec will cause ANR error or Force close.Make use of Asynctask.
public class WS_GetSMS_Asynctask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... params) {
//do your work here
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String jsonreader = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(jsonreader);
contacts = jsonObject.getJSONArray("tbl_content");
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
Log.d("contact", c.getString("content_name"));
Log.d("contact", c.getString("content"));
Log.d("contact", c.getString("content_id"));
Log.d("contact", c.getString("book_id"));
DatabaseHandler db = new DatabaseHandler(this);
db.addcontent(new data2(c.getInt("content_id"), c.getString("content_name"),c.getString("content"),c.getInt("book_id")));
}
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
return null;
}

Categories

Resources