geocoder declaration null pointer exception in service class - java

when i put reverse geocoder function into service class and trying to call in activity ,, i got null pointer exception ..
this is my class
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String tempAddress;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
location = locationManager
.getLastKnownLocation(locationProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
String locationgps=LocationManager.GPS_PROVIDER;
location = locationManager
.getLastKnownLocation(locationgps);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS/Data roaming is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public String getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
double latitude=getLatitude();
double longitude=getLongitude();
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
Toast.makeText(getApplicationContext(),"I am at: "+strAddress.toString(),Toast.LENGTH_LONG).show();
// myAddress.setText("I am at: " +strAddress.toString());
tempAddress=strAddress.toString();
return tempAddress;
//Intent intent = new Intent("MyCustomIntent");
// add data to the Intent
// intent.putExtra("strAddress",strAddress.toString());
// intent.setAction("android.provider.Telephony.SMS_RECEIVED");
// sendBroadcast(intent);
// Intent intent = new Intent (Menu.this,IncomingSms.class);
// intent.putExtra("strAddress",strAddress.toString());
// sendBroadcast(intent);
}
else
Toast.makeText(getApplicationContext(), "No Location found", Toast.LENGTH_LONG).show();
//myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Tidak bisa Menerima Alamat ,, harap cek jaringan dan gps hp anda!", Toast.LENGTH_LONG).show();
showSettingsAlert();}
tempAddress="Could not Retrive Address!";
return tempAddress;
}
}
and this is my activity class:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import javax.xml.transform.Templates;
import mo.locationtracking.GPSTracker;
import mo.sms.IncomingSms;
import info.MonitoringObjek.R;
import android.app.Activity;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
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 Menu extends Activity implements OnClickListener{
private Button bTambah;
private Button bLihat;
//private Button blokasi;
GPSTracker gps;
private TextView myAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
myAddress = (TextView)findViewById(info.MonitoringObjek.R.id.lokasisekarang);
// blokasi=(Button) findViewById(R.id.button_lokasi);
// blokasi.setOnClickListener(this);
bTambah = (Button) findViewById(R.id.button_tambah);
bTambah.setOnClickListener(this);
bLihat = (Button) findViewById(R.id.button_view);
bLihat.setOnClickListener(this);
// create class object
gps = new GPSTracker(Menu.this);
// check if GPS enabled
if(gps.canGetLocation()){
//double latitude = gps.getLatitude();
//double longitude = gps.getLongitude();
//Geocoder geocoder;
//myAddress.setText("Latitude: "+latitude+"Longitude: "+longitude);
String tempAddress=gps.getMyLocationAddress();
myAddress.setText("I am at: " +tempAddress);
gps.stopUsingGPS();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button_tambah :
Intent i = new Intent(this, CreateData.class);
startActivity(i);
break;
case R.id.button_view :
Intent i2 = new Intent(this, ViewData.class);
startActivity(i2);
break;
}
}
}
and this is my logcat:
05-28 14:47:14.187: E/Trace(5031): error opening trace file: No such file or directory (2)
05-28 14:47:14.688: E/AndroidRuntime(5031): FATAL EXCEPTION: main
05-28 14:47:14.688: E/AndroidRuntime(5031): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.MonitoringObjek/mo.database.Menu}: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.access$600(ActivityThread.java:137)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Handler.dispatchMessage(Handler.java:99)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.os.Looper.loop(Looper.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.main(ActivityThread.java:4786)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invokeNative(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): at java.lang.reflect.Method.invoke(Method.java:511)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
05-28 14:47:14.688: E/AndroidRuntime(5031): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
05-28 14:47:14.688: E/AndroidRuntime(5031): at dalvik.system.NativeStart.main(Native Method)
05-28 14:47:14.688: E/AndroidRuntime(5031): Caused by: java.lang.NullPointerException
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.location.Geocoder.<init>(Geocoder.java:83)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.locationtracking.GPSTracker.getMyLocationAddress(GPSTracker.java:213)
05-28 14:47:14.688: E/AndroidRuntime(5031): at mo.database.Menu.onCreate(Menu.java:54)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Activity.performCreate(Activity.java:5008)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
05-28 14:47:14.688: E/AndroidRuntime(5031): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
05-28 14:47:14.688: E/AndroidRuntime(5031): ... 11 more
i see inthis post it's say geocoder must declare inside on create in activity .. is that impossible to declare in service class? i need that geocoder still update even my application is closed..

The Location from the android application is not that much accurate you can call the google api webservice using get method and parse the json result and you can get Area Block city street etc
it is more accurate than default one

Related

ImageButton to open a new activity

I am building an android app and on the main layout i have 3 Image Buttons which when clicked they must each open a new activity.
When I run the app and pressed on them the app crushes. this is the code i am using:
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton converterbtn = (ImageButton)findViewById(R.id.btnConvert);
ImageButton placesbtn = (ImageButton)findViewById(R.id.imagBtnPlace);
ImageButton weatherbtn = (ImageButton)findViewById(R.id.imgbtnweather);
//Open Weather Activity
if (weatherbtn.isPressed() == true) {
weatherbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), weather_mainActivity.class);
startActivity(intent);
}
}); //Open Currency Activity
}else if (converterbtn.isPressed() == true) {
converterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), CurrencyConverter_MainActivity.class);
startActivity(intent1);
}
});//Open Places Activity
} else if (placesbtn.isPressed()) {
placesbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(getApplicationContext(), Places_mainActivity.class);
startActivity(intent1);
}
});
}
}
Manifest.xml
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
Any ideas why that happens? All the other posts ive checked are doing it with this way but on mine it doesnt seem to work.
Android Monitor log
01-08 03:00:58.288 22447-22447/? D/AndroidRuntime: Shutting down VM
--------- beginning of crash
01-08 03:01:01.127 1236-1547/? D/AudioFlinger: mixer(0xf4480000) throttle end: throttle time(56)
01-08 03:01:01.151 1550-21914/? D/OpenGLRenderer: endAllStagingAnimators on 0x7f0b1b83d400 (RippleDrawable) with handle 0x7f0b1b8bb540
01-08 03:01:01.192 1550-1954/? D/GraphicsStats: Buffer count: 3
Weather_MainActivity.java
package com.android.example.cwapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class weather_mainActivity extends AppCompatActivity {
public static final String TAG = weather_mainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
LocationManager locationManager;
#InjectView(R.id.timeLabel) TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)TextView mHumidityValue;
#InjectView(R.id.precipValue)TextView mPrecipValue;
#InjectView(R.id.summaryLabel)TextView mSummaryLabel;
#InjectView(R.id.iconImageView)ImageView mIconImageView;
#InjectView(R.id.refreshImageView)ImageView mRefreshImageView;
#InjectView(R.id.progressBar)ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)TextView mLocation;
public double latitude /*= 34.7720*/;
public double longitude /*= 32.4297*/;
//Location Manager
private boolean checkLocation() {
if (!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private final LocationListener locationListenerBest = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
Log.d(TAG, "Main UI code is running!");
}
private void getForecast(double latitude, double longitude) {
String apiKey = "6180f6e1b6747c1da3cb4638ea9d2961";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
} else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
float temp = mCurrentWeather.getTemperature();
String temp2 = Float.toString((temp - 32) * (5 / 9));
mTemperatureLabel.setText(temp2 + "");
mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
mSummaryLabel.setText(mCurrentWeather.getSummary());
mLocation.setText(mCurrentWeather.getTimeZone());
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
currentWeather.setSummary(currently.getString("summary"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void alertUserAboutError() {
AlertDialogFragment_weather dialog = new AlertDialogFragment_weather();
dialog.show(getFragmentManager(), "error_dialog");
}
};
RUN Log
01-09 21:29:30.827 5610-5610/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.827 5610-5610/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.864 5610-5627/? E/art: Thread attaching while runtime is shutting down: Binder_2
01-09 21:29:30.869 5614-5614/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:30.870 5614-5614/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:30.916 1548-1596/? E/InputDispatcher: channel '6ba3a14 com.android.example.cwapp/com.android.example.cwapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
01-09 21:29:31.830 5633-5633/? E/memtrack: Couldn't load memtrack module (No such file or directory)
01-09 21:29:31.830 5633-5633/? E/android.os.Debug: failed to load memtrack module: -2
01-09 21:29:32.033 1195-1309/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
01-09 21:29:33.170 1921-2145/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xedc344f0
01-09 21:30:01.551 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819a240
01-09 21:30:02.902 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8310
01-09 21:30:04.739 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b819b580
01-09 21:30:06.655 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1cf8380
01-09 21:30:08.253 5641-5654/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1bed700
01-09 21:30:09.115 5641-5641/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.example.cwapp, PID: 5641
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cwapp/com.android.example.cwapp.Places_mainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.android.example.cwapp.Places_mainActivity.onCreate(Places_mainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
01-09 21:30:11.307 1548-1601/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f44b1c8f020
01-09 21:30:11.326 1548-1937/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
Add CurrentWeather.class activity in your mainfest like this
<activity android:name=".CurrencyConverter_MainActivity"/>
<activity android:name=".weather_mainActivity"/>
<activity android:name=".CurrentWeather"/>
You should display your stack trace, but you don't need View.OnClickListner, not sure if that's causing it, but just have weatherbtn.setOnClickListener(new OnClickListener() {...
Other than that, there isn't anything wrong with how you're calling your activity.

Latitude and Longitude are null

I'm working on an app getting user's current location and showing it on map, as well as Latitude and Longitude on the screen, so far everything is going fine, the map's showing my current location as well as displaying latitude and longitude on the screen using this code
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
Problem occurs when I want to send this latitude and longitude on server , it throws NUll pointer exception
01-04 23:27:38.759 29286-29286/io.xgear.geotag E/AndroidRuntime: FATAL
EXCEPTION: main
Process: io.xgear.geotag, PID: 29286
java.lang.NullPointerException
at io.xgear.geotag.MainActivity$GeoTagTask.<init>(MainActivity.java:234)
at io.xgear.geotag.MainActivity$1.onClick(MainActivity.java:181)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19270)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
this is the piece of code for getting latitude and longitude to send
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
and this is the full code
package io.xgear.geotag;
import android.Manifest;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.ContentValues;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import io.xgear.geotag.helper.Post;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
private GeoTagTask mAuthTask = null;
GPSTracker gps;
private JSONObject jsonObj;
// UI references.
private EditText txtShopCode;
private EditText lblAddress;
private View mProgressView;
private View mGeoTagForm;
private Button btnGeoTag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtShopCode = (EditText) findViewById(R.id.txtShopCode);
btnGeoTag = (Button) findViewById(R.id.btnGeoTag);
mGeoTagForm = (View) findViewById(R.id.geoTagForm);
mProgressView = findViewById(R.id.geoTagProgress);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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;
}
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
btnGeoTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String shopid = txtShopCode.getText().toString();
boolean cancel = false;
View focusView = null;
//txtShopCode.setInputType(InputType.TYPE_CLASS_NUMBER);
if (TextUtils.isEmpty(shopid)) {
txtShopCode.setError(getString(R.string.error_field_required));
focusView = txtShopCode;
cancel = true;
}
else {
showProgress(true);
mAuthTask = new GeoTagTask(shopid);
mAuthTask.execute((Void) null);
}
}
});
}
//
// public void btnGeoTag_Click(View v){
//
// }
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
mGeoTagForm.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mGeoTagForm.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private final String shopCode;
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
private boolean isConnect;
GeoTagTask(String shopId) {
shopCode = shopId;
isConnect = false;
}
#Override
protected Boolean doInBackground(Void... params) {
boolean res = false;
try {
ContentValues nameValuePairs = new ContentValues();
nameValuePairs.put("Id", shopCode);
nameValuePairs.put("lat", lat);
nameValuePairs.put("lng", lng);
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lat + "\nLong: " + lng, Toast.LENGTH_LONG).show();
Log.i("Latitude", lat+"");
Post post = new Post(getApplicationContext());
String result = "";
// isConnect = post.isConnected();
// if(isConnect) {
result = post.doPost(nameValuePairs);
jsonObj = new JSONObject(result);
Log.i("Result", result+"");
if(jsonObj.getInt("success") == 1)
res = true;
// }
} catch (JSONException e) {
e.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// intent.putExtra("jsonObj", jsonObj.toString());
// startActivity(intent);
txtShopCode.getText().clear();
txtShopCode.requestFocus();
Toast.makeText(getBaseContext(), "Your shop is geo tagged ", Toast.LENGTH_LONG).show();
} else {
// if(isConnect){
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// else
Toast.makeText(getBaseContext(), R.string.geoTagError, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#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
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_main, menu);
// return true;
// }
}
UPDATE
I have added thes lines in GeoTagTask the button is working the app is not crashing but I'm not sure if it's going to work if location is changed because
if( location != null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
is giving me errors .
The lines I have added
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
Problem
Problem is inside GeoTagTask ,
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
You are accessing an uninitialized variable.
Solution
Make onCreate location a global variable,
public class MainActivity extends FragmentActivity implements LocationListener {
Location location;
void onCreate() {
....
location = locationManager.getLastKnownLocation(provider);
....
}
}
Use the global variable inside GeoTagTask,
public class GeoTagTask extends AsyncTask<Void, Void, Boolean> {
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());
...
}
inside GeoTagTask location object is different one and also doesn't initilized.
Location location;
private String lat = Double.toString(location.getLatitude());
private String lng = Double.toString(location.getLongitude());

