0

I try for days to get my current location on android studio but I always get a null location. I already try lot of things like this solution : I can't get location on Android real phone or this one : getlastknownlocation always return null after I re-install the apk file via eclipse but that does not work... I have managed the location on the Android Device Monitor like this : Android Device Monitor location

And the GPS is enable in the virtual device... It's not working on my phone too. So this is my code

public class MyLocation {
private double longitude;
private double latitude;
private LocationManager locationManager;
private Context context;
private LocationListener locationListener; 

public MyLocation(Context context){
    this.context = context;
    this.locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
}
public void findLocation() {
        String location_context = context.LOCATION_SERVICE;
        locationManager = (LocationManager) context.getSystemService(location_context);

        List<String> providers = locationManager.getProviders(true);

        for (String provider : providers) {
            try {
                Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    longitude = location.getLongitude();
                    latitude = location.getLatitude();
                }
                locationManager.requestLocationUpdates(provider, 1000, 0, locationListener);
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
    }

public double getLongitude() {
    return longitude;
}

public void setLongitude(double longitude) {
    this.longitude = longitude;
}

public double getLatitude() {
    return latitude;
}

public void setLatitude(double latitude) {
    this.latitude = latitude;
}

Thanks a lot in advance

EDIT : I forgot to say that I have the permissions in my manifest :

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

EDIT : this is my activity

public class CameraActivity extends Activity implements SingleLocationProvider.OnLocationProviderListener {
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private ImageView imageView;
    private Button backButton;
    private Button sendButton;
    private Picture picture;
    private TextView title;
    private TextView comment;
    private String email;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        picture = new Picture();
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            email = extras.getString("email");
        }
        else{
            email = "no email";
        }
        setContentView(R.layout.activity_camera);
        title = (EditText) findViewById(R.id.title);
        title.setText("comments");
        comment = (EditText) findViewById(R.id.comment);
        comment.setText("test");
        imageView = (ImageView) findViewById(R.id.imageView);
        backButton = (Button) findViewById(R.id.backButton);
        sendButton = (Button) findViewById(R.id.sendButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickBackButton(v);
            }
        });
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSendButton(v);
            }
        });

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            imageView.setDrawingCacheEnabled(true);
            imageView.buildDrawingCache(true);
            imageView.setImageBitmap(imageBitmap);
            imageView.setDrawingCacheEnabled(false);
        }
        else if(requestCode == 2 && resultCode == 2){
            title.setText("");
            comment.setText("");
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
        else{
            backToPreviousActivity();
        }
    }

    private void backToPreviousActivity(){
        Intent intent = new Intent(this, ConnectionActivity.class);
        //Clear all the activities
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickBackButton(View view) {
        Intent intent = new Intent(this, ConnectionActivity.class);
        //Clear all the activities
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void onClickSendButton(View view) {
        if(comment.getText().toString().isEmpty() || title.getText().toString().isEmpty()){
            Toast.makeText(this, R.string.errorSendPicture, Toast.LENGTH_LONG)
                    .show();
        }else {
            imageView.buildDrawingCache();
            Bitmap bmap = imageView.getDrawingCache();
            String stringImage = BitmapToString(bmap);
            setGpsCoordinates(picture);
            picture.setPictureString(stringImage);
            picture.setEmailPerson(email);
            picture.setComment(comment.getText().toString());
            picture.setName(title.getText().toString());
            //sendPicture();
            new HttpRequestTask().execute();
        }
    }



    private class HttpRequestTask extends AsyncTask<Void, Void, HttpResponse> {
        //private void sendPicture() {
        @Override
        protected HttpResponse doInBackground(Void... params) {
            RestTemplate restTemplate = new RestTemplate();
            final String url = "http://192.168.128.13:8081/DumontPerat/sharesite/picture/";
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setHeader("content-type", "application/json; charset=UTF-8");

            JSONObject dato = new JSONObject();
            try {
                dato.put("name", picture.getName());
                dato.put("pictureString", picture.getPictureString());
                dato.put("comment", picture.getComment());
                dato.put("emailPerson", picture.getEmailPerson());
                StringEntity entity = new StringEntity(dato.toString());
                post.setEntity(entity);
                HttpResponse resp = httpClient.execute(post);
                return resp;
            } catch (JSONException ex) {
            } catch (UnsupportedEncodingException ex) {
            } catch (IOException ex) {
            } catch (Exception e) {
                Log.e("ConnectionActivity", e.getMessage(), e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(HttpResponse response) {
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                goToLastActivity();
            }
            else{
                createToastProblem();
            }
        }
    }

    private void goToLastActivity(){
        Intent intent = new Intent(this, LastActivity.class);
        startActivityForResult(intent, 2);
    }

    private void setGpsCoordinates(Picture picture){
        /*MyLocation myLocation = new MyLocation(this.getApplicationContext());
        myLocation.findLocation();
            picture.setLatitude((float) myLocation.getLatitude());
            picture.setLongitude((float) myLocation.getLongitude());*/
        try {
            SingleLocationProvider mLocationProvider = new SingleLocationProvider(this);
            mLocationProvider.setOnLocationProviderListener(this);
            mLocationProvider.setTimeout(20000);
            mLocationProvider.requestLocation();
            Location l = mLocationProvider.getLastKnownLocation();
            if(l != null) {
                picture.setLatitude((float) l.getLatitude());
                picture.setLongitude((float) l.getLongitude());
            }
        }catch(Exception ex){}
    }

    private void createToastProblem(){
        Toast.makeText(this, R.string.errorConnection, Toast.LENGTH_LONG).show();
    }

    private String BitmapToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String temp = Base64.encodeToString(b, Base64.DEFAULT);
        return temp;
    }

    @Override
    public void onLocationStartedSeeking() {

    }

    @Override
    public void onLocationStoppedSeeking() {

    }

    @Override
    public void onLocationFound(Location location) {
        picture.setLatitude((float) location.getLatitude());
        picture.setLongitude((float) location.getLongitude());
    }

    @Override
    public void onLocationNotFound() {

    }

    @Override
    public void onGPSProviderDisabled() {

    }
}

EDIT: Ok, I'm stupid, the location has always been working... I forget to send my information to my Rest service it's why I was always 0 to the latitude and longitude... So stupid.. Thank you all !

Community
  • 1
  • 1
Isadora Perat
  • 93
  • 3
  • 13

3 Answers3

3

Ok, I'm stupid, the location has always been working... I forget to send my information to my Rest service it's why I was always 0 to the latitude and longitude... So stupid.. Thank you all !

Isadora Perat
  • 93
  • 3
  • 13
0
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import java.util.Timer;
import java.util.TimerTask;

@SuppressWarnings("ResourceType")
public class SingleLocationProvider {

    private int mTimeout = 5000;
    private LocationManager mLocationManager;
    private SingleLocationListener mListener;
    private Location mLastKnownLocation;

    private Timer mTimer;
    private RequestTimerTask mTimerTask;

    private OnLocationProviderListener mCallback;

    public SingleLocationProvider(Context context) {
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        mListener = new SingleLocationListener();

        mTimer = new Timer();
        mTimerTask = new RequestTimerTask();
    }

    public void requestLocation() {
        startSeeking();
    }

    public boolean checkGPSProviderEnabled() {
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (mCallback != null) {
                mCallback.onGPSProviderDisabled();
            }

            return false;
        }

        return true;
    }

    public void cancel() {
        stopSeeking();
    }

    private void startSeeking() {
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (mCallback != null) {
                mCallback.onGPSProviderDisabled();
                return;
            }
        }

        if (mCallback != null){
            mCallback.onLocationStartedSeeking();
        }

        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Integer.MAX_VALUE, Integer.MAX_VALUE, mListener);

        mTimer.schedule(mTimerTask, mTimeout);
    }

    private void stopSeeking() {
        mLocationManager.removeUpdates(mListener);

        mTimer.purge();
        mTimer.cancel();

        if (mCallback != null){
            mCallback.onLocationStoppedSeeking();
        }
    }

    public void setTimeout(int timeout) {
        mTimeout = timeout;
    }

    public void setOnLocationProviderListener(OnLocationProviderListener callback) {
        mCallback = callback;
    }

    public Location getLastKnownLocation() {
        return mLastKnownLocation;
    }

    private class SingleLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {

                mLastKnownLocation = location;

                if (mCallback != null) {
                    mCallback.onLocationFound(location);
                }

                stopSeeking();
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // Empty Block
        }

        @Override
        public void onProviderEnabled(String provider) {
            // Empty Block
        }

        @Override
        public void onProviderDisabled(String provider) {
            // Empty Block
        }
    }

    private class RequestTimerTask extends TimerTask {

        @Override
        public void run() {
            mLocationManager.removeUpdates(mListener);

            if (mCallback != null) {
                mCallback.onLocationNotFound();
            }

            stopSeeking();
        }
    }

    public interface OnLocationProviderListener {
        void onLocationStartedSeeking();

        void onLocationStoppedSeeking();

        void onLocationFound(Location location);

        void onLocationNotFound();

        void onGPSProviderDisabled();
    }

}

