С тех пор, как я обновил свои реализации приложений, я не смог запустить приложение.
Я получаю сообщение об ошибке «java.lang.IllegalStateException: FragmentManager уже выполняет транзакции» и не может найти решение этой проблемы ...
public class MainActivity extends AppCompatActivity {
private Toolbar mainToolbar;
private FirebaseAuth mAuth;
private FirebaseFirestore firebaseFirestore;
private String current_user_id;
private BottomNavigationView mainbottomNav;
private HomeFragment accountFragment;
private NotificationFragment notificationFragment;
private FilterFragment filterFragment;
private UserProfileFragment userProfileFragment;
private MapFragment homeFragment;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
if (mAuth.getCurrentUser() != null) {
current_user_id = mAuth.getCurrentUser().getUid();
mainbottomNav = findViewById(R.id.mainBottomNav);
BottomNavigationViewHelper.disableShiftMode(mainbottomNav);
BottomNavigationMenuView bottomNavigationMenuView =
(BottomNavigationMenuView) mainbottomNav.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(2);
BottomNavigationItemView itemView = (BottomNavigationItemView) v;
// FRAGMENTS
homeFragment = new MapFragment();
notificationFragment = new NotificationFragment();
accountFragment = new HomeFragment();
filterFragment = new FilterFragment();
userProfileFragment = new UserProfileFragment();
initializeFragment();
mainbottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
switch (item.getItemId()) {
case R.id.bottom_action_home:
replaceFragment(homeFragment, currentFragment);
return true;
case R.id.bottom_action_filters:
replaceFragment(filterFragment, currentFragment);
return true;
case R.id.bottom_action_account:
replaceFragment(userProfileFragment, currentFragment);
replaceFragment(accountFragment, currentFragment);
return true;
case R.id.bottom_action_notif:
replaceFragment(notificationFragment, currentFragment);
notifCount.setVisibility(View.GONE);
return true;
default:
return false;
}
}
});
private void initializeFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, homeFragment);
fragmentTransaction.add(R.id.main_container, filterFragment);
fragmentTransaction.add(R.id.main_container, notificationFragment);
fragmentTransaction.add(R.id.main_container, accountFragment);
fragmentTransaction.add(R.id.main_container, userProfileFragment);
fragmentTransaction.hide(filterFragment);
fragmentTransaction.hide(notificationFragment);
fragmentTransaction.hide(accountFragment);
fragmentTransaction.hide(userProfileFragment);
fragmentTransaction.commit();
}
@SuppressLint("RestrictedApi")
private void replaceFragment(Fragment currentFragment, Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (currentFragment == homeFragment) {
fragmentTransaction.hide(userProfileFragment);
fragmentTransaction.hide(filterFragment);
fragmentTransaction.hide(accountFragment);
fragmentTransaction.hide(notificationFragment);
if (addEventBtn.isEnabled()) {
addEventBtn.setVisibility(View.VISIBLE);
}
addPostBtn.setEnabled(false);
}
if (currentFragment == accountFragment) {
fragmentTransaction.hide(filterFragment);
fragmentTransaction.hide(homeFragment);
fragmentTransaction.hide(notificationFragment);
addPostBtn.setEnabled(true);
if (addEventBtn.isEnabled()) {
addEventBtn.setVisibility(View.GONE);
}
}
if (currentFragment == notificationFragment) {
fragmentTransaction.hide(userProfileFragment);
fragmentTransaction.hide(filterFragment);
fragmentTransaction.hide(homeFragment);
fragmentTransaction.hide(accountFragment);
addPostBtn.setEnabled(false);
if (addEventBtn.isEnabled()) {
addEventBtn.setVisibility(View.GONE);
}
}
if (currentFragment == filterFragment) {
fragmentTransaction.hide(userProfileFragment);
fragmentTransaction.hide(notificationFragment);
fragmentTransaction.hide(homeFragment);
fragmentTransaction.hide(accountFragment);
addPostBtn.setEnabled(false);
if (addEventBtn.isEnabled()) {
addEventBtn.setVisibility(View.GONE);
}
}
fragmentTransaction.show(currentFragment);
fragmentTransaction.commit();
//fragmentTransaction.replace(R.id.main_container, fragment);
}
}
Ошибка:
java.lang.RuntimeException: невозможно запустить действие. ComponentInfo {com.app.Activities.MainActivity}: java.lang.IllegalStateException: FragmentManager уже выполняет транзакции
РЕДАКТИРОВАТЬ 2: После дальнейших исследований, я смог найти то, что на самом деле стало причиной аварии. Очевидно, что всякий раз, когда я использую «addSnapshotListener» для фрагмента, я получаю ошибку «FragmentManager уже выполняет транзакции». Я полагаю, что это как-то связано с "getActivity ()", однако я не могу понять, почему он вызывает сбой приложения. Я отсоединяю слушателя, как предложено в документации Firebase.
Код фрагмента:
public class NotificationFragment extends Fragment {
private RecyclerView mNotificationList;
private NotificationsAdapter notificationsAdapter;
private List<Notifications> mNotifList;
private FirebaseFirestore mFirestore;
private String TAG = "Notification Fragment";
public NotificationFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_notification, container, false);
mNotifList = new ArrayList<>();
mNotificationList = (RecyclerView) v.findViewById(R.id.notification_list);
notificationsAdapter = new NotificationsAdapter(mNotifList);
mNotificationList.setHasFixedSize(true);
mNotificationList.setLayoutManager(new LinearLayoutManager(container.getContext()));
mNotificationList.setAdapter(notificationsAdapter);
mFirestore = FirebaseFirestore.getInstance();
final String current_user_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
Query query = mFirestore.collection("Users").document(current_user_id).collection("Notifications");
ListenerRegistration registration = query.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (documentSnapshots != null && !documentSnapshots.isEmpty()) {
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
final String notificationId = doc.getDocument().getId();
Notifications notifications = doc.getDocument().toObject(Notifications.class).withId(notificationId);
mNotifList.add(notifications);
Log.d(TAG, "list ids: " + notificationId);
notificationsAdapter.notifyDataSetChanged();
}
}
}
}
});
registration.remove();
return v;
}