2014-01-16 4 views
0

Я получаю информацию о погоде в своем приложении и работаю. Теперь я получаю исключение нулевого указателя, и я не уверен, почему, тем более, что он работал, и я не изменил ни одного из этого кода.Ошибка приложения Android с NullPointerException

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

+4

затем 'getLastKnownLocation' возвращает' null'. Если поставщик отключен или не использовался в последнее время, он возвращает «null». –

ответ

1

Если линия 48 вызывает проблемы, то, скорее всего, ваш место является нулевым. Это может быть null, если вы вызываете getLastKnownLocation(), в то время как поставщик отключен, как указано в документации по Android.

0

Я исправил это, добавив приемник местоположения.

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); 
Смежные вопросы