Android, gps. App with GPS's localizzation

I've ha problem: I 'm implementing a secondary Activity that give to me user's position. From Page1.java, through a button, open Track.java when I would like to show the coordinates of the user's location. The problem is when I click on this button: the application is closed!
This is the code of Page1.java:
package com.example.giacomob.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Giacomo B on 05/08/2015.
*/
public class Page1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
// String dato1 = getIntent().getExtras().getString("NomeDati1");
//Intent intent = getIntent(); // Point 1
// Bundle bundle = intent.getExtras(); // Point 2
// String data1 = bundle.getString("NomeDati1"); // Point 3
String dato1 = getIntent().getExtras().getString("NomeDati1"); //preleva la stringa
Toast.makeText(this, dato1, Toast.LENGTH_SHORT).show(); //PROVA: questo mi fa comparire una specie di label notifica trasparente con il valore di "data1"
Log.d("TAG", "data1:" + dato1); //credo sia una specie di debug
// String salve = getIntent().getExtras().getString("ciao");
// System.out.println("questo è il valore della prima variabile" +salve);
//FARE CONTROLLO IN CASO IL FILE XML E' VUOTO E QUINDI LA STRINGA E' VUOTA
String[] arr = dato1.split("\\|");
for (int i = 0; i < arr.length; i++) {
System.out.println(i + " => " + arr[i]);
}
final ArrayList <String> listp = new ArrayList<String>();
for (int i = 0; i < arr.length; ++i) {
listp.add(arr[i]);
}
// recupero la lista dal layout
final ListView mylist = (ListView) findViewById(R.id.listView1);
// creo e istruisco l'adattatore
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listp);
// inietto i dati
mylist.setAdapter(adapter);
Button b_load=(Button)findViewById(R.id.button_send2);
b_load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openTrack = new Intent(Page1.this, Track.class);
startActivity(openTrack);
}
});
}
This is the code of Track.java:
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
And this is the code of the xml file associate to Track.java, called "activity_track.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="In attesa di essere localizzati..."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:id="#+id/locationText"/>
</RelativeLayout>
This is LogCat's code:
08-08 00:04:23.801 2217-2217/com.example.giacomob.myapplication I/art﹕ Not late-enabling -Xcheck:jni (already on)
08-08 00:04:24.035 2217-2234/com.example.giacomob.myapplication I/OpenGLRenderer﹕ Initialized EGL, version 1.4
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:24.070 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398620, error=EGL_SUCCESS
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Root element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ ----------------------------
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ [ 08-08 00:04:25.762 2217: 2217 I/System.out ]
Current Element :destinazione
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Coordinata X : 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Naziome : Italia
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Paese : Cannole
08-08 00:04:25.762 2217-2217/com.example.giacomob.myapplication I/System.out﹕ Via : Piazza San Vincenzo
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 0 => 1
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 1 => 2
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 2 => Italia
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 3 => Cannole
08-08 00:04:25.864 2217-2217/com.example.giacomob.myapplication I/System.out﹕ 4 => Piazza San Vincenzo
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:25.919 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa511b960, error=EGL_SUCCESS
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/EGL_emulation﹕ eglSurfaceAttrib not implemented
08-08 00:04:26.166 2217-2234/com.example.giacomob.myapplication W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb4398900, error=EGL_SUCCESS
08-08 00:04:26.893 2217-2217/com.example.giacomob.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.giacomob.myapplication, PID: 2217
java.lang.RuntimeException: Unable to resume activity {com.example.giacomob.myapplication/com.example.giacomob.myapplication.Track}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2989)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.location.LocationManager.isProviderEnabled(java.lang.String)' on a null object reference
at com.example.giacomob.myapplication.Track.onResume(Track.java:39)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2978)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3020)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is the update of Track.java
package com.example.giacomob.myapplication;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener {
/* #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
}
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
// private LocationManager locationManager=null;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
private static final int MIN_DIST = 20;
private static final int MIN_PERIOD = 30000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
// LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}
I don't understand the reason for witch the app is closed! Please, help me! Thanks
You never instantiate your LocationManager reference. This must be done in onCreate like this:
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
The app crashes due to a Null Pointer Exception.
The answer of andrewdleach is correct; and the exact line to add in onCreate is this:
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
EDIT:
ok, try to use this
package com.example.giacomob.myapplication;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends ActionBarActivity implements LocationListener
{
String providerId = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
private final int MIN_DIST=20;
private static final int MIN_PERIOD=30000; */
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
/*if(!providerId.contains("gps"))
{
final Intent intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
intent.setData(Uri.parse("3"));
sendBroadcast(intent);
}*/
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume()
{
if (locationManager == null)
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
super.onResume();
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else
{
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
}
private void updateGUI(Location location)
{
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
txt.setText(msg);
}
#Override
protected void onPause()
{
super.onPause();
if (locationManager != null)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location)
{
updateGUI(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
#Override
public void onProviderEnabled(String s)
{ }
#Override
public void onProviderDisabled(String s)
{ }
}

Android Studio. MyApp Unfortunately has stopped

I am trying to get the current location (latitude and longtitude) and my app is not running. I have a TextView to view the longtitude (testing for a start).
This is my mainActivity code:
import android.content.Intent;
import android.location.GpsStatus;
import android.location.Location;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.internal.widget.ViewUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
//public Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView);
//creating new object of the method
MyLocationListener myLocationListener = new MyLocationListener();
double longt=myLocationListener.getLocation().getLongitude();
String longi =String.valueOf(longt);
//String lat1 =String.valueOf(lat);
tv.setText(longi);
//myLocationListener.onProviderEnabled(WIFI_SERVICE);
//myLocationListener.onProviderDisabled(WIFI_SERVICE);
// myLocationListener.getLatitude(location);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void process(View view){
Intent intent;
intent = new Intent(this,MapsActivity.class);
startActivity(intent);
}
}
and these errors came up:
>
8585-8585/com.example.maxi.try_v2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.maxi.try_v2, PID: 8585
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.maxi.try_v2/com.example.maxi.try_v2.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.maxi.try_v2.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
if you can help, I would be glad.
this is the MyLocationListener class (sorry for the incomplete info)
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Created by maxi on 7/17/15.
*/
public class MyLocationListener implements LocationListener {
private Context mContext;
//gps status flag
boolean isGpsEnabled = false;
boolean canGetLocation = false;
//flag for network status
boolean isNetworkEnabled;
//min distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
//min time between updates in miliseconds
private static final long MIN_TIME_BW_UPDATES = 60000; //1min
protected LocationManager locationManager;
public static double latitude;
public static double longtitude;
Location location;
/* public MyLocationListener(Context context){
this.mContext = context;
getLocation();
}*/
public void onLocationChanged(Location loc) {
latitude = loc.getLatitude();
longtitude = loc.getLongitude();
}
public void getLatitude(Location loc) {
latitude = loc.getLatitude();
String lat = String.valueOf(latitude);
Log.w("poutsa", lat);
}
public void onProviderDisabled(String provider) {
Log.w("myApp", "no network");
}
public void onProviderEnabled(String provider) {
Log.w("myApp", "NetIsOn");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
//http://developer.android.com/reference/android/location/LocationListener
// .html#onStatusChanged%28java.lang.String,%20int,%20android.os.Bundle%29
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
//gettin GPS status
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//gettin network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) {
//no network
} else {
this.canGetLocation = true;
//first get location from provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
if (isGpsEnabled){
if (location == null){
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Gps Enabled","Gps Enabled");
if (locationManager != null){
location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return location;
}
}
This is giving you a NullPointerException, which means you're getting null when making a request to the Location
double longt=myLocationListener.getLocation().getLongitude();
Caused by: java.lang.NullPointerException
at com.example.maxi.try_v2.MainActivity.onCreate(MainActivity.java:27)
Open MainActivity.java, look at line 27: you have a null variable.
Since you did not tell what line 27 is, I cannot help any more.
Just check for nulls, for example: myLocationListener.getLocation() might be null in your code.

nullPointerException on Geocoder

I am playing around with working with the location but now i keep on getting a nullPointerException when ever i click the button on the app. The button refreshes the location which is displayed. The location is displayed in latitude,longitude, street address,city,country and postal address. here is the code below.
package com.example.metrorails;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
CurrentPosition currentPosition;
String address;
String city;
String country;
String postalCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button refresh;
refresh = (Button)findViewById(R.id.refresh);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentPosition = new CurrentPosition(MainActivity.this);
TextView showresults = (TextView) findViewById(R.id.show_results);
showresults.setTextSize(20);
if(currentPosition.canGetLocation()){
double latitude = currentPosition.getLatitude();
double longitude = currentPosition.getLongitude();
showresults.setText("current latitude: "+latitude +"\n current longitude: "+longitude+
"\n Address is: " +currentPosition.getAddress() + "\n city is: "+currentPosition.getCity()+
"\n Current Country is: "+currentPosition.getCountry() +"\n Area Code : "+currentPosition.getPostalCode());
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
currentPosition.showSettingsAlert();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I'm still having problems with this program. here is the logcat below.
09-09 18:56:52.393: E/AndroidRuntime(1882): FATAL EXCEPTION: main
09-09 18:56:52.393: E/AndroidRuntime(1882): java.lang.NullPointerException
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.location.GeocoderParams. <init>(GeocoderParams.java:50)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.location.Geocoder.<init>(Geocoder.java:83)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.example.metrorails.CurrentPosition.<init>(CurrentPosition.java:71)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.example.metrorails.MainActivity$1.onClick(MainActivity.java:31)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.view.View.performClick(View.java:4240)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.view.View$PerformClick.run(View.java:17721)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Handler.handleCallback(Handler.java:730)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Handler.dispatchMessage(Handler.java:92)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.os.Looper.loop(Looper.java:137)
09-09 18:56:52.393: E/AndroidRuntime(1882): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-09 18:56:52.393: E/AndroidRuntime(1882): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 18:56:52.393: E/AndroidRuntime(1882): at java.lang.reflect.Method.invoke(Method.java:525)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-09 18:56:52.393: E/AndroidRuntime(1882): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-09 18:56:52.393: E/AndroidRuntime(1882): at dalvik.system.NativeStart.main(Native Method)
09-09 18:57:01.512: I/Process(1882): Sending signal. PID: 1882 SIG: 9
below is the CurrentPosition class.
package com.example.metrorails;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class CurrentPosition extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
public static String address;
public static String city;
private static String country;
private static String postalCode;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public String getAddress(){
return address;
}
public String getCity(){
return city;
}
public String getCountry(){
return country;
}
public String getPostalCode(){
return postalCode;
}
public CurrentPosition(Context context) {
this.mContext = context;
getLocation();
}
public void getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Geocoder geocode = new Geocoder(this, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocode.getFromLocation(latitude,longitude, 1);
this.address = addresses.get(0).getAddressLine(0);
this.city = addresses.get(0).getAddressLine(1);
this.country = addresses.get(0).getAddressLine(2);
this.postalCode = addresses.get(0).getPostalCode();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}} catch (Exception e) {
e.printStackTrace();
}
this.location = location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(CurrentPosition.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}

Categories