How to update weather with onCreate()? - android

I've been working on a weather app, and I know it's not perfect (I'm just starting out with android development), but I'm not sure how to update the weather info on every startup. I tried to keep everything in the onCreate() method, but it just "sticks" on the location and conditions that I used when I first started.
I have been able to work around this with a button that gets the new location and weather conditions when it is pressed, but that's not very intuitive. I'm wondering how I can get new conditions on app startup. Might it involve calling onRestart()?
Here's my only activity in the app:
package com.photonfighterlabs.dropweather;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ftoslab.openweatherretrieverz.CurrentWeatherInfo;
import com.ftoslab.openweatherretrieverz.OpenWeatherRetrieverZ;
import com.ftoslab.openweatherretrieverz.WeatherCallback;
import com.ftoslab.openweatherretrieverz.WeatherUnitConverter;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WeatherActivity extends Activity {
private double lat;
private double lng;
private String temp;
private String icon;
private TextView tempTextView;
private TextView cityTextView;
private TextView conditionsTextView;
private int LOCATION_PERMISSION_ID = 1001;
CurrentWeatherInfo currentWeatherInfoF;
private String city;
private List<Address> addresses;
private FusedLocationProviderClient mFusedLocationClient;
OpenWeatherRetrieverZ retriever;
ImageView image;
Geocoder geocoder;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_weather);
retriever = new OpenWeatherRetrieverZ(API_KEY); // hidden for obvious reasons, but working
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
geocoder = new Geocoder(this, Locale.getDefault());
tempTextView = (TextView) findViewById(R.id.temp_text_view);
cityTextView = (TextView) findViewById(R.id.city_text_view);
conditionsTextView = (TextView) findViewById(R.id.conditions_text_view);
image = (ImageView) findViewById(R.id.conditions_image);
if (ContextCompat.checkSelfPermission(WeatherActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(WeatherActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_ID);
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null)
lat = location.getLatitude();
lng = location.getLongitude();
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (!addresses.isEmpty()) {
city = addresses.get(0).getLocality();
cityTextView.setText("Current Weather - " + city);
Log.d("City", city);
}
Log.d("LAT", String.valueOf(lat));
Log.d("LNG", String.valueOf(lng));
}
});
retriever.updateCurrentWeatherInfo(lat, lng, new WeatherCallback() {
#Override
public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) {
currentWeatherInfoF = WeatherUnitConverter.convertToImperial(currentWeatherInfo);
}
#Override
public void onFailure(String error) {
Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show();
}
});
}
public void onRetrieveButtonClick(View view) {
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null)
lat = location.getLatitude();
lng = location.getLongitude();
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (!addresses.isEmpty()) {
city = addresses.get(0).getLocality();
cityTextView.setText("Current Weather - " + city);
Log.d("City", city);
}
Log.d("LAT", String.valueOf(lat));
Log.d("LNG", String.valueOf(lng));
}
});
retriever.updateCurrentWeatherInfo(lat, lng, new WeatherCallback() {
#Override
public void onReceiveWeatherInfo(CurrentWeatherInfo currentWeatherInfo) {
currentWeatherInfoF = WeatherUnitConverter.convertToImperial(currentWeatherInfo);
}
#Override
public void onFailure(String error) {
Toast.makeText(WeatherActivity.this, error, Toast.LENGTH_SHORT).show();
}
});
temp = currentWeatherInfoF.getCurrentTemperature();
Log.d("TMP : ", String.valueOf(temp));
tempTextView.setText( String.valueOf((int) Double.parseDouble(temp)) + (char) 0x00B0);
conditionsTextView.setText(currentWeatherInfoF.getWeatherDescriptionLong());
String iconURL = currentWeatherInfoF.getWeatherIconLink().toString();
Pattern p = Pattern.compile("\\d\\w(n|d)");
Matcher m = p.matcher(iconURL);
if (m.find()) {
icon = m.group();
Log.d("ICON", icon);
String iconName = "r" + icon;
image.setImageResource(getResources().getIdentifier(iconName, "drawable", getPackageName()));
Log.d("NAME", iconName);
}
}
}

