Java Android应用程序因NullPointerException崩溃

Java Android应用程序因NullPointerException崩溃,java,android,nullpointerexception,Java,Android,Nullpointerexception,我正在我的应用程序中获取天气信息,并使其正常工作。现在我得到了一个空指针异常,我不知道为什么,特别是因为它正在工作,而且我没有更改任何代码 package com.kentuckyfarmbureau.kyfb; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Location; import android.l

我正在我的应用程序中获取天气信息,并使其正常工作。现在我得到了一个空指针异常,我不知道为什么,特别是因为它正在工作,而且我没有更改任何代码

package com.kentuckyfarmbureau.kyfb;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class WeatherLocation extends Activity
{
    EditText locationText;
    TextView label;
    Button getWeather;
    String enteredText;
    String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=%s&format=json&num_of_days=5&key=37a5fj42xpyptvjgkhrx5rwu";
    String newURL;
    String currentLocationText;
    LocationManager lm;
    Location location;
    double longitude;
    double latitude;
    String longString;
    String latString;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weatherlocation);

        locationText = (EditText) findViewById(R.id.locationTextView);
        label = (TextView) findViewById(R.id.label);
        getWeather = (Button) findViewById(R.id.showWeather);

        locationText.setText("Current Location");

         lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
         location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
         longitude = location.getLongitude();
         latitude = location.getLatitude();
         longString = String.valueOf(longitude);
         latString = String.valueOf(latitude);
         currentLocationText = (latString + "+" + longString);
         enteredText = currentLocationText;

         newURL = String.format(url, enteredText);

        locationText.setOnEditorActionListener(new OnEditorActionListener()
        {
             @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
            {
                 boolean handled = false;
                 if (actionId == EditorInfo.IME_ACTION_DONE)
                 {
                     if(locationText.getText().toString().equals("Current Location"))
                     {
                         lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                         location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                         longitude = location.getLongitude();
                         latitude = location.getLatitude();
                         longString = String.valueOf(longitude);
                         latString = String.valueOf(latitude);
                         currentLocationText = (latString + "+" + longString);
                         enteredText = currentLocationText;
                     }
                     else
                     {
                         enteredText = locationText.getText().toString();
                         enteredText = enteredText.replaceAll(" ", "+"); 
                     }
                     System.out.println(enteredText);

                    // hide the virtual keyboard
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 
                                              InputMethodManager.RESULT_UNCHANGED_SHOWN);

                    newURL = String.format(url, enteredText);
                    System.out.println("Formatted URL: " + newURL);
                     handled = true;
                 }

                 return handled;
            }
        });

        // Get Weather button
        getWeather.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent weather = new Intent(WeatherLocation.this, Weather.class);
                weather.putExtra("INTENT_KEY_URL", newURL);
                weather.putExtra("CURRENT_LOCATION", locationText.getText().toString());
                startActivity(weather);
            }
        });
    }
}

问题似乎在第48行,
longitude=location.getLongitude()

如果第48行是问题的根源,那么很可能是您的
位置为空。如android文档中所述,如果在禁用提供程序时调用getLastKnownLocation(),则该值可能为null

我通过添加一个位置侦听器修复了这个问题

final LocationListener locationListener = new LocationListener()
     {


    @Override
             public void onLocationChanged(Location currentLocation)
             {
                 latitude = currentLocation.getLatitude();
                 longitude = currentLocation.getLongitude();
             }
             public void onProviderDisabled(String provider) 
             {

             }
             public void onProviderEnabled(String provider) 
             {

             }
             public void onStatusChanged(String provider, int status, Bundle extras) 
             {

             }
         };
并加入:

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener);

然后
getLastKnownLocation
返回
null
。如果提供程序已禁用或最近未使用,它将返回
null