错误:尝试调用虚拟方法'double.android.location.Location.getLatitude()'

时间:2020-04-28 13:47:49

标签: java android android-studio debugging location

有人可以帮助我解决问题吗?

我想在我的应用程序中添加Weather。我正在使用OpenWeatherMap API。 问题是:

启动应用程序时,它会崩溃,因为纬度和经度设置为null,但是为什么呢? 当我检查电话是否给我一些经纬度时,是的,它给了我。

问题是这个 (Common.current_location.getLatitude()), String.valueOf(Common.current_location.getLongitude())

public class ActivitytoActivity extends AppCompatActivity {

    public ActivitytoActivity() {
        compositeDisposable = new CompositeDisposable();
        Retrofit retrofit   = RetrofitClient.getInstance();
        mService = retrofit.create(IOpenWeatherMap.class);
    }

    //___________Navigation_________________
    ImageView imgView;
    CardView  cardView_music;
    CardView cardView_vid;
    CardView cardView_live;
    CardView cardView_eat;
    CardView cardView_drive;
    CardView cardView_shop;
    CardView cardView_pay;
    CardView cardView_date;

    //____________Weather ID________________
    ImageView iconweather;
    TextView tempweather;
    ProgressBar loading_weather;
    LinearLayout linlayweather;
    LinearLayout linlayall;
    CardView     cardview_weather;

    CompositeDisposable compositeDisposable;
    IOpenWeatherMap     mService;

    //____________Weather API_________________
    private FusedLocationProviderClient fusedLocationProviderClient;
    private LocationCallback            locationCallback;
    private LocationRequest             locationRequest;



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

        //_________Initialize for Weather_______________

        linlayweather    = findViewById(R.id.linlayweather);
        cardview_weather = findViewById(R.id.cardview_weather);

        iconweather      = (ImageView)    findViewById(R.id.iconweather);
        tempweather      = (TextView)     findViewById(R.id.tempweather);
        loading_weather  = (ProgressBar)  findViewById(R.id.loading_weather);
        linlayall        = (LinearLayout) findViewById(R.id.linlayall);

        getWeatherInformation();

        //_________Request Permissions (Weather)____________

        Dexter.withContext(this)
                .withPermissions(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport
                                                             report) {

                        if (report.areAllPermissionsGranted()) {
                            buildLocationRequest();
                            buildLocationCallBack();

                            if (ActivityCompat.checkSelfPermission(ActivitytoActivity.this,
                                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.
                                    PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                                    ActivitytoActivity.this, Manifest.permission.
                                            ACCESS_COARSE_LOCATION) != PackageManager.
                                    PERMISSION_GRANTED) {

                                return;
                            }else {

                            }

                            fusedLocationProviderClient = LocationServices.
                                    getFusedLocationProviderClient(ActivitytoActivity.this);
                            fusedLocationProviderClient.requestLocationUpdates(locationRequest,
                                    locationCallback, Looper.myLooper());
                        }


                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list,
                                                                   PermissionToken permissionToken) {

                        Snackbar.make(linlayall, "Permission Denied", Snackbar.LENGTH_LONG)
                                .show();
                    }
                }).check();


//__________Initialize the Navigation CardViews_____________

        imgView = (ImageView) findViewById(R.id.backArrow_img_activitytoactivity);
        cardView_music = (CardView) findViewById(R.id.cardview_spotify);
        cardView_vid = (CardView) findViewById(R.id.cardview_youtube);
        cardView_live = (CardView) findViewById(R.id.cardview_twitch);
        cardView_eat = (CardView) findViewById(R.id.cardview_lieferando);
        cardView_drive = (CardView) findViewById(R.id.cardview_uber);
        cardView_shop = (CardView) findViewById(R.id.cardview_amazon);
        cardView_pay = (CardView) findViewById(R.id.cardview_paypal);
        cardView_date = (CardView) findViewById(R.id.cardview_tinder);

//__________Navigation for the CardViews______________

        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ActivitytoActivity.this,
                        MainActivity.class);
                startActivity(intent);
            }
        });

        cardView_music.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(ActivitytoActivity.this, Music.class);
                startActivity(intent1);
            }
        });

        cardView_vid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(ActivitytoActivity.this, Videos.class);
                startActivity(intent2);
            }
        });

        cardView_live.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent3 = new Intent(ActivitytoActivity.this, Live.class);
                startActivity(intent3);
            }
        });

        cardView_eat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent4 = new Intent(ActivitytoActivity.this, Eat.class);
                startActivity(intent4);
            }
        });

        cardView_drive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent5 = new Intent(ActivitytoActivity.this, Drive.class);
                startActivity(intent5);
            }
        });

        cardView_shop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent6 = new Intent(ActivitytoActivity.this, Shop.class);
                startActivity(intent6);
            }
        });

        cardView_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent7 = new Intent(ActivitytoActivity.this, Pay.class);
                startActivity(intent7);
            }
        });

        cardView_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent8 = new Intent(ActivitytoActivity.this, Date.class);
                startActivity(intent8);
            }
        });


    }

    private void getWeatherInformation() {
        compositeDisposable.add(mService.getWeatherByLatLng(String.valueOf(Common.current_location.getLatitude()),
                String.valueOf(Common.current_location.getLongitude()),
                Common.APP_ID,
                "metric")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<WeatherResult>() {
                    @Override
                    public void accept(WeatherResult weatherResult) throws Exception {

                        //Load Image
                        Picasso.get().load(new StringBuilder("https://openweathermap.org/img/wn/")
                        .append(weatherResult.getWeather().get(0).getIcon())
                        .append(".png").toString()).into(iconweather);

                        //Load Information
                        tempweather.setText(new StringBuilder(String.valueOf(weatherResult.getMain()
                        .getTemp())).append("°C").toString());

                        //Display panel
                        cardview_weather.setVisibility(View.VISIBLE);
                        loading_weather.setVisibility(View.GONE);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Toast.makeText(ActivitytoActivity.this, ""
                                +throwable.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
        );
    }

    //___________Request Permissions Methods____________

    private void buildLocationCallBack() {
        locationCallback = new LocationCallback(){

            @Override
            public void onLocationResult(LocationResult locationResult){
                super.onLocationResult(locationResult);

                Common.current_location = locationResult.getLastLocation();

                linlayall = (LinearLayout)findViewById(R.id.linlayall);

                //Log
                Log.d("Location", locationResult.getLastLocation().getLatitude()+"/"
                +locationResult.getLastLocation().getLongitude());

            }

        };
    }

    private void buildLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(5000);
        locationRequest.setFastestInterval(3000);
        locationRequest.setSmallestDisplacement(10.0f);
    }
}

那是我的错误

java.lang.RuntimeException: Unable to start activity ComponentInfo{company.rw.rexx/company.rw.rexx.ActivitytoActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at company.rw.rexx.ActivitytoActivity.getWeatherInformation(ActivitytoActivity.java:224)
        at company.rw.rexx.ActivitytoActivity.onCreate(ActivitytoActivity.java:98)
        at android.app.Activity.performCreate(Activity.java:7183)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6944) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

0 个答案:

没有答案
相关问题