这是我的代码。我正在编写一个应用程序并使用firebase加载随机用户照片,但是在我对这个片段进行了多次操作之后,它会因内存泄漏而崩溃。我一直在寻找它。请帮助:)
我的应用如何运作:
公共类RatingFragment扩展Fragment {
private TabLayout tabLayout;
private ImageView imageView;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private DataSnapshot childSnapshot;
private User user, newUser;
private RatingBar ratingBar;
private Random random = new Random(System.currentTimeMillis());
public RatingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view;
view = inflater.inflate(R.layout.fragment_rating, container, false);
tabLayout = view.findViewById(R.id.tabLayoutRating);
tabLayout.setTabTextColors(ColorStateList.valueOf(Color.WHITE));
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference().child("users");
imageView = view.findViewById(R.id.ivRandomPhoto);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int userCount = (int) dataSnapshot.getChildrenCount();
int rand = random.nextInt(userCount);
Iterator itr = dataSnapshot.getChildren().iterator();
for (int i = 0; i < rand; i++) {
itr.next();
}
childSnapshot = (DataSnapshot) itr.next();
user = childSnapshot.getValue(User.class);
imageView.setImageURI(Uri.parse(user.getNewPhoto()));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
ratingBar = view.findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
newUser = new User (user.getUserId(),user.getUsername(),user.getPhotos(),user.getAverageRating(),user.getPoints()+1,user.getNewPhoto());
databaseReference.child(user.getUserId()).setValue(newUser);
ratingBar.setRating(0);
}
});
TabLayout.Tab tab = tabLayout.getTabAt(1);
tab.select();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
CropFragment cropFragment = new CropFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_framelayout, cropFragment);
fragmentTransaction.commit();
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
}
答案 0 :(得分:0)
您正在onCreateView中添加ValueEventListener,但据我所知,您无法随时删除它。除此之外,我还没有看到任何其他内存泄漏源。