简体   繁体   中英

Using JSON for Lat Long on Google Maps

I am trying to get a JSON object from an API to use the Lat Long for each marker on google maps.

I can read the JSON in, as i have been able to put it in a listview, as a string, but cants seem to parse it into a double, it crashes every time.

Java:

package com.fly.plane;

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.fly.plane.R;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.Projection;
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 android.R.array;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MyMapActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get data JSON
    private static String url = "http://edmundgentle.com/snippets/flights/api.php";

    // JSON Node speeds
    private static final String TAG_data = "data";
    private static final String TAG_BEARING = "bearing";
    private static final String TAG_speed = "speed";
    private static final String TAG_ARR = "arr";
    private static final String TAG_DEP = "dep";
    private static final String TAG_DEP_LAT = "lat";
    private static final String TAG_DEP_LON = "lon";

    // data JSONArray
    JSONArray data = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    // Hashmap for ListView
    ArrayList<Double> ct;

    //final Handler handler;
    private GoogleMap mMap; 
    public static final LatLng dest(int i){
        final double latitude = -34.6 * i;
        final double longitude = 34.23 * i;
        return new LatLng(latitude, longitude);
    }
    public double latt = -15.48169437461;
    public double lng = -15.48169437461;
    public ArrayList<Integer> dLat;

    public String dlat;
    public String dlon;
    public String alat;
    public String alon;

    public boolean wait = true;

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

        contactList = new ArrayList<HashMap<String, String>>();

        ct = new ArrayList<Double>();

        //ListView lv = getListView();

      //create markers  
        new Getdata().execute();

        }

    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class Getdata extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MyMapActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            HTTPHandler sh = new HTTPHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, HTTPHandler.GET);

            Log.d("Response: ", "> " + jsonStr);
            boolean limit = false;
            int j = 0;
            if (jsonStr != null  ||  limit == false) {
                j++;
                //if (j > 20)limit = true;
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    data = jsonObj.getJSONArray(TAG_data);

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

                        // departure node is JSON Object
                        JSONObject dep = c.getJSONObject(TAG_DEP);
                        //String dtime = dep.getString(TAG_DEP_TIME);
                        String dlat = dep.getString(TAG_DEP_LAT);
                        String dlon = dep.getString(TAG_DEP_LON);

                        // arrival node is JSON Object
                        JSONObject arr = c.getJSONObject(TAG_ARR);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        contact.put(TAG_DEP_LAT, dlat );
                        contact.put(TAG_DEP_LON,dlon);                  

                        // adding contact to contact list
                        contactList.add(contact);

                        if (i== data.length()){
                            wait = false;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();            
            // use plane api for latlon

            mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            List<Marker> markers = new ArrayList<Marker>();
            for (int i = 0; i < 1 ; i++)
            {           
                // Now parse it in double

                double latitude = Double.parseDouble(dlat);
                double longitude = Double.parseDouble(dlon);

                //double latitude = 34 + i;
                //double longitude = 56 + i;

                    Marker marker =  mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(latitude, longitude))
                    //.position(new LatLng(latitude, longitude))
                    .title("Hello world")
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
                    markers.add(marker);            

                }  

            //setListAdapter(adapter);
        }

    }


}

Here is the Messages i receive:

