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 :
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 !