getLastLocation() and updateCurrentWeatherInfo(...) are both asynchronous operations. You start them both at the same time which means that updateCurrentWeatherInfo will most likely run before the position is available.
You must start it only after you have got the position, for example from the onSuccess listener.

You have tried with onResume() method?
You can use it and when the view is visible wi

Awareness offers a snapshot-API for obtaining the weather via getWeather() API method at the device location without managing location access or integrating with APIs that query weather from server on-demand.
Illustrative code-snippet:
Awareness.SnapshotApi.getWeather(mGoogleApiClient)
.setResultCallback(new ResultCallback<WeatherResult>() {
#Override
public void onResult(#NonNull WeatherResult weatherResult) {
if (!weatherResult.getStatus().isSuccess()) {
Log.e(TAG, "Could not get weather.");
return;
}
Weather weather = weatherResult.getWeather();
Log.i(TAG, "Weather: " + weather);
}
});
Please refer here for description of the Weather class whose instance is returned by the API.
The advantage of using this is that you can massively simplify your code, avoid having to manage location requests and call the API as often as needed (I believe it has a cache to avoid too many network requests that are battery draining).

Related

Problem in getting the Location in android studio

In my Android project, sometimes I am able to get the user location and sometimes I get NULL location. I have tried out all possible scenarios but not able to get the reason for the NULL location. This is the Main Activity file.
I have also added ACCESS_FINE_LOCATION and INTERNET permission in the manifest file and implementation 'com.google.android.gms:play-services-location:16.0.0' in build.gradle file.
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
Context context = this;
Button fetch;
TextView user_location;
TextView user_address;
Double latitude;
Double longitude;
private FusedLocationProviderClient mFusedLocationClient;
Geocoder geocoder;
List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetch = findViewById(R.id.fetch_location);
user_location = findViewById(R.id.user_location);
user_address = findViewById(R.id.user_address);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fetch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
fetchLocation();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void fetchLocation() throws IOException {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Required Location Permission")
.setMessage("You have to give this permission to acess this feature")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create()
.show();
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
// Permission has already been granted
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
latitude = location.getLatitude();
longitude = location.getLongitude();
user_location.setText("Latitude = "+latitude + "\nLongitude = " + longitude);
geocoder = new Geocoder(context, Locale.getDefault());
user_address.setText("Latitude = "+latitude + "\nLongitude = " + longitude);
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
user_address.setText(address+ " \n" + city + " \n" + state + "\n " + country + "\n " + postalCode + "\n " + knownName);
}
else
{
user_location.setText("Latitude, Longitude not able to access");
user_address.setText("Not Done!!!!!!!!!");
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//abc
}else{
}
}
}
}

Android: Location updating very slowly

