I am trying to fetch some for Location Address using IntentService but ended up with error leading to app crash. Please help me.
Here is the Stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.ResultReceiver.send(int, android.os.Bundle)' on a null object reference
at com.example.ajender.sample2.FetchAddressIntentService.deliverResultToReceiver(FetchAddressIntentService.java:91)
at com.example.ajender.sample2.FetchAddressIntentService.onHandleIntent(FetchAddressIntentService.java:81)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
Here is FetchAddressIntentService:
public class FetchAddressIntentService extends IntentService {
private static String TAG="Fetch-address-Service";
protected ResultReceiver mReceiver;
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* #param name Used to name the worker thread, important only for debugging.
*/
public FetchAddressIntentService(String name) {
super(name);
}
public FetchAddressIntentService(){
super("FetchAddressIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
String errorMessage = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
Location location = intent.getParcelableExtra(
Constants.LOCATION_DATA_EXTRA);
mReceiver=intent.getParcelableExtra(Constants.RECEIVER);
Log.e(TAG,"1-----");
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
// In this sample, get just a single address.
1);
} catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = "service_not_available";
Log.e(TAG, errorMessage, ioException);
} catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = "invalid_lat_long_used";
Log.e(TAG, errorMessage + ". " +
"Latitude = " + location.getLatitude() +
", Longitude = " +
location.getLongitude(), illegalArgumentException);
}
// Handle case where no address was found.
if (addresses == null || addresses.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = "no_address_found";
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
Address address = addresses.get(0);
ArrayList<String> addressFragments = new ArrayList<String>();
// Fetch the address lines using getAddressLine,
// join them, and send them to the thread.
for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
addressFragments.add(address.getAddressLine(i));
}
Log.i(TAG, "address_found");
deliverResultToReceiver(Constants.SUCCESS_RESULT,
TextUtils.join(System.getProperty("line.separator"),
addressFragments));
}
}
private void deliverResultToReceiver(int resultCode, String message) {
Bundle bundle = new Bundle();
bundle.putString(Constants.RESULT_DATA_KEY, message);
Log.e(TAG, "2-----");
mReceiver.send(resultCode, bundle);
Log.e(TAG, "3-----");
}
This service should have to send back bundle with Result Receiver and result code but not happening....
The error can be resolved following the steps below
In the MainActivity
Add public AddressResultReceiver mResultReceiver;
mResultReceiver = new AddressResultReceiver(null)- This will automatically assign a id for the main activity class.
In the FetchAddressIntentService
Add mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
Check whether mReceiver is null by logging it.
Send the data using your current code.
It should work. Thats how I got Around it.If you have any problem comment.
Probably you haven't initialize the mResultReceiver from your activity correctly, which you are supposed to pass to the FetchAddressIntentService intent:
mResultReceiver = new AddressResultReceiver(new android.os.Handler());
..
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
..
startService(intent);
What happens in case of IntentService is that you have three components that are playing role: MainActivity (that will call the intent service), IntentService (which is responsible for handling the intent) and the last ResultReceiver which receives the result after the intent has been handled (or operated).
As evident from the Log you have not initialized or assigned any value to ResultReceiver mReceiver
You should initialize mResultReceiver by declaring a class let us call it AddressResultReceiver which extends ResultReceiver and has a parameterized constructor that accepts a single parameter as Handler object and overrides the onReceiveResult() method like the following:
AddressResultReceiver(Handler handler) {
super(handler);
}
//Result from intent service
#Override
public void onReceiveResult(int resultCode, Bundle bundle) {
...
}
Now you have successfully obtained two of three components: MainActivity for starting an intent request and ResultReceiver for receiving the result. Let us now make our IntentService by defining a class in the project hierarchy and extending it with IntentService and overriding its method onHandleIntent(Intent intent)():
public class FetchAddressIntentService extends IntentService {
public FetchAddressIntentService() {
super("FetchAddressIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {...}
}
So we are now good to go to get the things up and working. Now write the following code in your MainActivity:
//Initializing the reference with AddressResultReceiver object
mResultReceiver = new AddressResultReceiver(new Handler());
...
//Setting the IntentService to FetchAddressIntentService
Intent intent = new Intent(this, FetchAddressIntentService.class);
/*passing the receiver object to the service so as to let it know where to
publish results*/
intent.putExtra(Constants.RECEIVER, mResultReceiver);
...
//starting the service
startService(intent);
Now your deliverResult(int, String) would no longer throw NullPointerException. For more information visit IntentService and ResultReceiver. Hope it helps! :)
Add the below code in your protected void onHandleIntent (#Nullable Intent intent){} before Geocoder
if (intent != null){
String errorMessage ="";
resultReceiver = intent.getParcelableExtra(Constants.RECEIVER);
Location location = intent.getParcelableExtra(Constants.LOCATION_DATA_EXTRA);
if (location == null) {
return;
}
Related
Please, I am having problem sending an ArrayList data to Activity.
The data is an URL saved in ArrayList but after using bundle extras, I am getting null pointer exception. I also try to catch the exception but still the data i get using get extra string is null
// below is the code i used to pass the data
Bundle extras = new Bundle();
extras.putString("VidUrl",VideoLecturesUrl.get(position));
extras.putString("bookUrl",bookUrl.get(position));
extras.putString("VidTitle",titleList.get(position));
Intent intent = new Intent(getActivity(),DetailsView.class);
intent.putExtras(extras);
startActivity(intent);
// below is the receiving activity
Intent intent = getIntent();
extras =intent.getExtras();
if (extras!=null){
try {
Video_Url = extras.getString("VidUrl");
BookUrl = extras.getString("bookUrl");
Title = extras.getString("VidTitle");
Toast.makeText(this,Video_Url,Toast.LENGTH_SHORT).show();
Toast.makeText(this,BookUrl,Toast.LENGTH_SHORT).show();
Toast.makeText(this,Title,Toast.LENGTH_SHORT).show();
videotexTitle.setText(Title);
setTitle(Title);
setVideo(Video_Url.toString());
}catch (Exception e){
e.printStackTrace();
}
} else {
Toast.makeText(this, "the extrass is empty", Toast.LENGTH_SHORT).show();
}
in the fragment
public interface NoticeFragmentListener {
public void onFragmentSendArray(ArrayType yourArray);
}
NoticeFragmentListener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeFragmentListener so we can send events to the host
listener = (NoticeFragmentListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
}
}
//metod to send array
public void SendArray(ArrayType yourArray){listener.onFragmentSendArray(yourArray);}
in de activity
public class yourActivity extends AppCompatActivity implements YourFragment.NoticeFragmentListener
and recive the array
#Override
public onFragmentSendArray(ArrayType yourArray) {
}
For simplicity use the SharedPreferences for this purpose
I have something strange going on with my application.
I am trying to send a string via Broadcast by doing the following:
1st step (Sending):
Intent intent = new Intent("INFO");
intent.putExtra("INFO_VALUE", "hello_world_2019");
2nd step (Receiving):
if ("INFO".equals(intent.getAction())) {
String abc = intent.getStringExtra("INFO_VALUE");
Log.i(TAG, "" + abc);
}
Doing the previous steps, I get a null into my abc field. Also, if I use the debugger and check my intent related to the second step, I get:
intent -> mExtras -> mMap -> value[0] -> name: "hello_world_2019"
I am confused to what is going on. The abc field is not supposed to be null, but it is in this case.
How can I populate the aforementioned field so it is not null ?
Please explain what exactly you are trying to do, if you want to send data from one activity to other than my friend this is not the correct way to do that.
If you want to send a broadcast and receive that somewhere inside your code than you need to follow the below steps:
ReceiverActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("INFO"));
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
SenderActivity.java
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("INFO");
// You can also include some extra data.
intent.putExtra("message", "Message goes here!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
I am trying to get Scanresults of wifi from one class to an other.
this is my first class:
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
// Wenn Hardware scan durchzogen wurde (wegen -->SCAN_RESULTS_AVAILABLE_ACTION)
String wifiList1;
wifiList = mainWifi.getScanResults();
wifiList1=wifiList.toString();
Toast.makeText(ctx, "Scan für AP Umgebung fertig", Toast.LENGTH_SHORT).show();
Log.v("onReceive","ausgeführt");
Log.v("ScanResults",wifiList1);
}
public List<ScanResult> getWifiList(){
return wifiList;
}
And this one here is the other class, where I want to use my data from getScanResults(), which I am saving here in wifilist as you can see.
public StringBuilder getAParound(){
StringBuilder sb = new StringBuilder();
DemoApp wf2 = new DemoApp();
DemoApp.WifiReceiver wf = wf2.new WifiReceiver();
for (int i = 0; i< wf.getWifiList().size(); i++) { // At this line Android Monitor says Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
sb.append(Integer.toString(i + 1) + ". ");
sb.append(wf.getWifiList().get(i).toString());
Log.v("getAParound","ausgeführt");
}
return sb;
}
I can see the results in Log.v("ScanResults",wifiList1); without any problems.
Can someone help me out please?
I think, you dont Instanced the wifiList, try to use 'new' key word to create a instance of the list in the constructor method maybe.
Like This:
public class WifiReceiver extends BroadcastReceiver {
private List<ScanResult> wifiList;
// This is a construtcor
public WifiReceiver(){
wifiList = new List<ScanResult>() // Here you crerate the object
}
#Override
public void onReceive(Context ctx, Intent intent) {
// Wenn Hardware scan durchzogen wurde (wegen -->SCAN_RESULTS_AVAILABLE_ACTION)
String wifiList1;
wifiList = mainWifi.getScanResults();
wifiList1=wifiList.toString();
Toast.makeText(ctx, "Scan für AP Umgebung fertig", Toast.LENGTH_SHORT).show();
Log.v("onReceive","ausgeführt");
Log.v("ScanResults",wifiList1);
}
public List<ScanResult> getWifiList(){
return wifiList;
}
its is because the object types defualt value is 'null'
I create an application that implements simple geolocation problem: once in, say, 20 minutes, it takes a LatLng coordinate.
For this purpose, from MainActivity, I initiate BroadcastReceiver to work. It instantiates LocationManager to find coordinates, which needs application context.
The problem is: due to memory reasons, Android OS can kill my MainActivity, so, BroadcastReceiver, firing next time, catches null pointer exception, referring to application's context.
Ideas:
I. I could restart the activity inside BroadcastReceiver like this:
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
but context is null due to killed Activity.
II. Maybe, the paradigm, presented in my solution, too cumbersome?
Maybe here is graceful solution, I even didn't think of?
Well, my code snippet:
public class MainActivity extends AppCompatActivity {
// ...
public void onStartSessionButtonClicked (View view) {
Intent alarmRecIntent = new Intent(this, AlarmReceiver.class);
PendingIntent mAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmRecIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)this.getSystemService(ALARM_SERVICE);
alarmManager.cancel(mAlarmIntent);
alarmManager.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
RConstants.locUpdateInterval,
mAlarmIntent
);
}
}
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
Context mContext = context;
try {
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
throw new Exception("network provider is not enabled");
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDTS,
MIN_DIST_CHANGE_FOR_UPDTS,
locationListener
);
}
catch (Exception e) { /* catch codeblock */ }
}
I really confused myself supposing that context comes NULL to BroadcastReceiver's onReceive() method, when MainActivity is killed by Android OS. The other one pointer came NULL in my code, so it caused exception.
If you interested, please, check out the code snippet below for details:
public class AlarmReceiver extends BroadcastReceiver {
LocationManager mlocationManager = null;
private CountDownTimer cdTimer = null;
private Context mContext;
final private static long MIN_TIME_BW_UPDTS = 1000 * 1; // ms
final private static float MIN_DIST_CHANGE_FOR_UPDTS = 5.0f; // meters
#Override
public void onReceive (Context context, Intent intent) {
mContext = context; // < -- 1 -- >
try {
mlocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (!mlocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
throw new Exception("network provider is not enabled");
}
// < -- 2 -- >
cdTimer = new CountDownTimer(RConstants.locUpdateTimeoutUsed, RConstants.locUpdateTimeoutUsed) {
/// other required methods overridden here ...
#Override
public void onFinish() {
mlocationManager.removeUpdates(locationListener);
mlocationManager = null; // < -- 4 -- >
Log.d("ALARM", getCurrentDateTime() + ", timeout");
}
}.start();
mlocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDTS,
MIN_DIST_CHANGE_FOR_UPDTS,
locationListener
);
}
catch (Exception e) {
Log.d("ALARM", getCurrentDateTime() + ", exc: " + e.getMessage()); < -- 5 -- >
}
}
private LocationListener locationListener = new LocationListener() {
/// other required methods overridden here ...
#Override
public void onLocationChanged(Location location) {
cdTimer.cancel();
cdTimer = null;
mlocationManager.removeUpdates(locationListener); // < -- 6 -- >
mlocationManager = null;
String latLng = " {" + location.getLatitude() + ":" + location.getLongitude() + "}";
Log.d("ALARM", getCurrentDateTime() + latLng);
}
}
}
So, context (mark "< -- 1 -- >"), coming to onReceive is not null.
In note "< -- 2 -- >" I instantiate CountDownTimer with constant RConstants.locUpdateTimeoutUsed. The problem is, it defined and assigned outside of AlarmReceiver, so, when my Activity is killed, RConstants.locUpdateTimeoutUsed comes declared, but not defined. So, CountDownTimer constructs with (0, 0) values. That's why it's instance - cdTimer, fires onFinish() hardly being started. Here it cancels update for mLocationManager and sets it to NULL. But before mLocationManager completely stopped, method onLocationChanged manages to work, so, in line < -- 6 -- > caughts exception.
I am trying to develop an Android application, which can access the current location of my phone and send it to my friend with URL.
So I use location object mLocation to access latitude and longitude of my location. FectchAddressIntentService.java is a service to obtain location address.
But it gives an error:
java.lang.IllegalArguementException:Attempt to invoke virtual method 'double android.Location.getlatitude()' on a null object reference
Here is the code of my MainActivity.java:
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
protected static final String TAG = "main-activity";
protected static final String ADDRESS_REQUESTED_KEY = "address-request-pending";
protected static final String LOCATION_ADDRESS_KEY = "location-address";
protected String message;
protected String phoneNo = "1234567890";
public void sendMessage() {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(MainActivity.this,"Sending SMS",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG);
}
}
public void startGuardianActivity(){
Intent intentViewGuardian = new Intent(this, Guardians.class);
startActivity(intentViewGuardian);
}
/**
* Provides the entry point to Google Play services.
*/
protected GoogleApiClient mGoogleApiClient;
/**
* Represents a geographical location.
*/
protected Location mLastLocation;
protected String latitude;
protected String longitude;
/**
* Tracks whether the user has requested an address. Becomes true when the user requests an
* address and false when the address (or an error message) is delivered.
* The user requests an address by pressing the Fetch Address button. This may happen
* before GoogleApiClient connects. This activity uses this boolean to keep track of the
* user's intent. If the value is true, the activity tries to fetch the address as soon as
* GoogleApiClient connects.
*/
protected boolean mAddressRequested;
/**
* The formatted location address.
*/
protected String mAddressOutput;
/**
* Receiver registered with this activity to get the response from FetchAddressIntentService.
*/
private AddressResultReceiver mResultReceiver;
/**
* Kicks off the request to fetch an address when pressed.
*/
Button btnAlert;
Button btnAddGuardian;
Button btnRemoveGuardian;
Button btnViewGuardians;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mResultReceiver = new AddressResultReceiver(new Handler());
btnAlert = (Button) findViewById(R.id.btn_Alert);
btnAddGuardian = (Button) findViewById(R.id.btn_add_guardian);
btnRemoveGuardian = (Button) findViewById(R.id.btn_remove_guardian);
btnViewGuardians = (Button) findViewById(R.id.btn_view_guardians);
btnAddGuardian.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnRemoveGuardian.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnViewGuardians.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startGuardianActivity();
}
});
// Set defaults, then update using values stored in the Bundle.
mAddressRequested = false;
mAddressOutput = "";
updateValuesFromBundle(savedInstanceState);
updateUIWidgets();
buildGoogleApiClient();
}
/**
* Updates fields based on data stored in the bundle.
*/
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Check savedInstanceState to see if the address was previously requested.
if (savedInstanceState.keySet().contains(ADDRESS_REQUESTED_KEY)) {
mAddressRequested = savedInstanceState.getBoolean(ADDRESS_REQUESTED_KEY);
}
// Check savedInstanceState to see if the location address string was previously found
// and stored in the Bundle. If it was found, display the address string in the UI.
if (savedInstanceState.keySet().contains(LOCATION_ADDRESS_KEY)) {
mAddressOutput = savedInstanceState.getString(LOCATION_ADDRESS_KEY);
displayAddressOutput();
}
}
}
/**
* Builds a GoogleApiClient. Uses {#code #addApi} to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
/**
* Runs when user clicks the Fetch Address button. Starts the service to fetch the address if
* GoogleApiClient is connected.
*/
public void fetchAddressButtonHandler(View view) {
// We only start the service to fetch the address if GoogleApiClient is connected.
if (mGoogleApiClient.isConnected() && mLastLocation != null) {
startIntentService();
}
// If GoogleApiClient isn't connected, we process the user's request by setting
// mAddressRequested to true. Later, when GoogleApiClient connects, we launch the service to
// fetch the address. As far as the user is concerned, pressing the Fetch Address button
// immediately kicks off the process of getting the address.
mAddressRequested = true;
updateUIWidgets();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// Gets the best and most recent location currently available, which may be null
// in rare cases when a location is not available.
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
latitude = String.valueOf(mLastLocation.getLatitude());
longitude = String.valueOf(mLastLocation.getLongitude());
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
}
try {
if (mLastLocation != null) {
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_LONG).show();
return;
}
}
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
}
// It is possible that the user presses the button to get the address before the
// GoogleApiClient object successfully connects. In such a case, mAddressRequested
// is set to true, but no attempt is made to fetch the address (see
// fetchAddressButtonHandler()) . Instead, we start the intent service here if the
// user has requested an address, since we now have a connection to GoogleApiClient.
if (mAddressRequested) {
startIntentService();
}
}
/**
* Creates an intent, adds location data to it as an extra, and starts the intent service for
* fetching an address.
*/
protected void startIntentService() {
// Create an intent for passing to the intent service responsible for fetching the address.
Intent intent = new Intent(this, FetchAddressIntentService.class);
// Pass the result receiver as an extra to the service.
intent.putExtra(Constants.RECEIVER, mResultReceiver);
// Pass the location data as an extra to the service.
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
// Start the service. If the service isn't already running, it is instantiated and started
// (creating a process for it if needed); if it is running then it remains running. The
// service kills itself automatically once all intents are processed.
startService(intent);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
/**
* Updates the address in the UI.
*/
protected void displayAddressOutput() {
sendMessage();
}
private void updateUIWidgets() {
if (mAddressRequested) {
btnAlert.setEnabled(false);
} else {
btnAlert.setEnabled(true);
}
}
/**
* Shows a toast with the given text.
*/
protected void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save whether the address has been requested.
savedInstanceState.putBoolean(ADDRESS_REQUESTED_KEY, mAddressRequested);
// Save the address string.
savedInstanceState.putString(LOCATION_ADDRESS_KEY, mAddressOutput);
super.onSaveInstanceState(savedInstanceState);
}
/**
* Receiver for data sent from FetchAddressIntentService.
*/
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
/**
* Receives data sent from FetchAddressIntentService and updates the UI in MainActivity.
*/
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Display the address string or an error message sent from the intent service.
mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
message = "I am in DANGER!!I need your help #"+mAddressOutput+" link: http://maps.google.com/?q="+latitude+","+longitude;
displayAddressOutput();
// Show a toast message if an address was found.
if (resultCode == Constants.SUCCESS_RESULT) {
showToast(getString(R.string.address_found));
}
mAddressRequested = false;
updateUIWidgets();
}
}
}
I tried to convert
latitude = String.valueOf(mLastLocation.getLatitude());
to
longitude = String.valueOf(mLastLocation.getLongitude());
But didn't work.
I don't know what this error is, I don`t know what NullPointerException is,
I tried to follow other Questions on Stack Overflow of similar type but didn't solve problem, Can anyone help me to get through this?
Even if you feel it might be a duplicate of other question, tell me how it is or how they are related & how to solve my problem. Thanks in advance.:-)
The error means the valiable mLastLocation is null.
So the result of this line:
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
is null. I think you should null check before these lines:
latitude = String.valueOf(mLastLocation.getLatitude());
longitude = String.valueOf(mLastLocation.getLongitude());
Because they are calling methods of mLastLocation.
That is like:
if (mLastLocation == null || !Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available, Toast.LENGTH_LONG).show();
return;
}
latitude = String.valueOf(mLastLocation.getLatitude());
longitude = String.valueOf(mLastLocation.getLongitude());