When I leave this Fragment and re-enter my LatLng can't be found. Throws np… and yes I know what np's are…maybe it's a Life cycle problem?

huangapple go评论127阅读模式
英文:

When I leave this Fragment and re-enter my LatLng can't be found. Throws np... and yes I know what np's are...maybe it's a Life cycle problem?

问题

以下是您提供的代码的翻译部分:

我需要在我的应用程序中的一个功能中使用我的```FINE LOCATION```。我知道什么是```null pointers```,我意识到这意味着它无法获取我的位置但我不明白为什么因为有时它可以正常工作长时间没有崩溃然后如果我退出```Activity```,然后尝试重新访问它应用程序通常会崩溃

为什么会发生这种情况

我应该尝试保存```LatLng```值以通过使用```onResume();```方法来解决这个问题吗不确定为什么它有时可以正常工作而其他时候找不到我的位置...

```readEventsNearby();```方法中这是抛出空指针异常的代码行```if (SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng) < metersToMiles) {
mPostList.add(post);}```。我在```getLocation();```方法中获取我的位置

问题出在我获取的```myLatLng```,正如您下面可以看到的为什么它起初可以工作然后当我退出 Fragment 并重新进入时会产生```null pointer```?

**Fragment**

    public class EventsNearbyFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    
        // ...(其他部分已省略)
    
        private double myLatitude, myLongitude;
        private LatLng myLatLng;
    
        // ...(其他部分已省略)
    
        private void getMyLocation() {
            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            Task<Location> task = mFusedLocationProviderClient.getLastLocation();
            task.addOnSuccessListener(location -> {
                if (location != null) {
                    myLatitude = location.getLatitude();
                    myLongitude = location.getLongitude();
    
                    // 我的位置
    
                    myLatLng = new LatLng(myLatitude, myLongitude);
                }
            });
        }
    
        // ...(其他部分已省略)
    
    }

请注意,这只是您提供代码的一部分翻译,其他部分已被省略。如果您需要整个代码的完整翻译,请随时提问。

英文:

I need to use my FINE LOCATION for one of the features in my app. I know what null pointers are and I realize that it means that it can't get my location, but I don't understand why not because sometimes it works fine, no crashes for a prolonged period of time, and then if I exit the Activity and then try to re-access it app the app crashes usually.

Why is this happening?

Should I try to save the LatLng value to solve this problem by using the onResume(); method? Not sure why it works and other times my location can't be found...

This is the line throwing the null pointer if (SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng) &lt; metersToMiles) {
mPostList.add(post);}
in the readEventsNearby(); method. I get my location in the getLocation(); method.

The issue is myLatLng which I get as you can see below. Why does it work, and then when I exit the Fragment and re-enter it produces the null pointer?

Fragment

