Running GoogleApiClient on Thread results in error - java

I am new to android. I am trying to display current location in my MainActivity.
But as my network is slow I am getting the entire front end very late. So i decided to use Threads. So my location based part of the code runs silently in the background.Things worked Perfectly but my OnResume function throws an error. And I am not sure how to proceed further about it.
My Thread code in MainActivity OnCreate:
UserLocationDetails locationDetails=new UserLocationDetails();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
GoogleApiClient mGoogleApiClient;
SmsManager smsManager = SmsManager.getDefault();
private LocationRequest mLocationRequest;
TextView userLocationView;
Button settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable=new Runnable() {
#Override
public void run() {
mGoogleApiClient=new GoogleApiClient.Builder(MainActivity.this).
addConnectionCallbacks(MainActivity.this).
addOnConnectionFailedListener(MainActivity.this).
addApi(LocationServices.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
};
Thread googleApiClientThread=new Thread(runnable);
googleApiClientThread.start();
OnResume Function:
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
Logcat Error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.android.gms.common.api.GoogleApiClient.connect()' on a null object reference
at androidfactory.mafi.com.wru.MainActivity.onResume(MainActivity.java:113)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1280)
at android.app.Activity.performResume(Activity.java:6096)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3011)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3063)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
            at android.app.ActivityThread.access$800(ActivityThread.java:155)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5343)
            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:905)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Null Pointer Exception is thrown because in onResume() it is trying to call method on mGoogleApiClient, but it is not created as its creation is done inside of Runnable background thread, so there is asynchronous execution of code.
you can check before calling connect() for null reference.
protected void onResume() {
super.onResume();
if(mGoogleApiClient != null){
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
}

Why do you need to initialize the GoogleApiClient inside a thread inside onCreate?
You can just declare it without a thread.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient=new GoogleApiClient.Builder(this).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this).
addApi(LocationServices.API).build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
then your onResume should work fine.
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
Log.i(TAG, "OnResume, Connected back!");
}
About your comment :
If its NOT NULL , why should I connect again ? Only if its null I
should be connecting right ??
You cannot call connect() from a NULL Object such mGoogleApiClient. Since you initialized it on a separated thread, Android calls onCreate()-->onStart()-->onResume() one after another in this order, so when you reach onResume(), your mGoogleApiClient was not initialized yet by the thread, that's why you got the error.
Just by initializing a mGoogleApiClient you are NOT CONNECTING ANYTHING! So you need to call connect() if you plan to use any feature from Google Play Service.

Related

Receiving 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

I am new to android development and scripting with java. I am trying to create an app that allows me to toggle the internal microphone on and off via a switch. I found two scirpts (a switch script and a microphone control script) and I have peaced them together, correcting any debugging issues as I go and currently the script shows up clean. However when it is run on a phone or simulator it crashes immediately posting the following error,
android.content.Context android.content.Context.getApplicationContext()' on a null object reference"focused around my use of import android.content.Context;.
The error appears to be based on the Context.getApplicationContext request failing to find a result and thus posting NULL.
I have looked at a long list of other people suffering from similar areas, but all solutions seem to focus on changes to different areas of their code which I cannot relate back to my own scripts.
package com.example.myfirstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
public class MainActivity extends AppCompatActivity {
private Switch sw1;
Button btnGet;
Context context = getApplicationContext();
AudioManager audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE));
#Override
protected void onCreate(Bundle savedInstanceState) {
audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sw1 = findViewById(R.id.switch1);
btnGet = findViewById(R.id.getBtn);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sw1.isChecked()) {
audioManager.setMicrophoneMute(false);
}
else {
audioManager.setMicrophoneMute(true);
}
}
});
}
}
The expected result, even if the script doesn't work, is that I am able to run the app, currently the app crashes on startup and posts the following error message...
[Logcat]
2019-08-20 13:23:01.710 5559-5559/com.example.myfirstapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myfirstapp, PID: 5559
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.example.myfirstapp.MainActivity.<init>(MainActivity.java:16)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Your issue is that you are attempting to retrieve the context at initialization ie.
Context context = getApplicationContext();
There is no guarantee that getApplicationContext(); will return a valid value until the activity has been created. In this case it is null and when you attempt to access it on the next line you get a null pointer exception. You need to instead assign the variable context within the onCreate() along with the audio manager.
For example, like so:
Context context;
AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
audioManager = ((AudioManager)context.getSystemService(Context.AUDIO_SERVICE));
...
}
Another thing to note is that the Activity class is a subclass of Context, so you do not need to retrieve the application context you can instead write
AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
...
}
I guess, the problem here is this line:
Context context = getApplicationContext();
Instead of initializing it as a class field, initialize it inside onCreate() method.
For Example:
public class MainActivity extends AppCompatActivity {
private Switch sw1;
Button btnGet;
Context context;
AudioManager audioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = ((AudioManager)getSystemService(Context.AUDIO_SERVICE));
audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
context = getApplicationContext();
setContentView(R.layout.activity_main);
sw1 = findViewById(R.id.switch1);
btnGet = findViewById(R.id.getBtn);
.
.

Android crash due to GoogleApiClient

Essentially I am trying to close the GoogleApiClient when I pause or finish the fragment as it is crashing when I go back into said fragment.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mGoogleApiClient = new GoogleApiClient
.Builder(getActivity())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(getActivity(),this)
.build();
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
FATAL EXCEPTION: main
Process: com.example.conornaylor.fyp, PID: 7055
java.lang.IllegalStateException: Already managing a GoogleApiClient
with id 0
at com.google.android.gms.common.internal.zzbo.zza(Unknown Source)
at com.google.android.gms.internal.zzbau.zza(Unknown Source)
at
com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown
Source)
at
com.example.conornaylor.fyp.event.CreateEventFragment.onViewCreated(CreateEventFragment.java:164)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1343)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at
android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at
android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at
android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2063)
at
android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:725)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Fixed the issue by calling mGoogleApiClient.stopAutoManage() in the onPause method of the fragment.

