2016-09-25 94 views
-2

Hello Im newebie to android programming。在這裏,我不斷收到nullreference錯誤。我正在使用Google Map API並使用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」 請幫助我..

林正從我的日誌

此錯誤
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監視器」的東西,將會有一個名爲logcat的標籤。 –

回答

0

看來您從Google Analytics獲得的位置對象爲空

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

添加回調googleclient

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

你應該檢查,如果該位置是空,如果是這樣的請求位置更新。

+0

謝謝回答我的問題@Adam 但我已經實現了這個方法,但仍然得到錯誤 我沒有在前面的代碼段中顯示 我將編輯我的代碼段代碼,以便我可以向您顯示我的所有活動代碼 謝謝 –

+0

您應該在此處閱讀有關空指針的更多信息。 http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it –

相關問題