英文:
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) < metersToMiles) {
in the
mPostList.add(post);}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<Post> 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 -> buildDialog());
backArrow.setOnClickListener(v -> 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("" + progress + "");
mApply.setOnClickListener(v -> {
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE).edit();
editor.putInt("miles", 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 -> mDialog.dismiss());
}
private void setSwipeRefreshLayout(View view) {
mSwipeRefreshLayout = view.findViewById(R.id.refresh);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.post(() -> {
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<>();
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 && 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();
// My location
myLatLng = new LatLng(myLatitude, myLongitude);
}
});
}
@Override
public void onResume() {
super.onResume();
}
private void readEventsNearby() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
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 && post.getLocation() != null) {
double eventLatitude = post.getLocation().getLatitude();
double eventLongitude = post.getLocation().getLongitude();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE);
miles = sharedPreferences.getInt("miles", 10);
metersToMiles = miles * 1609.344;
if (SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng) < 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 > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
}
@Override
public void onRefresh() {
readEventsNearby();
}
}
答案1
得分: 1
因为在执行SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng)
时,myLatLng
变量为null
,所以导致程序崩溃。
这可能是由于以下一些可能性造成的:
- 你给
mFusedLocationProviderClient.getLastLocation()
添加了一个成功监听器,但它可能没有成功,因此myLatLng
从未被赋值,将保持为null
。 - 它可能成功了,但由于某种原因你在那之前就执行了
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:
- You added a success listener to
mFusedLocationProviderClient.getLastLocation()
and it may not be succeeding, thereforemyLatLng
is never assigned and will benull
. - It may succeed but for some reason you are executing
SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng)
before that, thereforemyLatLng
is stillnull
.
I suggest you to check for the nullability of myLatLng
before executing SphericalUtil.computeDistanceBetween(new LatLng(eventLatitude, eventLongitude), myLatLng)
and react according to it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论