Assignment in onMapReady() not working after method ends [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to implement a GoogleMap object into my code. When I use getMapASync() and assign the map created in the onMapReady() call back to the GoogleMap object I want to use, it works within that method, but once I refer to it outside of that method it says that it is still null. Why?
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
GoogleMap mMap;
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
Toast.makeText(this, "Ready to map", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Map not connected", Toast.LENGTH_SHORT).show();
}
}
else{
setContentView(R.layout.activity_main);
}
String mapType2 = Integer.toString(mMap.getMapType());
Toast.makeText(this, mapType2 + " mMap", Toast.LENGTH_SHORT).show();
//This is for debugging purposes
}
public boolean servicesOK(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,this,ERROR_DIALOG_REQUEST);
dialog.show();
}
else{
Toast.makeText(this, "Can't connect to mapping service", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap(){
if(mMap == null){
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
return (mMap != null);
}
#Override
public void onMapReady(GoogleMap map) {
this.mMap = map;
}
}
The error message I get is this:
FATAL EXCEPTION: main
Process: com.ramaya947yahoo.mymaps, PID: 1037
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ramaya947yahoo.mymaps/com.ramaya947yahoo.mymaps.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.google.android.gms.maps.GoogleMap.getMapType()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2452)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
at android.app.ActivityThread.access$900(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:152)
at android.app.ActivityThread.main(ActivityThread.java:5497)
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 'int com.google.android.gms.maps.GoogleMap.getMapType()' on a null object reference
at com.ramaya947yahoo.mymaps.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2405)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535) 
at android.app.ActivityThread.access$900(ActivityThread.java:155) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:152) 
at android.app.ActivityThread.main(ActivityThread.java:5497) 
at java.lang.reflect.Method.invoke(Native Method) 
Its because you are ivoking
String mapType2 = Integer.toString(mMap.getMapType());
in onCreate method when map is not yet initializer nor assigned.
All map initialization related code should be placed in
#Override
public void onMapReady(GoogleMap map) {
this.mMap = map;
//here
}
As this is called some time after activity is already created.

Context for intent in onpostexecute is not null but getting null exception