02-17 14:58:06.635: D/dalvikvm(23289): GC_FOR_ALLOC freed 54K, 24% free 23518K/30936K, paused 24ms, total 24ms
02-17 14:58:06.645: I/dalvikvm-heap(23289): Grow heap (frag case) to 30.616MB for 4194320-byte allocation
02-17 14:58:07.726: D/dalvikvm(23289): GC_FOR_ALLOC freed 4204K, 23% free 23921K/30932K, paused 33ms, total 33ms
02-17 14:58:07.736: I/dalvikvm-heap(23289): Grow heap (frag case) to 31.010MB for 4194320-byte allocation
02-17 14:58:08.517: D/dalvikvm(23289): GC_FOR_ALLOC freed 4293K, 23% free 23831K/30932K, paused 29ms, total 30ms
02-17 14:58:08.527: I/dalvikvm-heap(23289): Grow heap (frag case) to 30.922MB for 4194320-byte allocation
02-17 14:58:09.227: D/dalvikvm(23289): GC_FOR_ALLOC freed 4194K, 23% free 23868K/30932K, paused 27ms, total 27ms
02-17 14:58:09.237: I/dalvikvm-heap(23289): Grow heap (frag case) to 30.958MB for 4194320-byte allocation
02-17 14:58:09.968: D/dalvikvm(23289): GC_FOR_ALLOC freed 4149K, 23% free 23884K/30932K, paused 25ms, total 26ms
02-17 14:58:09.968: I/dalvikvm-heap(23289): Grow heap (frag case) to 30.973MB for 4194320-byte allocation
02-17 14:58:10.118: D/dalvikvm(23289): GC_FOR_ALLOC freed 4377K, 24% free 23626K/30932K, paused 25ms, total 25ms
02-17 14:58:10.128: I/dalvikvm-heap(23289): Grow heap (frag case) to 30.721MB for 4194320-byte allocation
02-17 14:58:10.439: D/dalvikvm(23289): GC_FOR_ALLOC freed 4508K, 24% free 23642K/30932K, paused 24ms, total 25ms
02-17 14:58:13.532: D/dalvikvm(23289): GC_FOR_ALLOC freed 2705K, 24% free 23782K/30932K, paused 26ms, total 27ms
02-17 14:58:25.974: D/dalvikvm(23289): GC_FOR_ALLOC freed 1949K, 20% free 24954K/30932K, paused 37ms, total 38ms
02-17 14:58:32.340: I/dalvikvm(23289): threadid=3: reacting to signal 3
02-17 14:58:32.430: I/dalvikvm(23289): Wrote stack traces to '/data/anr/traces.txt'
02-17 14:58:39.787: D/dalvikvm(23289): GC_FOR_ALLOC freed 1959K, 17% free 26506K/31692K, paused 51ms, total 51ms
02-17 14:58:54.081: D/dalvikvm(23289): GC_FOR_ALLOC freed 2235K, 17% free 28302K/33764K, paused 67ms, total 69ms
02-17 14:59:12.779: D/AndroidRuntime(23289): Shutting down VM
02-17 14:59:12.779: W/dalvikvm(23289): threadid=1: thread exiting with uncaught exception (group=0x41890898)
02-17 14:59:12.829: E/AndroidRuntime(23289): FATAL EXCEPTION: main
02-17 14:59:12.829: E/AndroidRuntime(23289): java.lang.NullPointerException
02-17 14:59:12.829: E/AndroidRuntime(23289):    at java.lang.StringToReal.parseDouble(StringToReal.java:244)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at java.lang.Double.parseDouble(Double.java:295)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at com.fly.plane.MyMapActivity$Getdata.onPostExecute(MyMapActivity.java:222)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at com.fly.plane.MyMapActivity$Getdata.onPostExecute(MyMapActivity.java:1)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at android.os.AsyncTask.finish(AsyncTask.java:631)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at android.os.Looper.loop(Looper.java:137)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at android.app.ActivityThread.main(ActivityThread.java:5419)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at java.lang.reflect.Method.invokeNative(Native Method)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at java.lang.reflect.Method.invoke(Method.java:525)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
02-17 14:59:12.829: E/AndroidRuntime(23289):    at dalvik.system.NativeStart.main(Native Method)

I think I have figured out

            double latitude = Double.parseDouble(dlat);
            double longitude = Double.parseDouble(dlon);

Seem to cause the issue, as if i change them to be a set value, it works fine.

Any help would be appreciated, ive spent a few days on this and cant figure out why it doesn't work!

Cheers Phil.

inside your doInBackground method you recreate your dlat and dlong strings. they have nothing to do with the global dlat and dlong variables you created in the top of the code.

 String dlat = dep.getString(TAG_DEP_LAT);
 String dlon = dep.getString(TAG_DEP_LON);

but inside your onPostExecute you try to access the global variables you created in the beginning but it looks like you never initialized them.

  double latitude = Double.parseDouble(dlat);
  double longitude = Double.parseDouble(dlon);

thats why you get a nullpointer.

edit: quick fix - try replacing (within the doInBackground method)

String dlat = dep.getString(TAG_DEP_LAT);
String dlon = dep.getString(TAG_DEP_LON);

by

dlat = dep.getString(TAG_DEP_LAT);
dlon = dep.getString(TAG_DEP_LON);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM