Error Boolean isFromMockProvider() on a null object reference - java

can you help me. i have an error in my code with a boolean isFromMockProvider() on a null object reference. this problem occurs when the gps on my provider is slow can you guys help me with dealing with the error
here is my code:
GetLocation getLocation = new GetLocation(getApplicationContext());
Location location = getLocation.getLocation();
boolean isMockLocation = location.isFromMockProvider();
if (isMockLocation==true){
showDialog();
}
else {
tesmock.setText("No Use Mock ");
}

Your question is lacking quite a bit of context, so this involves some guess work:
What's probably happening is that when your gps is slow, getLocation.getLocation() returns null rather than a Location object, so trying to call location.isFromMockProvider() throws a NullPointerException.
The best way to solve this would be to check whether location is null before calling that function:
Location location = getLocation.getLocation();
if(location!=null){
boolean isMockLocation = location.isFromMockProvider();
//the stuff you then do with isMockLocation
} else{
//display an error message or something saying the GPS is too slow
}

Is it like this? I'm sorry because I'm a beginner
Location location = getLocation.getLocation();
if(location!=null){
boolean isMockLocation = location.isFromMockProvider();
if (isMockLocation==true){
showDialog();
}
else {
tesmock.setText("No Use Mock ");
}
} else{
//display an error message or something saying the GPS is too slow
}

You are using 2 If statements
GetLocation getLocation = new GetLocation(getApplicationContext());
Location location = getLocation.getLocation();
if (location!=null){
boolean isMockLocation = location.isFromMockProvider();
if (isMockLocation==true){
showDialog();
}
else {
tesmock.setText("No Use Mock ");
}
} else { //show Here a dialog saying GPS is slow or Something like this
}

Related

How to run onLocationChanged method when app is closed (with onStop method)

I have this method, which manages my location:
#Override
public void onLocationChanged(final Location location) {
if(inRun){
Clocation myLocation = new Clocation(location, this.useMetricUnits());
this.updateSpeed(myLocation);
this.updateDistance(myLocation);
this.updateAverageSpeed(this.distance, this.chronometer);
if (activity.getText().toString() != ActivityRecongnizedService.getActivity()) {
activity.setText(ActivityRecongnizedService.getActivity());
activityTimer.start();
}
switch (activity.getText().toString()) {
case "STILL": still = true; break;
case "IN VEHICLE": inVehicle = true; break;
case "ON BICYCLE": onBicycle = true; break;
case "ON FOOT": onFoot = true; break;
case "RUNNING": running = true; break;
case "WALKING": walking = true;break;
case "TILTING": tilting = true; break;
}
setTimeActivity();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String[] key;
key = user.getEmail().split("#");
reference.child("Position").child(key[0]).child("latlng").setValue(new LatLng(location.getLatitude(),location.getLongitude()));
}
}
But I want this method to run when MainActivity is down. I read about this thing and there are two ways to do the same: with service or with onStop method.
I prefer the second way, with onStop method, but I don't know how to call onLocationChanged in onStop method.
I hope this could help you.
In Android, there are location manager, which provides access to system location service.
You can fire onLocationChanged event by using this class.
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Get the best provider for the criteria
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestprovider = locationManager.getBestProvider(criteria,false);
locationManager.requestLocationUpdates(bestprovider,0, 0, this);
If you insert some of this code in onStop method, the onLocationChanged event will be fired.
Override your onStop method and get the user's last known location in this manner
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location. In some rare situations this can be null.
}
refer this link for more detail https://developer.android.com/training/location/retrieve-current now that you got the user's location under the call back of onSuccessListener you can update the location to your Firebase Database/Server
Note Depending on your requirements you can run this code on a main thread or on a different thread

Why is this List sometimes null and sometimes not?

I have an activity that shows the results of the previous activity to the user. I save these results to a database. In my onCreate method I create a reference to my ViewModel and populate a List.
mAtcViewModel = new AtcViewModel(getApplication());
atcUserStatsList = mAtcViewModel.getAllUsersList();
I then go on call the save to database method after this assignment:
private void saveToDB(String playerName) {
mUser = playerName;
getAtcUser getAtcUser = new getAtcUser(playerName, this);
getAtcUser.delegate = this;
getAtcUser.execute();
}
When I get the result from onPostExecute this method is called:
#Override
public void processFinish(AtcUserStats atc_user) {
callOnChanged(atc_user);
}
This then calls a method where I am able to see the users previous stored results and adjust them with their new results but in this block of code a problem only sometimes arises, saying that atcUserStatsList is null:
try {
for (int i = 0; i < atcUserStatsList.size(); i++) {
if (atcUserStatsList.get(i).getUserName().equals(mUser)) {
mAtcViewModel.updateAtcPlayerStats(mUser, finalDartsHit, finalGamesWon, finalGamesPlayed, finalSinglesPlayed, finalDoublesPlayed, finalTreblesPlayed, finalDartsThrown,
finalSinglesDartsThrown, finalDoublesDartsThrown, finalTreblesDartsThrown, finalSinglesDartsHit, finalDoublesDartsHit, finalTreblesDartsHit, finalSecondPlace, finalThirdPlace);
}
}
} catch (Execption e) {
e.printStackTrace();
Log.d("atcUserStatsList", "Unable to save to database");
getMessage("Unable to save to database");
}
When I debug the list is populated most of the time and then when I run the app without debugging sometimes it is empty/null and the snackbar message appears and nothing is saved whereas other times it wouldn't appear and results are saved? Why would this be?
Is it anything to do with the lifecycle?
EDIT:
For example here is the list populated while debugging now this code will work:
And tbh for some reason it can be hard to get this list not Null when debugging(?).

How to make sure that NullPointerException doesn't come while showing infinite data from api.

