简体   繁体   English

NullPointerException导致Android应用崩溃

[英]Android App Crash with NullPointerException

I am getting weather info in my app and had it working. 我在我的应用程序中获取天气信息并使其正常运行。 Now I am getting a null pointer exception and I'm not sure why, especially since it was working and I haven't changed any of this code. 现在,我得到了一个空指针异常,我不确定为什么,特别是因为它正在工作并且我没有更改任何代码。

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);
            }
        });
    }
}

The problem seems to be line 48, longitude = location.getLongitude(); 问题似乎出在第48行, longitude = location.getLongitude();

If line 48 is causing the issues, then most likely your location is null. 如果第48行引起了问题,则您的位置很可能为空。 This can be null if you call getLastKnownLocation() while the provider is disabled as noted in the android documentation. 如果您按照Android文档中的说明禁用了提供程序,则调用getLastKnownLocation()时可以为null。

I fixed this by adding a location listener. 我通过添加位置侦听器来解决此问题。

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) 
             {

             }
         };

And adding: 并添加:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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