2016-10-06 3 views
0

사용자의 위치, 특히 도시를 가져 오려고합니다. 앱이 런타임에 권한을 요청합니다. 그러나 위치를 ArrayList에 넣으려고하면 null 객체 참조 오류가 발생합니다.android : 위치가 null 객체 참조 오류를 반환합니다.

아래에서 구체적인 내용을 말씀 드리겠습니다.

내가 뭘 잘못하고 있니?

ERROR 널 객체 참조에 '를 java.util.List android.location.Geocoder.getFromLocation (더블 더블 INT)'의 가상 메소드를 호출

시도

import android.Manifest; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Address; 
import android.location.Criteria; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.provider.Settings; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AlertDialog; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Locale; 

public class PhoneList extends AppCompatActivity implements LocationListener { 


    LocationManager locationManager; 
    private String provider; 
    public final static int MY_PERMISSIONS_REQUEST_READ_LOCATION = 1; 
    public double myLng; 
    public double myLat; 
    List addresses = new ArrayList(); 

    public Geocoder myGeo; 

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

     if (1 == 0) { 
      showAlert(); 
     } else { 
      locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      Criteria criteria = new Criteria(); 
      provider = locationManager.getBestProvider(criteria, false); 
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       GetLocationPermission(); 

       return; 
      } 
      locationManager.requestLocationUpdates(provider, 0, 0, this); 
      Location location = locationManager.getLastKnownLocation(provider); 
      onLocationChanged(location); 

      myLat = location.getLatitude(); 
      myLng = location.getLongitude(); 
     } 

    } 

    private void showAlert() { 
     final AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
     dialog.setTitle("Enable Location") 
       .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + 
         "use this app") 
       .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
         Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(myIntent); 
        } 
       }) 
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
        } 
       }); 
     dialog.show(); 
    } 

    public void GetLocationPermission(){ 
     if (ContextCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_READ_LOCATION); 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_READ_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        System.out.println("Yes"); 
       } else { 

        System.out.println("boo"); 
       } 
       return; 
      } 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     try { 

//ERROR IS ON THIS LINE 
      addresses = myGeo.getFromLocation(location.getLatitude(), location.getLongitude(), 10); 

     } catch (IOException e) { 
      Log.e("LocateMe", "Could not get Geocoder data", e); 

     } 
    } 

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

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 

    } 
} 

답변

1

myGeo 참조를 초기화하지 않으 셨습니다.

수정하려면 getFromLocation()으로 전화하기 전에 초기화하십시오. 부수적으로, locationManager.getLastKnownLocation() 호출은 null을 반환 할 가능성이 있기 때문에 Location이 null이 아닌지도 확인해야합니다.

@Override 
public void onLocationChanged(Location location) { 
    try { 
     //Add initialization: 
     myGeo = new Geocoder(this, Locale.getDefault()); 
     //Make sure that the Location is not null: 
     if (location != null) { 
      addresses = myGeo.getFromLocation(location.getLatitude(), location.getLongitude(), 10); 
     } 

    } catch (IOException e) { 
     Log.e("LocateMe", "Could not get Geocoder data", e); 

    } 
} 
+0

당신은 아름다운 인간입니다! 고맙습니다! –

관련 문제