I am fetching data from api and showing them into recyclerview.
I am using InfiniteScroll to load more data on scroll.
It works fine if I scroll smoothly but if I scroll fast I get NullPointerException as data is not being fetched on time even after I am checking if model data is not null in Adapter class.
How to avoid this situation?
Please find the code below:
#NonNull
private InfiniteScrollListener createInfiniteScrollListener() {
return new InfiniteScrollListener(10, linearLayoutManager) {
#Override public void onScrolledToEnd(final int firstVisibleItemPosition) {
offset += 10;
final List<Purchase2> itemsLocal = loadMore(offset);
refreshView(recyclerView, new PurchaseMainTestAdapter(itemsLocal, R.layout.list_orders_layout, getApplicationContext(), emptyView), firstVisibleItemPosition);
}
};
}
private List<Purchase2> loadMore(int index){
progressBar.setVisibility(View.VISIBLE);
//add loading progress view
purchases.add(new Purchase2());
adapter.notifyItemInserted(purchases.size()-1);
OneViewApi apiService =
ApiClient.getClient().create(OneViewApi.class);
Call<Orders> call;
call = apiService.getPurchaseData(auth_token,index,10);
Log.d("Called url is:", call.request().url().toString());
call.enqueue(new Callback<Orders>() {
#Override
public void onResponse(Call<Orders> call, Response<Orders> response) {
if(response.isSuccessful()){
//remove loading view
purchases.remove(purchases.size()-1);
List<Purchase2> result = response.body().getPurchases();
if(result.size()>0){
//add loaded data
purchases.addAll(result);
}else{//result size 0 means there is no more data available at server
adapter.setMoreDataAvailable(false);
Toast.makeText(getApplicationContext(),"No More Data Available",Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
//should call the custom method adapter.notifyDataChanged here to get the correct loading status
}else{
Log.e("Item list"," Load More Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<Orders> call, Throwable t) {
Log.e("Item list"," Load More Response Error "+t.getMessage());
}
});
return purchases;
}
at first use try{} catch{} then trace your code via break point to fine where exception happened
but i guess exception occur in here :purchases.remove(purchases.size()-1); that your list is null and you are trying to remove an item.(in first time) or about adding and removing items.
but for detect showing load more or not you can add null to purchases list then handle it in adapter - it's too better
Got the fix for this null pointer Exception:
1.) Added adapter code inside
try{} catch{} block
2.) Has set the flag so that on scroll it could not call the service again until last one is executed
if(!isLoading) {
isLoading = true;
final List<Purchase2> itemsLocal = loadMorePurchaseData(offset, null, null, null);
refreshView(recyclerView, new PurchaseMainAdapter(itemsLocal, R.layout.list_orders_layout, getApplicationContext(), emptyView), firstVisibleItemPosition);}
And in network call set the appropriate flag:
public void onResponse(Call<Orders> call, Response<Orders> response) {
if(response.isSuccessful()){
List<Purchase2> result = response.body().getPurchases();
if(result.size()>0){
//add loaded data
purchases.addAll(result);
}else{//result size 0 means there is no more data available at server
purchase_adapter.setMoreDataAvailable(false);
//telling adapter to stop calling load more as no more server data available
Toast.makeText(getApplicationContext(),"No More Data Available",Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
isLoading = false;
//should call the custom method adapter.notifyDataChanged here to get the correct loading status
}else{
Log.e("Item list"," Load More Response Error "+String.valueOf(response.code()));
}
Thanks everyone for giving the hint.

`locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);` always returns true

I am testing an app which uses Location services. And it returns null causing NPE (Null Pointer Exception) whenever my Location Services are turned off. So after some searching I found that
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
should return the correct boolean value but when testing my app it seems to always return true causing a NPE (Null Pointer Exception) and crashing my app.
I also read this question. Which has the exact opposite problem apparently and tried that solution. That also didn't work. I am testing on a Samsung G5. Why is this happening. Is something wrong in the code or is there another solution to my problem.
Here is the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isGPSEnabled = false;
intentThatCalled = getIntent();
String m2txt = intentThatCalled.getStringExtra("v2txt");
getLocation(m2txt);
}
public void getLocation(String n2txt) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
location = locationManager.getLastKnownLocation(bestProvider);
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
if (isGPSEnabled==true) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(n2txt);
}
}
I am still a beginner in android.
Please do help.
EDIT:
This question seems to have the same problem on the same Hardware model. Is this a Hardware Bug? If it is, is there any other possibility. I will also test on another device Note-4 and let you know.
The solution to your problem is to NEVER assume you have a location, Just because your GPS is enabled does not mean you will get a location.
At any time you can get a null location so instead of worrying about if the GPS is enabled or not you should worry about if your location returned is null or not.
getLastKnownLocation() can return a null if there is no last location

Facebook SDK for Android null pointer exception

I'm following simple tutorial at: https://developers.facebook.com/docs/android/getting-started/ and after I made everything work, I have problems onCompleted callback method.
My code looks like this:
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
}).executeAsync();
since executeMeRequestAsync method from tutorial was deprecated. Everything passes fine, and user != null evaluates as true so I come inside of the block, but on user.getName() I always get NullPointerException and I've checked while debugging GraphUser instance, and it was filled with null values. What I might be doing wrong? Can it be some problems with application configuration? I've generated new KeyHash and it's correct, so I don't know what else would be incorrect.
A NullPointerException can be thrown if findViewById(R.id.welcome) returns null. You can modify your logic to check for welcome as well:
public void onCompleted(GraphUser user, Response response) {
TextView welcome = (TextView) findViewById(R.id.welcome);
if(user != null && welcome != null) {
welcome.setText("Hello " + user.getName() + "!");
}
else {
// Log it in some way
}
}

Categories

Resources