I've been stumped with this problem for two days now. I've checked this forum and other forums but can't get a question or answer close enough to my problem.
Basically I'm trying to execute an intent to open an activity from a non-activities onpostexecute, I'm sending the context (MainActivty.this) and string from a onMarkerClick function that is in a method in the MainActivity. This is going to a constructor in the non-activity which has the parameters for context and the string.
The issue is that I'm getting a null exception, but after debugging, the context is not null, it has the value of MainActivity, but when the intent is executed it returns a null exception. I've also tried many variations eg. Activity, getApplicationContext, this.context, (classname).context, (classname).this and tried a global context to no avail. The odd thing is I put the intent into an if statement if(context != null) and it passes through and it executes the intent which in turn gives me null exception which doesn't make sense. I know I'm new to android if anyone has any other suggestions on opening the activity that would be great thanks very much.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.quantusapps.joggertest, PID: 12253
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:131)
at android.content.ComponentName.(ComponentName.java:77)
at android.content.Intent.(Intent.java:4029)
at com.example.quantusapps.joggertest.BusCoachTramInfo.onPostExecute(BusCoachTramInfo.java:131)
at com.example.quantusapps.joggertest.BusCoachTramInfo.onPostExecute(BusCoachTramInfo.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)<
This is the Mainactivity Method with onMarkerClick
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String bctID = bctExtraMarkerInfo.get(marker.getId());
BusCoachTramInfo busCoachTramInfo = new BusCoachTramInfo(bctID, MainActivity.this);
busCoachTramInfo.execute(bctID);
return false;
}
});
This is the non-activity constructor.
Context context;
BusCoachTramInfo(String busstopID, Context context) {
this.context = context;
naptanIdUrl = "https://api.tfl.gov.uk/StopPoint/" + busstopID + "/Arrivals?app_key=" + tfl_API_KEY + "&app_id=9c0b3009";
}
This is where the null exception is happening.
#Override
protected void onPostExecute(TreeMap<Integer, String[]> Map) {
super.onPostExecute(Map);
Intent i = new Intent(context, BusArrivalTime.class);
context.startActivity(i);
One way to get things done is implementing the AsyncTask as part of a method which takes an instance of MainActivity as a parameter. The AsyncTask on the other hand would work with a WeakReference:
void doExecuteBusCoachTramInfo(final String busstopID, MainActivity activity){
final WeakReference<MainActivity> wrActivity = new WeakReference<MainActivity>(MainActivity.this);
new AsyncTask<Void, Void, TreeMap<Integer, String[]>>(){
#Override
protected TreeMap<Integer, String[]> doInBackground(Void... params)
{
// your code from BusCoachTramInfo here
}
#Override
protected void onPostExecute(TreeMap<Integer, String[]> integerTreeMap)
{
// get back to the original Activity if possible:
MainActivity activity = wrActivity.get();
if (activity != null){
Intent i = new Intent(activity, BusArrivalTime.class);
activity.startActivity(i);
}
}
}.execute();
}
This method may be part of MainActivity, but it can just as well belong to some other class.

NullPointerException since changing Google Maps API key

I'm getting an error in my Android application. The application worked perfectly and then when I was building the apk I realised my Google Maps API key wasn't going to work for multiple users, so I made a new one following the Google tutorial. Now when I install my app I get a force close - could someone help me ?
This is the logcat:
`03-20 15:42:45.209 3906-3906/project.sharethefare E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: project.sharethefare, PID: 3906
java.lang.RuntimeException: Unable to start activity ComponentInfo{project.sharethefare/project.sharethefare.CurrentLocation}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.google.android.gms.maps.SupportMapFragment.getMap()' on a null object reference
at project.sharethefare.CurrentLocation.setUpMapIfNeeded(CurrentLocation.java:55)
at project.sharethefare.CurrentLocation.onCreate(CurrentLocation.java:25)
at android.app.Activity.performCreate(Activity.java:6221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5834)
            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:1388)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
`
This is the class:
public class CurrentLocation extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
//________________________________________________________________________________________
#Override
protected void onCreate(Bundle savedInstanceState) { //auto generated
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_location);
setUpMapIfNeeded(); //part of google maps api
mMap.setMyLocationEnabled(true); //creates a new HomeScreen
}
#Override
protected void onResume() { //Auto Generated
super.onResume();
setUpMapIfNeeded(); //set up map if not already created
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.curLocMap))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
//call the method to continuously check current location
private void setUpMap() {
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
}
//called above. Used to constantly update the users position on the map
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
//create a new latitude and longitude point
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
//make global variables on home screen == to current location
HomeScreen.curLat = location.getLatitude();
HomeScreen.curLong = location.getLongitude();
HomeScreen.curLocSet = true;
//animate the camera to zoom in on position when found
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
};
public void backToHome(View view){ // called when button clicked. returns to homeScreen activity
Intent intent = new Intent(CurrentLocation.this,HomeScreen.class);
startActivity(intent);
}
}
Any help would be greatly appreciated. Thanks in advance

Categories