and this is the usage

SingleLocationProvider mLocationProvider = new SingleLocationProvider(this);
mLocationProvider.setOnLocationProviderListener(this);
mLocationProvider.setTimeout(20000);
mLocationProvider.requestLocation();

Add these to your manifest for permission

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

You can test it on real device. Feel free to use it :)

Hope it helps.

Emre Aktürk
  • 3,306
  • 2
  • 18
  • 30
  • This line is not working : mLocationProvider.setOnLocationProviderListener(this);, I try this (SingleLocationProvider.OnLocationProviderListener) this but this does not work too... – Isadora Perat Dec 09 '15 at 13:25
  • Just keep this line and "mLocationProvider.setOnLocationProviderListener(this);" and let your activity or class implements "SingleLocationProvider.OnLocationProviderListener". – Emre Aktürk Dec 09 '15 at 13:27
  • While you have this line "mLocationProvider.setOnLocationProviderListener(this);" Alt + Enter to it and choose let the implement blah blah. – Emre Aktürk Dec 09 '15 at 13:28
  • Try this but when I want to get the location it's still null... :( Don't know what's wrong... – Isadora Perat Dec 09 '15 at 13:39
  • I hope you dont this class in your "MyLocation" class. Can you post your activity? – Emre Aktürk Dec 09 '15 at 13:41
  • No I did not :) I post my activity, thank you a lot for your responses – Isadora Perat Dec 09 '15 at 17:50
  • You shouldnt call .getLastKnownLocation because there is no known location since your phone or emulator booted newly and did not know previous location. On the other hand, after calling "mLocationProvider.requestLocation()", "onLocationFound" or "onLocationNotFound" methods will trigger. Add toasts or logs to check which states you are in. Another control point, after you called "mLocation.requestLocation", you should see GPS icon on status bar of your phone. That means its searching for your location. You can help it to find faster to move near a windows or outdoor :) – Emre Aktürk Dec 09 '15 at 18:06
  • I did the getLastKnownLocation method after try without it... Because I can't get the location and it was a test... I really don't understand what's the problem... – Isadora Perat Dec 09 '15 at 18:36
  • lets add logs or toasts to onLocationFound and onLocationNotFound methods. – Emre Aktürk Dec 09 '15 at 18:57
0

You should request these permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Gex
  • 2,092
  • 19
  • 26