Pobieranie lokalizacji - pomocy.

0

Witam pisze ponieważ znów potrzebuje pomocy.
Mam taki kody i potrzebuje pobrać lokalizacje zapisać w zmiennych "String latitude;String longitude;:" ale nie działa mi i już nie wiem czemu czy ktoś, błagam.

package com.example.osp_app;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.text.DateFormat;
import java.util.Date;

public class NextDepartureActivity extends AppCompatActivity implements LocationListener{

    DatabaseHelper mDatabaseHelper;

    private EditText dataEditText;
    private EditText commanderEditText;
    private EditText numberOfPeople;
    private EditText timeSelect;
    private EditText victimsEditText;
    private EditText typActionEditText;


    private Button confirmBtn;
    String latitude;
    String longitude;
    LocationManager locationManager;
    Criteria criteria;
    Location location;
    String bestProvider;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActivityCompat.requestPermissions(NextDepartureActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
        setContentView(R.layout.departure_new_layout);

        commanderEditText = (EditText) findViewById(R.id.comander);
        dataEditText = (EditText) findViewById(R.id.date);
        numberOfPeople = (EditText) findViewById(R.id.numberPeople);
        timeSelect = (EditText) findViewById(R.id.timeSelect);
        victimsEditText = (EditText) findViewById(R.id.victims);
        typActionEditText = (EditText) findViewById(R.id.typAcction);
        mDatabaseHelper = new DatabaseHelper(this);
        dataEditText.setText(getCurrentDate());
        timeSelect.setText(getCurrentTime());
        confirmBtn = (Button) findViewById(R.id.confirmBtn);

        confirmBtn.setOnClickListener(new View.OnClickListener() {
//            @SuppressLint("MissingPermission")
            @Override
            public void onClick(View v) {
                String commander = commanderEditText.getText().toString();
                String date = dataEditText.getText().toString();
                String people = numberOfPeople.getText().toString();
                String timeAction = timeSelect.getText().toString();
                String victims = victimsEditText.getText().toString();
                String type = typActionEditText.getText().toString();
                if (commanderEditText.length() != 0 && numberOfPeople.length() != 0) {
                    renderLocation();
                    mDatabaseHelper.AddData(commander, date, people, timeAction, victims, type, latitude, longitude);
                    commanderEditText.setText("");
                    numberOfPeople.setText("");
                    victimsEditText.setText("");
                    typActionEditText.setText("");
                    toastMessage("Twoje dane zotstały dodane!");

                } else {
                    toastMessage("Prosze wypełnij wszystkie pola!");
                }
            }
        });
    }
    private void toastMessage (String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    };
    private CharSequence getCurrentDate() {
        DateFormat dateFormat = DateFormat.getDateInstance();
        Date date = new Date();
        return  dateFormat.format(date);
    }
    private CharSequence getCurrentTime() {
        DateFormat timeFormat = DateFormat.getTimeInstance();
        Date time = new Date();
        return  timeFormat.format(time);
    }

    @SuppressLint("MissingPermission")
    private void renderLocation(){
        criteria = new Criteria();
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        bestProvider = locationManager.getBestProvider(criteria, true);
        location = locationManager.getLastKnownLocation(bestProvider);
        locationManager.requestLocationUpdates(bestProvider, 1000, 1, this);
        if ((location == null))
        {
            latitude = String.valueOf(location.getLatitude());
            longitude = String.valueOf(location.getLongitude());
            Toast.makeText(this,"Dostawca lokalizacji: "+ bestProvider.toLowerCase()
                    +"\nDługość geograficzna: " + String.valueOf(location.getLongitude())
                    +"\nSzerokość geograficzna: "+ String.valueOf(location.getLatitude()),Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this,"Błąd - sprawdź dane i spóbuj jeszcze raz.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onLocationChanged(Location location) { }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) { }
    @Override
    public void onProviderEnabled(String provider) { }
    @Override
    public void onProviderDisabled(String provider) { }

}


Dostaje też błędy:

Process: com.example.osp_app, PID: 3331
    java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
        at com.example.osp_app.NextDepartureActivity.renderLocation(NextDepartureActivity.java:112)
        at com.example.osp_app.NextDepartureActivity.access$600(NextDepartureActivity.java:25)
        at com.example.osp_app.NextDepartureActivity$1.onClick(NextDepartureActivity.java:75)
        at android.view.View.performClick(View.java:7140)
        at android.view.View.performClickInternal(View.java:7117)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27355)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7403)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
2

Masz czeski błąd. Wykonujesz operację, kiedy obiekt jest nullem.

 if ((location == null))
        {
            latitude = String.valueOf(location.getLatitude());
            longitude = String.valueOf(location.getLongitude());
0

Faktycznie!.
Ale niestety go to zmieni na:

if (!(location == null))
       {
           latitude = String.valueOf(location.getLatitude());
           longitude = String.valueOf(location.getLongitude());+

Wchodzi mi w elsa i dalej nic z tego. Jezu chyba jestem na to za głupi.

0

No to znaczy, że dla Twojej aplikacji nie jest znana lokalizacja. Masz pozwolenie od systemu na korzystanie z lokalizacji?

0

W manifest mam:

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I gdy pierwszy raz uruchamiam aplikacje po ponownym zainstalowaniu pyta o pozwolenie.

a za to zapytanie odpowiada :

ActivityCompat.requestPermissions(NextDepartureActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
0

W poszukiwaniu odpowiedzi jak zwykle pomógł stack :D

https://stackoverflow.com/questions/20438627/getlastknownlocation-returns-null

Nie wiem ostatecznie gdzie tkwił problem w kodzie napisanym wcześnie, ale najważniejsze że teraz działa.
Dzięki Michał Sikora za pomoc bo zacząłem szukać czemu zwraca mi nulla i w tedy trafiłem na stack..

Temat do zamknięcia.

1 użytkowników online, w tym zalogowanych: 0, gości: 1