I am trying to create an app that sends to my server the location of my android device on button press. Unfortunately the location updates very slowly, sometimes taking minutes and tens of meters to get the new location.
I'm relatively new to Android programming and if anyone could help me with a way to update the location every time when press the send button I would be grateful.
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import org.json.*;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class DefaultActivity extends AppCompatActivity {
private String serverURL;
private TextView tv_Title, tv_Status;
private Button b_SendLocation, b_SendNow, b_StopLocation;
private User user;
private FusedLocationProviderClient locationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_default);
Intent intent = getIntent();
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
locationClient = LocationServices.getFusedLocationProviderClient(this);
serverURL = intent.getExtras().getString("serverURL");
JSONParse(intent.getExtras().getString("myResponse"));
tv_Title = findViewById(R.id.TextView_Title);
tv_Status = findViewById(R.id.TextView_Status);
b_SendLocation = findViewById(R.id.Button_SendLocation);
b_SendNow = findViewById(R.id.Button_SendNow);
b_StopLocation = findViewById(R.id.Button_StopLocation);
tv_Title.setText(user.getLastName() + " " + user.getFirstName());
tv_Status.setText(" ");
b_SendLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Sending location every 5 sec.");
}
});
b_SendNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Current location sent!");
GetLocation();
}
});
b_StopLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Feedback("Periodic sending halted!");
}
});
}
private void GetLocation() {
if (ActivityCompat.checkSelfPermission(DefaultActivity.this, ACCESS_FINE_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;
}
locationClient.getLastLocation().addOnSuccessListener(DefaultActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
double latitude, longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
tv_Status.setText("Latitude: " + latitude + "\nLongitude: " + longitude);
SendLocation(latitude, longitude);
}
else
tv_Status.setText("Location is null!");
}
});
}
private void SendLocation(double latitude, double longitude){
OkHttpClient client = new OkHttpClient();
String url = serverURL + "/api/user/?id=" + user.getID() + "&latitude=" + latitude + "&longitude=" + longitude;
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e){
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
tv_Status.append("\n\n Server error!");
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException{
if (response.isSuccessful()){
runOnUiThread(new Runnable() {
#Override
public void run() {
tv_Status.append("\n\n Server acknowledged!");
}
});
}
}
});
}
private void JSONParse(String JSONString){
User readUser = new User();
try {
JSONObject obj = new JSONObject(JSONString);
readUser.setID(Integer.parseInt(obj.getString("ID")));
readUser.setFirstName(obj.getString("FirstName"));
readUser.setLastName(obj.getString("LastName"));
readUser.setEmail(obj.getString("Email"));
readUser.setPassword(obj.getString("Password"));
readUser.setRole(obj.getString("Role"));
Feedback("Welcome back " + readUser.getFirstName() + "!");
} catch (JSONException e) {
Feedback("JSON Exception!");
e.printStackTrace();
}
user = readUser;
}
private void Feedback(String message){
Toast toast=Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG);
toast.show();
}
}

CheckSelfPermission() not running with API 24

Neither
Permission Denied nor Permission Granted are showing up in my log.
However the Log.v("SPAM","1"); is working.
Does the class have to be the "MainActivity" running in order for the code to work ?
This is the class where the permissions are being used.
Another problem was that requestPermissions was not running, and the code below wasn't either. Any ideas what this could be?
package com.project.backgroundprocesstest;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by Alex on 14/09/2016.
*/
public class LocationControl extends AppCompatActivity{
final int REQUEST_ACCESS_FINE_LOCATION = 5;
private Context context;
private LocationManager locationManager;
public LocationControl(Context context){
this.context = context;
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.v("SPAM", "1");
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new MyLocationListener(context));
}
}
public LocationManager getLocationManager(){
return locationManager;
}
public String getLocation(){
Log.v("SPAM", "1");
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.v("CheckPermission","Permission Denied");
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_ACCESS_FINE_LOCATION);
Log.v("CheckPermission","It Does run");
}
else{
Log.v("CheckPermission","Permission Granted");
Location location = this.locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitudinal = location.getLongitude();
double latitudinal = location.getLatitude();
String cityName = findCity(location);
Date date = new Date();
return setJSON(longitudinal,latitudinal,cityName,date);
}
return null;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults){
switch(requestCode){
case REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Log.d("CheckPermission","User Denisd Permission");
}
return;
}
}
}
public String setJSON(double lng, double lat, String place, Date date) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put("longitudinal", lng);
jsonObject.put("latitudinal", lat);
jsonObject.put("name", place);
jsonObject.put("created", date);
} catch (Exception e) {
Log.e("Error", "JSON ERROR");
}
if(jsonObject != null)
return jsonObject.toString();
else
return null;
}
private String findCity(Location loc){
String cityName = null;
Geocoder gcd = new Geocoder(context, Locale.getDefault());
// IF any addresses which belong to the Longitudinal and Latitudinal are found,
// set cityName and print it
List<Address> addresses;
try{
addresses = gcd.getFromLocation(loc.getLatitude(),loc.getLongitude(),1 );
if(addresses.size()>0){
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
}catch(IOException e){
e.printStackTrace();
}
return cityName;
}
private String locationToString(Location location){
return Location.convert(location.getLatitude(),Location.FORMAT_DEGREES)+" " + Location.convert(location.getLongitude(),Location.FORMAT_DEGREES);
}
}
EDIT: No errors are popping up in log or debug.
You can call checkCallingPermission (permission) of Context instead

