Lat / Long中的NullPointer异常

时间:2014-07-06 17:37:47

标签: android nullpointerexception latitude-longitude

当我试图从我的GPSTracker类中获取纬度和经度时,我得到了一个nullpointer异常。我正在尝试获取lat和long并将它们添加到我的url的末尾。任何人都可以帮助我吗?

这是我的错误。

    07-06 13:31:40.451: W/System.err(25222): java.net.MalformedURLException
07-06 13:31:40.451: W/System.err(25222):    at java.net.URL.<init>(URL.java:152)
07-06 13:31:40.451: W/System.err(25222):    at java.net.URL.<init>(URL.java:125)
07-06 13:31:40.451: W/System.err(25222):    at rafa.weatherapp.JSONParser.getJSONFromUrl(JSONParser.java:28)
07-06 13:31:40.451: W/System.err(25222):    at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:70)
07-06 13:31:40.451: W/System.err(25222):    at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:1)
07-06 13:31:40.451: W/System.err(25222):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-06 13:31:40.451: W/System.err(25222):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 13:31:40.451: W/System.err(25222):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-06 13:31:40.456: D/GPS Enabled(25222): GPS Enabled
07-06 13:31:40.456: W/System.err(25222):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-06 13:31:40.456: W/System.err(25222):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-06 13:31:40.461: W/System.err(25222):    at java.lang.Thread.run(Thread.java:841)
07-06 13:31:40.461: D/AndroidRuntime(25222): Shutting down VM
07-06 13:31:40.461: E/Buffer Error(25222): Error converting result java.lang.NullPointerException: lock == null
07-06 13:31:40.461: W/dalvikvm(25222): threadid=1: thread exiting with uncaught exception (group=0x41749c08)
07-06 13:31:40.461: E/JSON Parser(25222): Error parsing data org.json.JSONException: End of input at character 0 of 
07-06 13:31:40.461: E/AndroidRuntime(25222): FATAL EXCEPTION: main
07-06 13:31:40.461: E/AndroidRuntime(25222): Process: rafa.weatherapp, PID: 25222
07-06 13:31:40.461: E/AndroidRuntime(25222): java.lang.RuntimeException: Unable to start activity ComponentInfo{rafa.weatherapp/rafa.weatherapp.MainActivity}: java.lang.NullPointerException
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.ActivityThread.access$900(ActivityThread.java:175)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.os.Looper.loop(Looper.java:146)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.ActivityThread.main(ActivityThread.java:5602)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at java.lang.reflect.Method.invokeNative(Native Method)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at java.lang.reflect.Method.invoke(Method.java:515)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at dalvik.system.NativeStart.main(Native Method)
07-06 13:31:40.461: E/AndroidRuntime(25222): Caused by: java.lang.NullPointerException
07-06 13:31:40.461: E/AndroidRuntime(25222):    at rafa.weatherapp.GPSTracker.getLatitude(GPSTracker.java:91)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at rafa.weatherapp.MainActivity.onCreate(MainActivity.java:40)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.Activity.performCreate(Activity.java:5451)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
07-06 13:31:40.461: E/AndroidRuntime(25222):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
07-06 13:31:40.461: E/AndroidRuntime(25222):    ... 11 more