public class EventsNearbyFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private RecyclerView mRecyclerView;
private PostAdapter mPostAdapter;
private List&lt;Post&gt; mPostList;
private SwipeRefreshLayout mSwipeRefreshLayout;
private ProgressBar mProgressBar2;
private FusedLocationProviderClient mFusedLocationProviderClient;
private double myLatitude, myLongitude;
private LatLng myLatLng;
private TextView mDistance, mNoEventsNearBy;
private Dialog mDialog;
private ProgressBar mProgressBar;
private Button mApply;
private int miles;
double metersToMiles;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events_nearby, container, false);
mProgressBar2 = view.findViewById(R.id.progress_bar);
ImageView backArrow = view.findViewById(R.id.back);
ImageView filterIcon = view.findViewById(R.id.distance_filter);
mNoEventsNearBy = view.findViewById(R.id.no_events_nearby);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 44);
}
filterIcon.setOnClickListener(v -&gt; buildDialog());
backArrow.setOnClickListener(v -&gt; getActivity().getSupportFragmentManager().popBackStack());
initializeRecyclerView(view);
setSwipeRefreshLayout(view);
return view;
}
private void buildDialog() {
mDialog = new Dialog(getContext());
mDialog.setContentView(R.layout.seek_bar);
mDistance = mDialog.findViewById(R.id.text_view);
mProgressBar = mDialog.findViewById(R.id.progress_bar);
SeekBar seekBar = mDialog.findViewById(R.id.seek_bar);
mApply = mDialog.findViewById(R.id.apply);
setCancel();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mProgressBar.setProgress(progress);
mDistance.setText(&quot;&quot; + progress + &quot;&quot;);
mApply.setOnClickListener(v -&gt; {
SharedPreferences.Editor editor = getActivity().getSharedPreferences(&quot;prefs&quot;, Context.MODE_PRIVATE).edit();
editor.putInt(&quot;miles&quot;, progress);
editor.apply();
mDialog.dismiss();
readEventsNearby();
});
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mDialog.show();
}
private void setCancel() {
Button cancel = mDialog.findViewById(R.id.cancel);
cancel.setOnClickListener(v -&gt; mDialog.dismiss());
}
private void setSwipeRefreshLayout(View view) {
mSwipeRefreshLayout = view.findViewById(R.id.refresh);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.post(() -&gt; {
mSwipeRefreshLayout.setRefreshing(true);
readEventsNearby();
});
}
private void initializeRecyclerView(View view) {
mRecyclerView = view.findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
mPostList = new ArrayList&lt;&gt;();
mPostAdapter = new PostAdapter(getContext(), mPostList);
mRecyclerView.setAdapter(mPostAdapter);
if (mRecyclerView.getAdapter().getItemCount() == 0) {
mProgressBar2.setVisibility(View.VISIBLE);
} else {
mProgressBar2.setVisibility(View.GONE);
}
}
private void getMyLocation() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &amp;&amp; ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Task&lt;Location&gt; task = mFusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(location -&gt; {
if (location != null) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
// My location
myLatLng = new LatLng(myLatitude, myLongitude);
}
});
}
@Override
public void onResume() {
super.onResume();
}
private void readEventsNearby() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(&quot;Posts&quot;);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mPostList.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Post post = dataSnapshot.getValue(Post.class);
if (post != null &amp;&amp; post.getLocation() != null) {
double eventLatitude = post.getLocation().getLatitude();
double eventLongitude = post.getLocation().getLongitude();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(&quot;prefs&quot;, Context.MODE_PRIVATE);
miles = sharedPreferences.getInt(&quot;miles&quot;, 10);
metersToMiles = miles * 1609.344;
if (SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng) &lt; metersToMiles) {
mPostList.add(post);
}
}
}
if (mPostList.size() == 0) {
mProgressBar2.setVisibility(View.GONE);
mNoEventsNearBy.setVisibility(View.VISIBLE);
} else {
mProgressBar2.setVisibility(View.GONE);
mNoEventsNearBy.setVisibility(View.GONE);
}
mPostAdapter = new PostAdapter(getContext(), mPostList);
mRecyclerView.setAdapter(mPostAdapter);
mPostAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 44) {
if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
}
@Override
public void onRefresh() {
readEventsNearby();
}
}

答案1

得分: 1

因为在执行SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng)时,myLatLng变量为null,所以导致程序崩溃。

这可能是由于以下一些可能性造成的:

  1. 你给mFusedLocationProviderClient.getLastLocation()添加了一个成功监听器,但它可能没有成功,因此myLatLng从未被赋值,将保持为null
  2. 它可能成功了,但由于某种原因你在那之前就执行了SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng),因此myLatLng仍然是null

我建议你在执行SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng)之前检查myLatLng是否为null,并根据情况做出相应的处理。

英文:

It's crashing because the myLatLng variable is null when executing SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng)

This may happen because of some of the following possibilities:

  1. You added a success listener to mFusedLocationProviderClient.getLastLocation() and it may not be succeeding, therefore myLatLng is never assigned and will be null.
  2. It may succeed but for some reason you are executing SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng) before that, therefore myLatLng is still null.

I suggest you to check for the nullability of myLatLng before executing SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng) and react according to it.

huangapple
  • 本文由 发表于 2020年9月11日 06:42:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63838564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定