Incorrect Location updates with wifi/mobile network but not with GPS

Following is the coding i got from some one else work. I am trying to implement bit of his work with necessary changes in my app. The problem here is that it is not returning the proper address when the GET ADDRESS button is clicked. Besides, it works only with the wifi/mobile network but not with the GPS. Meanwhile, i wonder how to make auto-posting of data to sever when the call is making to a contact. Thank you!
package com.yang.address;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class AddressActivity extends Activity {
/** Called when the activity is first created. */
Double lat, lon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLocation = (Button)findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) AddressActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = location.getLatitude();
lon = location.getLongitude();
TextView tv = (TextView) findViewById(R.id.txtLoc);
tv.setText("Your Location is:" + lat + "--" + lon);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
});
Button btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
postData(lat, lon);
}
});
Button btnAdd = (Button)findViewById(R.id.btnAddress);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView tv = (TextView)findViewById(R.id.txtAddress);
tv.setText(GetAddress(lat, lon));
}
});
}
public void postData(Double lat2, Double lon2) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet htget = new HttpGet("http://myappurl.com/Home/Book/"+lat2+"/"+lon2);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(htget);
String resp = response.getStatusLine().toString();
Toast.makeText(this, resp, 5000).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "Error", 5000).show();
} catch (IOException e) {
Toast.makeText(this, "Error", 5000).show();
}
}
public String GetAddress(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
}
Looks like you've made some progress since your last question.
First off, the LocationManager system on androids is Listening Service in that you register it as a listener and allow the OS to notify when updates are made. This means you should have the code you put in your OnClick method run before you need it. Your best option is to have the OnCreate method of your Activity register the listener as the Activity starts and use the onLocationChanged callback as a way to store the new Location on a class variable.
private Location lastKnownLocation;
private TextView tv;
public void onCreate(Bundle savedInstanceState) {
//....
setupLocationServices();
//....
tv = (TextView) findViewById(R.id.txtLoc);
Button btnLocation = (Button)findViewById(R.id.btnLocation);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
updateLocation();
}
});
//....
}
private void setupLocationServices() {
//....
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lastKnownLocation = location;
updateLocation();
}
....
}
private void updateLocation() {
double lat = lastKnownLocation.getLatitude();
double lat = lastKnownLocation.getLongitude();
tv.setText("Your Location is:" + lat + "--" + lon);
}
As for your reasoning as to why it doesn't work with GPS it is because you never register the GPS listener. Where you have this line:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You would need to substitude in this value:
LocationManager.GPS_PROVIDER
Again, as I recommended before I really suggest taking the time to fully understand the Android Developer documentation
As for your other problem regarding listening to the state of incoming calls you should start off by checking the TelephonyManager documentation here. Specifically look for the use of ACTION_PHONE_STATE_CHANGED and its extras for incoming calls. For outgoing calls google the use of ACTION_NEW_OUTGOING_CALL Intents.

android get zipcode of India from latitude and longitude [duplicate]

This question already has answers here:
ZipCode from location
(3 answers)
Closed 9 years ago.
I need to get the zip code from a latitude and longitude, Im able to get the address with street names but cannot get the zip code. String pCode is returning Null in the below code.
Below is the code I'm using:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class GetCurrentLocation extends Activity implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
String addrs = null;
String pCode = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
addrs = addresses.get(0).getAddressLine(0);
pCode = addresses.get(0).getPostalCode();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName+" Address "+ addrs+
" Postal Code"+pCode;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
use this api it will give zipcode also.
by passing lat and log.
http://ws.geonames.org/findNearbyPostalCodesJSON?formatted=true&lat=23.0333&lng=72.6167
the Discription of the API .getFromLocation states :
The returned values may be obtained by means of a network lookup. The
results are a best guess and are not guaranteed to be meaningful or
correct.
So there is a good chance that the location returned only has some info missing.
There are 2 solution's for your issue:
1) Increase the maxResults , lets say 5. And check if any of the 5 has a postal code.( query could return less than 5 so make sure to put appropriate check)
2) refer ZipCode from location , for how to query it separately if we have city name.

Categories

Resources