这是我的GPSTracker课程

    public class GPSTracker extends Service implements LocationListener{

private final Context mContext;
boolean isGPSEnabled = false;   
boolean isNetworkEnabled = false;   
boolean canGetLocation = false;

Location location;
Double latitude;
Double longitude;

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 meters 
private static final long  MIN_TIME_BW_UPDATES = 1000 * 60 * 1; //1 minute  
protected LocationManager locationManager;

public GPSTracker (Context context){
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        //getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if(!isGPSEnabled && !isNetworkEnabled){
            //no network provider is enabled
        } else{
            this.canGetLocation = true;
            // First get location from Network provider
            if (isNetworkEnabled){
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if(locationManager != null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if(location != null){
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isGPSEnabled){
                if(location == null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if(locationManager != null){
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if(location != null){
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e){
        e.printStackTrace();
    }
    return location;
}
/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();

        System.out.print(latitude);
    }

    return latitude;
}
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }
    return longitude;
}

/**
 * Function to show setting alert dialog
 */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    //Setting Dialog Title
    alertDialog.setTitle("GPS is settings");
    //Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings and enable GPS?"); 
    //Setting Icon to Dialog
    //alertDialog.setIcon(R.drawable.delete);
    //On Pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);

        }
    });
    //on pressing cancel button
    alertDialog.setNegativeButton("Cancel",  new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int which){
            dialog.cancel();
        }
    });
    //Showing alert message
    alertDialog.show();
}

public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}
@Override
public void onLocationChanged(Location location){       
}
@Override
public void onProviderDisabled(String provider){        
}
@Override
public void onProviderEnabled(String provider){     
}
@Override 
public void onStatusChanged(String provider, int status, Bundle extras){        
}
@Override
public IBinder onBind(Intent arg0){
    return null;
}   
}

这是我的MainActivity

    public class MainActivity extends Activity {

    TextView weather = null;
    TextView summary = null;
    TextView icon = null;
    JSONObject currentTemperature = null;
    String temperature = "";
    String weatherSummary = "";
    String weatherIcon = "";
    GPSTracker gps;
    double latitude = 0;
    double longitude = 0;
    String myUrl;


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

        weather = (TextView) findViewById(R.id.weather);
        summary = (TextView) findViewById(R.id.weather_summary);
        icon = (TextView) findViewById(R.id.string_icon);           
        // we will using AsyncTask during parsing 
        new AsyncTaskParseJson().execute();

        gps = new GPSTracker(MainActivity.this);
         myUrl = "https://api.forecast.io/forecast/5530508d3568e57848d53bf10cfade1f/" +
                gps.getLatitude() + "," + gps.getLongitude();
    }

   /* public String convertLatitude(){
        latitude = gps.getLatitude();
        String latitude2 = Double.toString(latitude);

        return latitude2;
    }*/

   /* public String convertLongitude(){
        longitude = gps.getLongitude();
        String longitude2 = Double.toString(longitude);

        return longitude2;
    }*/

    //do in background method to call JSON Parser
    public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
        final String TAG = "AsyncTaskParseJson.java";       

        @Override
        protected String doInBackground(String... arg0){

           try {


                // instantiate our json parser
                JSONParser jParser = new JSONParser();
                // get json string from url
                JSONObject json = jParser.getJSONFromUrl(myUrl);


                JSONObject current = json.getJSONObject("currently");
                temperature = current.getString("temperature");

                weatherSummary = current.getString("summary");
                weatherIcon = current.getString("icon");





            } catch (JSONException e) {
              e.printStackTrace();
            }
        return myUrl;


        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {

             weather.setText(temperature);
             summary.setText(weatherSummary);
             icon.setText(weatherIcon);

        }
    }
}

2 个答案:

答案 0 :(得分:1)

执行AsyncTask后设置myUrl。它可能为null,这就是你在logcat中得到NullPointerException的原因:

JSONObject json = jParser.getJSONFromUrl(myUrl);

at rafa.weatherapp.MainActivity$AsyncTaskParseJson.doInBackground(MainActivity.java:1)
E/Buffer Error(25222): Error converting result java.lang.NullPointerException: lock == null

答案 1 :(得分:1)

Caused by: java.lang.NullPointerException
    at rafa.weatherapp.GPSTracker.getLatitude(GPSTracker.java:91)

对于getLatitude()中的此NPE:您正在将null Double拆箱到原始double。从if (location != null)分支返回一个值,例如

public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();

        System.out.print(latitude);
        return 0.0; // or some other "special" value
    }

    return latitude;
}