2016-09-25 2 views
-2

Hello Im newebie to android programming. Я продолжаю получать ошибку при отсутствии ошибок, когда здесь. Я использую API Карт Google и использую azure webservice. Я новый для stackoverflow тоже, поэтому мой вопрос в беспорядке, и моя грамматика тоже.Я получаю сообщение об ошибке «java.lang.NullPointerException: попытка вызвать виртуальный метод»

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 

private GoogleMap mMap; 
private double myLatitude, myLongitude; 
private String myUrl; 
private static Context context; 
private Button set; 
private EditText skillCari; 
private TextView latlng; 
private List<People> finalPeople = new ArrayList<>(); 
private List<People> myPeople = new ArrayList<>(); 
private double currentLatitude, currentLongitude; 
private GoogleApiClient mGoogleApiClient; 
private LocationRequest mLocationRequest; 
public Activity currentActivity = this; 
private double minLatitude, maxLatitude, minLongitude, maxLongitude; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 
    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
    MapsActivity.context = getApplicationContext(); 

    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API).build(); 

    mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
      .setInterval(10 * 1000).setFastestInterval(1 * 1000); 
    latlng = (TextView) findViewById(R.id.Latlng); 
    RecyclerView myRecyle = (RecyclerView) findViewById(R.id.RecycleView); 
    myRecyle.setHasFixedSize(true); 
    myRecyle.setLayoutManager(new LinearLayoutManager(this)); 
    final AdapterCard myCard = new AdapterCard(); 
    myRecyle.setAdapter(myCard); 
    skillCari = (EditText) findViewById(R.id.skill_cari); 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    final Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    set = (Button) findViewById(R.id.butSearch); 
    set.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      myCard.clearData(); 
      BengService service = ServiceFactory.createRetrofitService(BengService.class, BengService.BENG_SERVICE); 
      service.getSkilledUser(skillCari.getText().toString()) 
        .subscribeOn(Schedulers.newThread()) 
        .observeOn(AndroidSchedulers.mainThread()) 
        .subscribe(new Subscriber<List<People>>() { 
         @Override 
         public void onCompleted() { 
         } 

         @Override 
         public void onError(Throwable e) { 
          Log.e("GithubDemo", e.getMessage()); 
          Log.e("GithubDemo", e.toString()); 
         } 

         @Override 
         public void onNext(List<People> peoples) { 
          finalPeople = SaringPeople(peoples, location.getLatitude(), location.getLongitude()); 
          myCard.addData(finalPeople); 
          TambahMap(mMap, finalPeople); 


         } 
        }); 
     } 
    }); 


} 

public ArrayList<People> SaringPeople(List<People> people, double userLatitude, double userLongitude) { 
    myLatitude = userLatitude; 
    myLongitude = userLongitude; 
    myPeople = people; 
    ArrayList<People> peopleSample = new ArrayList<>(); 
    double R = 6371; 
    double radius = 0.300; 
    double longitudeMin, longitudeMaks, latitudeMin, latitudeMaks; 
    longitudeMin = (userLongitude - Math.toDegrees(radius/R/Math.cos(Math.toRadians(userLatitude)))); 
    longitudeMaks = (userLongitude + Math.toDegrees(radius/R/Math.cos(Math.toRadians(userLatitude)))); 
    latitudeMaks = (userLatitude + Math.toDegrees(radius/R)); 
    latitudeMin = (userLatitude - Math.toDegrees(radius/R)); 
    for (People myPeople : people) { 
     if ((myPeople.getLatitude() <= latitudeMaks) && (myPeople.getLatitude() >= latitudeMin) && (myPeople.getLongitude() <= longitudeMaks) && (myPeople.getLongitude() >= longitudeMin)) { 
      peopleSample.add(myPeople); 
     } 
     else{} 
    } 
    return peopleSample; 

} 

public void TambahMap(GoogleMap googleMap, List<People> people) { 
    Bitmap urlImage; 
    for (People mypeople : people) { 
     urlImage = getBitmap(mypeople.getPhotoURL()); 
     LatLng haha = new LatLng(mypeople.getLatitude(), mypeople.getLongitude()); 
     googleMap.addMarker(new MarkerOptions().position(haha).title(mypeople.getFullName()).icon(BitmapDescriptorFactory.fromBitmap(urlImage))); 

    } 
} 

public Bitmap getBitmap(String imageUrl) { 
    try { 
     URL url = new URL(imageUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.connect(); 
     InputStream input = connection.getInputStream(); 
     Bitmap bitmap = BitmapFactory.decodeStream(input); 
     return bitmap; 

    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } 
} 

    @Override 
public void onLocationChanged(Location location) { 
    currentLatitude = location.getLatitude(); 
    currentLongitude = location.getLongitude(); 
} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
    if (location == null){ 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } else { 
     currentLatitude = location.getLatitude(); 
     currentLongitude = location.getLongitude(); 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

Я пытаюсь работает метод "TambahMap" и "SaringPeople", нажав кнопку "butSearch" пожалуйста, помогите мне ..

Im получаю эту ошибку из моего журнала

09-26 00:16:04.018 6337-6337/com.example.beng.bengtuak E/GithubDemo: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 
09-26 00:16:04.018 6337-6337/com.example.beng.bengtuak E/GithubDemo: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 
09-26 00:16:16.386 6337-6337/com.example.beng.bengtuak E/GithubDemo: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 
09-26 00:16:16.386 6337-6337/com.example.beng.bengtuak E/GithubDemo: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference 
+0

Извините, но без трассировки стека вы не получите ответа –

+0

можете объяснить, как я могу использовать трассировку стека? спасибо –

+0

Предполагая, что вы используете Android-студию, вы должны иметь вещь под названием «Android Monitor», там будет вкладка logcat. –

ответ

0

Похоже, что объект местоположения, который вы получаете из googleclient, имеет значение null

final Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 

Добавить функцию обратного вызова для googleclient

public void onConnected(@Nullable Bundle bundle) { 
     mLastLocation = LocationServices.FusedLocationApi .getLastLocation(mGoogleApiClient); 
    } 

Вы должны проверить, если это место является недействительным, и если да обновлений запрос о местоположении.

+0

Спасибо за ответ на мой вопрос @Adam но я внедрил этот метод, но все еще получает ошибку Я не показывал его в своем более раннем коде кода . Я отредактирую свой код фрагмента, чтобы я мог показать вам весь код своей деятельности. спасибо –

+0

Здесь вы должны узнать больше о nullpointer. http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it –

Смежные вопросы