Attempt to invoke virtual method 'Context android.content.Context.getApplicationContext()' The Next CEO of Stack OverflowiOS startMonitoringForRegion, didExitRegion, didEnterRegion, didStartMonitoringForRegion. Methods not firing properlyHow to use Geo-fencing methods in backgroundHow to get geofencing didEnterRegion delegate method call when app is closedGeo-Fencing didEnterRegion and didExitRegion methods not called?How can I eliminate false states of my monitored region in the location manager's didDetermineState method?Location Manager didEnterRegion and didExitRegion methods are not calledCLLocationManager: didEnterRegion & didExitRegionAlert method did not calledCLLocationManager didDetermineState method not called when app is in BackgroundGeofence exit region delegate method triggered even device in stable position iOS (objective-c)Attempting to create geofences that send local notifications on entry in Ionic using .watchPosition()
Rotate a column
Received an invoice from my ex-employer billing me for training; how to handle?
Help understanding this unsettling image of Titan, Epimetheus, and Saturn's rings?
How to count occurrences of text in a file?
Why do we use the plural of movies in this phrase "We went to the movies last night."?
Workaholic Formal/Informal
Preparing Indesign booklet with .psd graphics for print
What happens if you roll doubles 3 times then land on "Go to jail?"
Limits on contract work without pre-agreed price/contract (UK)
Which tube will fit a -(700 x 25c) wheel?
Why does standard notation not preserve intervals (visually)
Skipping indices in a product
Why do remote companies require working in the US?
Is micro rebar a better way to reinforce concrete than rebar?
Is it ever safe to open a suspicious html file (e.g. email attachment)?
Why has the US not been more assertive in confronting Russia in recent years?
Why didn't Khan get resurrected in the Genesis Explosion?
How fast would a person need to move to trick the eye?
Why do professional authors make "consistency" mistakes? And how to avoid them?
I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin
Do I need to enable Dev Hub in my PROD Org?
If the heap is initialized for security, then why is the stack uninitialized?
Unreliable Magic - Is it worth it?
What is ( CFMCC ) on ILS approach chart?
Attempt to invoke virtual method 'Context android.content.Context.getApplicationContext()'
The Next CEO of Stack OverflowiOS startMonitoringForRegion, didExitRegion, didEnterRegion, didStartMonitoringForRegion. Methods not firing properlyHow to use Geo-fencing methods in backgroundHow to get geofencing didEnterRegion delegate method call when app is closedGeo-Fencing didEnterRegion and didExitRegion methods not called?How can I eliminate false states of my monitored region in the location manager's didDetermineState method?Location Manager didEnterRegion and didExitRegion methods are not calledCLLocationManager: didEnterRegion & didExitRegionAlert method did not calledCLLocationManager didDetermineState method not called when app is in BackgroundGeofence exit region delegate method triggered even device in stable position iOS (objective-c)Attempting to create geofences that send local notifications on entry in Ionic using .watchPosition()
Im working on Geofences. i have creates google api client in my main activity and using the object of GoogleApiClient in another fragment. Now Im getting this exception and application getting crashed.
Here is the complete error details.
2019-03-07 20:01:56.197 10473-10473/com.example.foodtag E/UncaughtException: 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:109)
at com.example.foodtag.MainActivity.getGeofencePendingIntent(MainActivity.java:184)
at com.example.foodtag.CameraFragment.addFence(CameraFragment.java:228)
at com.example.foodtag.CameraFragment.access$000(CameraFragment.java:72)
at com.example.foodtag.CameraFragment$1.onClick(CameraFragment.java:163)
Here is my fragment class.
public class CameraFragment extends Fragment implements
AdapterView.OnItemSelectedListener, ResultCallback {
MainActivity help = new MainActivity();
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_camera, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]Manifest.permission.CAMERA, 0);
geofencingClient = LocationServices.getGeofencingClient(getContext());
tag.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
help.populateGeofenceList(); //
Toast.makeText(getContext(), "populated", Toast.LENGTH_SHORT).show();
addFence(); // error in this method
);
return view;
Here is the method definition:
private void addFence()
if (!MainActivity.mClient.isConnected())
Toast.makeText(getContext(), "MClient Not connected", Toast.LENGTH_SHORT).show();
return;
try
if (ActivityCompat.checkSelfPermission((Activity)getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions((Activity)getContext(), new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
return;
LocationServices.GeofencingApi.addGeofences(MainActivity.mClient,
help.getGeofencingRequest(), //error calling this method which is written in my main activity
help.getGeofencePendingIntent()
).setResultCallback(this);
catch (SecurityException securityException)
Log.e(TAG,"security exception");
My main activity goes like this
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LoaderManager.LoaderCallbacks<Cursor>, LocationListener
public static final int GEOFENCE_RADIUS = 250;
private static final String LOG_TAG = "MainActivity ";
private static final int MAX_LENGTH = 20;
public double latitude, longitude;
LocationManager locationManager;
public List<Geofence> mGeofenceList = new ArrayList<>();
public static GoogleApiClient mClient;
private Geofencing mGeofencing;
private boolean mIsEnabled;
private CheckBox mRingerPermissionCheckBox;
private static final int PLACE_PICKER_REQUEST = 109;
String Id;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (SaveSharedPreference.getPassword(getApplicationContext()).length() == 0)
Intent i = new Intent(getApplicationContext(), Userlogin.class);
startActivity(i);
setupViewPager();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions((Activity)this,
new String[]Manifest.permission.CAMERA,0);
return;
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
// Toast.makeText(this, ""+longitude+latitude, Toast.LENGTH_LONG).show();
buildGoogleApiClient();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
//geofencingClient = LocationServices.getGeofencingClient(this);
// Toast.makeText(this, ""+geofencingClient, Toast.LENGTH_LONG).show();
public synchronized void buildGoogleApiClient()
mClient = new GoogleApiClient.Builder(getBaseContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mClient.connect();
mGeofencing = new Geofencing(mClient,this);
Toast.makeText(this, ""+mClient, Toast.LENGTH_SHORT).show();
private void setupViewPager()
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment());
adapter.addFragment(new CameraFragment());
adapter.addFragment(new ProfileFragment());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(adapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_food);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_camera);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_account);
/* tabLayout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
switch()
case 1:
Intent i=new Intent( MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,0);
);*/
public static String random()
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++)
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
return randomStringBuilder.toString();
public void populateGeofenceList()
mGeofenceList.add(new Geofence.Builder()
.setRequestId(random())
.setCircularRegion(latitude,longitude,GEOFENCE_RADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build());
Id = random();
// Toast.makeText(this, ""+mGeofenceList, Toast.LENGTH_SHORT).show();
public GeofencingRequest getGeofencingRequest()
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
public PendingIntent getGeofencePendingIntent()
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int i, @Nullable Bundle bundle)
return null;
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor)
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader)
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
@Override
public void onNothingSelected(AdapterView<?> parent)
@Override
public void onConnected(@Nullable Bundle bundle)
Log.i(LOG_TAG,"Api connection successful");
// Toast.makeText(this , "onConnected", Toast.LENGTH_SHORT).show();
@Override
public void onConnectionSuspended(int i)
Log.i(LOG_TAG,"API Client connection suspended.");
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
Log.i(LOG_TAG,"API Connection client suspended.");
Toast.makeText(this , "onConectionFailed", Toast.LENGTH_SHORT).show();
@Override
public void onResume()
super.onResume();
buildGoogleApiClient();
@Override
public void onStop()
super.onStop();
try
if (mClient.isConnecting() catch (NullPointerException n)
Toast.makeText(this, ""+ n, Toast.LENGTH_SHORT).show();
@Override
public void onLocationChanged(Location location)
latitude=location.getLatitude();
longitude = location.getLongitude();
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
PLEASE HELP ME !
geofencing
add a comment |
Im working on Geofences. i have creates google api client in my main activity and using the object of GoogleApiClient in another fragment. Now Im getting this exception and application getting crashed.
Here is the complete error details.
2019-03-07 20:01:56.197 10473-10473/com.example.foodtag E/UncaughtException: 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:109)
at com.example.foodtag.MainActivity.getGeofencePendingIntent(MainActivity.java:184)
at com.example.foodtag.CameraFragment.addFence(CameraFragment.java:228)
at com.example.foodtag.CameraFragment.access$000(CameraFragment.java:72)
at com.example.foodtag.CameraFragment$1.onClick(CameraFragment.java:163)
Here is my fragment class.
public class CameraFragment extends Fragment implements
AdapterView.OnItemSelectedListener, ResultCallback {
MainActivity help = new MainActivity();
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_camera, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]Manifest.permission.CAMERA, 0);
geofencingClient = LocationServices.getGeofencingClient(getContext());
tag.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
help.populateGeofenceList(); //
Toast.makeText(getContext(), "populated", Toast.LENGTH_SHORT).show();
addFence(); // error in this method
);
return view;
Here is the method definition:
private void addFence()
if (!MainActivity.mClient.isConnected())
Toast.makeText(getContext(), "MClient Not connected", Toast.LENGTH_SHORT).show();
return;
try
if (ActivityCompat.checkSelfPermission((Activity)getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions((Activity)getContext(), new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
return;
LocationServices.GeofencingApi.addGeofences(MainActivity.mClient,
help.getGeofencingRequest(), //error calling this method which is written in my main activity
help.getGeofencePendingIntent()
).setResultCallback(this);
catch (SecurityException securityException)
Log.e(TAG,"security exception");
My main activity goes like this
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LoaderManager.LoaderCallbacks<Cursor>, LocationListener
public static final int GEOFENCE_RADIUS = 250;
private static final String LOG_TAG = "MainActivity ";
private static final int MAX_LENGTH = 20;
public double latitude, longitude;
LocationManager locationManager;
public List<Geofence> mGeofenceList = new ArrayList<>();
public static GoogleApiClient mClient;
private Geofencing mGeofencing;
private boolean mIsEnabled;
private CheckBox mRingerPermissionCheckBox;
private static final int PLACE_PICKER_REQUEST = 109;
String Id;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (SaveSharedPreference.getPassword(getApplicationContext()).length() == 0)
Intent i = new Intent(getApplicationContext(), Userlogin.class);
startActivity(i);
setupViewPager();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions((Activity)this,
new String[]Manifest.permission.CAMERA,0);
return;
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
// Toast.makeText(this, ""+longitude+latitude, Toast.LENGTH_LONG).show();
buildGoogleApiClient();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
//geofencingClient = LocationServices.getGeofencingClient(this);
// Toast.makeText(this, ""+geofencingClient, Toast.LENGTH_LONG).show();
public synchronized void buildGoogleApiClient()
mClient = new GoogleApiClient.Builder(getBaseContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mClient.connect();
mGeofencing = new Geofencing(mClient,this);
Toast.makeText(this, ""+mClient, Toast.LENGTH_SHORT).show();
private void setupViewPager()
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment());
adapter.addFragment(new CameraFragment());
adapter.addFragment(new ProfileFragment());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(adapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_food);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_camera);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_account);
/* tabLayout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
switch()
case 1:
Intent i=new Intent( MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,0);
);*/
public static String random()
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++)
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
return randomStringBuilder.toString();
public void populateGeofenceList()
mGeofenceList.add(new Geofence.Builder()
.setRequestId(random())
.setCircularRegion(latitude,longitude,GEOFENCE_RADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build());
Id = random();
// Toast.makeText(this, ""+mGeofenceList, Toast.LENGTH_SHORT).show();
public GeofencingRequest getGeofencingRequest()
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
public PendingIntent getGeofencePendingIntent()
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int i, @Nullable Bundle bundle)
return null;
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor)
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader)
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
@Override
public void onNothingSelected(AdapterView<?> parent)
@Override
public void onConnected(@Nullable Bundle bundle)
Log.i(LOG_TAG,"Api connection successful");
// Toast.makeText(this , "onConnected", Toast.LENGTH_SHORT).show();
@Override
public void onConnectionSuspended(int i)
Log.i(LOG_TAG,"API Client connection suspended.");
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
Log.i(LOG_TAG,"API Connection client suspended.");
Toast.makeText(this , "onConectionFailed", Toast.LENGTH_SHORT).show();
@Override
public void onResume()
super.onResume();
buildGoogleApiClient();
@Override
public void onStop()
super.onStop();
try
if (mClient.isConnecting() catch (NullPointerException n)
Toast.makeText(this, ""+ n, Toast.LENGTH_SHORT).show();
@Override
public void onLocationChanged(Location location)
latitude=location.getLatitude();
longitude = location.getLongitude();
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
PLEASE HELP ME !
geofencing
add a comment |
Im working on Geofences. i have creates google api client in my main activity and using the object of GoogleApiClient in another fragment. Now Im getting this exception and application getting crashed.
Here is the complete error details.
2019-03-07 20:01:56.197 10473-10473/com.example.foodtag E/UncaughtException: 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:109)
at com.example.foodtag.MainActivity.getGeofencePendingIntent(MainActivity.java:184)
at com.example.foodtag.CameraFragment.addFence(CameraFragment.java:228)
at com.example.foodtag.CameraFragment.access$000(CameraFragment.java:72)
at com.example.foodtag.CameraFragment$1.onClick(CameraFragment.java:163)
Here is my fragment class.
public class CameraFragment extends Fragment implements
AdapterView.OnItemSelectedListener, ResultCallback {
MainActivity help = new MainActivity();
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_camera, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]Manifest.permission.CAMERA, 0);
geofencingClient = LocationServices.getGeofencingClient(getContext());
tag.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
help.populateGeofenceList(); //
Toast.makeText(getContext(), "populated", Toast.LENGTH_SHORT).show();
addFence(); // error in this method
);
return view;
Here is the method definition:
private void addFence()
if (!MainActivity.mClient.isConnected())
Toast.makeText(getContext(), "MClient Not connected", Toast.LENGTH_SHORT).show();
return;
try
if (ActivityCompat.checkSelfPermission((Activity)getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions((Activity)getContext(), new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
return;
LocationServices.GeofencingApi.addGeofences(MainActivity.mClient,
help.getGeofencingRequest(), //error calling this method which is written in my main activity
help.getGeofencePendingIntent()
).setResultCallback(this);
catch (SecurityException securityException)
Log.e(TAG,"security exception");
My main activity goes like this
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LoaderManager.LoaderCallbacks<Cursor>, LocationListener
public static final int GEOFENCE_RADIUS = 250;
private static final String LOG_TAG = "MainActivity ";
private static final int MAX_LENGTH = 20;
public double latitude, longitude;
LocationManager locationManager;
public List<Geofence> mGeofenceList = new ArrayList<>();
public static GoogleApiClient mClient;
private Geofencing mGeofencing;
private boolean mIsEnabled;
private CheckBox mRingerPermissionCheckBox;
private static final int PLACE_PICKER_REQUEST = 109;
String Id;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (SaveSharedPreference.getPassword(getApplicationContext()).length() == 0)
Intent i = new Intent(getApplicationContext(), Userlogin.class);
startActivity(i);
setupViewPager();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions((Activity)this,
new String[]Manifest.permission.CAMERA,0);
return;
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
// Toast.makeText(this, ""+longitude+latitude, Toast.LENGTH_LONG).show();
buildGoogleApiClient();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
//geofencingClient = LocationServices.getGeofencingClient(this);
// Toast.makeText(this, ""+geofencingClient, Toast.LENGTH_LONG).show();
public synchronized void buildGoogleApiClient()
mClient = new GoogleApiClient.Builder(getBaseContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mClient.connect();
mGeofencing = new Geofencing(mClient,this);
Toast.makeText(this, ""+mClient, Toast.LENGTH_SHORT).show();
private void setupViewPager()
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment());
adapter.addFragment(new CameraFragment());
adapter.addFragment(new ProfileFragment());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(adapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_food);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_camera);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_account);
/* tabLayout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
switch()
case 1:
Intent i=new Intent( MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,0);
);*/
public static String random()
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++)
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
return randomStringBuilder.toString();
public void populateGeofenceList()
mGeofenceList.add(new Geofence.Builder()
.setRequestId(random())
.setCircularRegion(latitude,longitude,GEOFENCE_RADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build());
Id = random();
// Toast.makeText(this, ""+mGeofenceList, Toast.LENGTH_SHORT).show();
public GeofencingRequest getGeofencingRequest()
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
public PendingIntent getGeofencePendingIntent()
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int i, @Nullable Bundle bundle)
return null;
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor)
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader)
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
@Override
public void onNothingSelected(AdapterView<?> parent)
@Override
public void onConnected(@Nullable Bundle bundle)
Log.i(LOG_TAG,"Api connection successful");
// Toast.makeText(this , "onConnected", Toast.LENGTH_SHORT).show();
@Override
public void onConnectionSuspended(int i)
Log.i(LOG_TAG,"API Client connection suspended.");
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
Log.i(LOG_TAG,"API Connection client suspended.");
Toast.makeText(this , "onConectionFailed", Toast.LENGTH_SHORT).show();
@Override
public void onResume()
super.onResume();
buildGoogleApiClient();
@Override
public void onStop()
super.onStop();
try
if (mClient.isConnecting() catch (NullPointerException n)
Toast.makeText(this, ""+ n, Toast.LENGTH_SHORT).show();
@Override
public void onLocationChanged(Location location)
latitude=location.getLatitude();
longitude = location.getLongitude();
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
PLEASE HELP ME !
geofencing
Im working on Geofences. i have creates google api client in my main activity and using the object of GoogleApiClient in another fragment. Now Im getting this exception and application getting crashed.
Here is the complete error details.
2019-03-07 20:01:56.197 10473-10473/com.example.foodtag E/UncaughtException: 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:109)
at com.example.foodtag.MainActivity.getGeofencePendingIntent(MainActivity.java:184)
at com.example.foodtag.CameraFragment.addFence(CameraFragment.java:228)
at com.example.foodtag.CameraFragment.access$000(CameraFragment.java:72)
at com.example.foodtag.CameraFragment$1.onClick(CameraFragment.java:163)
Here is my fragment class.
public class CameraFragment extends Fragment implements
AdapterView.OnItemSelectedListener, ResultCallback {
MainActivity help = new MainActivity();
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_camera, container, false);
mStorageRef = FirebaseStorage.getInstance().getReference();
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]Manifest.permission.CAMERA, 0);
geofencingClient = LocationServices.getGeofencingClient(getContext());
tag.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
help.populateGeofenceList(); //
Toast.makeText(getContext(), "populated", Toast.LENGTH_SHORT).show();
addFence(); // error in this method
);
return view;
Here is the method definition:
private void addFence()
if (!MainActivity.mClient.isConnected())
Toast.makeText(getContext(), "MClient Not connected", Toast.LENGTH_SHORT).show();
return;
try
if (ActivityCompat.checkSelfPermission((Activity)getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions((Activity)getContext(), new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
return;
LocationServices.GeofencingApi.addGeofences(MainActivity.mClient,
help.getGeofencingRequest(), //error calling this method which is written in my main activity
help.getGeofencePendingIntent()
).setResultCallback(this);
catch (SecurityException securityException)
Log.e(TAG,"security exception");
My main activity goes like this
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LoaderManager.LoaderCallbacks<Cursor>, LocationListener
public static final int GEOFENCE_RADIUS = 250;
private static final String LOG_TAG = "MainActivity ";
private static final int MAX_LENGTH = 20;
public double latitude, longitude;
LocationManager locationManager;
public List<Geofence> mGeofenceList = new ArrayList<>();
public static GoogleApiClient mClient;
private Geofencing mGeofencing;
private boolean mIsEnabled;
private CheckBox mRingerPermissionCheckBox;
private static final int PLACE_PICKER_REQUEST = 109;
String Id;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (SaveSharedPreference.getPassword(getApplicationContext()).length() == 0)
Intent i = new Intent(getApplicationContext(), Userlogin.class);
startActivity(i);
setupViewPager();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions((Activity)this,
new String[]Manifest.permission.CAMERA,0);
return;
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
// Toast.makeText(this, ""+longitude+latitude, Toast.LENGTH_LONG).show();
buildGoogleApiClient();
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION, 101);
//geofencingClient = LocationServices.getGeofencingClient(this);
// Toast.makeText(this, ""+geofencingClient, Toast.LENGTH_LONG).show();
public synchronized void buildGoogleApiClient()
mClient = new GoogleApiClient.Builder(getBaseContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mClient.connect();
mGeofencing = new Geofencing(mClient,this);
Toast.makeText(this, ""+mClient, Toast.LENGTH_SHORT).show();
private void setupViewPager()
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment());
adapter.addFragment(new CameraFragment());
adapter.addFragment(new ProfileFragment());
ViewPager viewPager = (ViewPager) findViewById(R.id.container);
viewPager.setAdapter(adapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_food);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_camera);
tabLayout.getTabAt(2).setIcon(R.drawable.ic_account);
/* tabLayout.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View v)
switch()
case 1:
Intent i=new Intent( MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,0);
);*/
public static String random()
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++)
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
return randomStringBuilder.toString();
public void populateGeofenceList()
mGeofenceList.add(new Geofence.Builder()
.setRequestId(random())
.setCircularRegion(latitude,longitude,GEOFENCE_RADIUS)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build());
Id = random();
// Toast.makeText(this, ""+mGeofenceList, Toast.LENGTH_SHORT).show();
public GeofencingRequest getGeofencingRequest()
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
public PendingIntent getGeofencePendingIntent()
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
return PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
@NonNull
@Override
public Loader<Cursor> onCreateLoader(int i, @Nullable Bundle bundle)
return null;
@Override
public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor)
@Override
public void onLoaderReset(@NonNull Loader<Cursor> loader)
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
@Override
public void onNothingSelected(AdapterView<?> parent)
@Override
public void onConnected(@Nullable Bundle bundle)
Log.i(LOG_TAG,"Api connection successful");
// Toast.makeText(this , "onConnected", Toast.LENGTH_SHORT).show();
@Override
public void onConnectionSuspended(int i)
Log.i(LOG_TAG,"API Client connection suspended.");
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
Log.i(LOG_TAG,"API Connection client suspended.");
Toast.makeText(this , "onConectionFailed", Toast.LENGTH_SHORT).show();
@Override
public void onResume()
super.onResume();
buildGoogleApiClient();
@Override
public void onStop()
super.onStop();
try
if (mClient.isConnecting() catch (NullPointerException n)
Toast.makeText(this, ""+ n, Toast.LENGTH_SHORT).show();
@Override
public void onLocationChanged(Location location)
latitude=location.getLatitude();
longitude = location.getLongitude();
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
@Override
public void onProviderEnabled(String provider)
@Override
public void onProviderDisabled(String provider)
PLEASE HELP ME !
geofencing
geofencing
asked Mar 7 at 14:57
Venkatesh dharavathVenkatesh dharavath
32
32
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55046766%2fattempt-to-invoke-virtual-method-context-android-content-context-getapplication%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55046766%2fattempt-to-invoke-virtual-method-context-android-content-context-getapplication%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown