0

У меня есть приложение с двумя активностями. Когда перехожу во вторую активность, с базы данных firebase берутся числа, на основании которых заполняются progress bar'ы, находящиеся во фрагменте. У меня проблема в том, что когда я захожу в активность, прогресс бары не заполняются, но если нажать системную кнопку назад (что вернет нас в предыдущую активность), а потом снова запустить активность, прогресс бары заполнены! Я вообще без понятия, почему так происходит. Прогресс бары заполняются в onCreateView() фрагмента, чтение объекта с базы данных происходит в onCreate() активности. При пересоздании фрагмента ничего не изменяется, из чего я сделал вывод, что проблема в загрузке с базы данных. Но почему такая проблема появляется, ведь когда я перехожу в активность с фрагментом второй раз, выполняется тот же код, что выполнялся и в первый раз!

Я искренне надеюсь на вашу поддержку, потому что я уже совсем не знаю, что делать.


Код метода onCreate():

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    auth = FirebaseAuth.getInstance();
    user = auth.getCurrentUser();



    if (user != null) {
        // already signed in
        uid = user.getUid();
        name = user.getDisplayName();
        email = user.getEmail();
    } else {
        // not signed in
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()//,
                                // new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()
                                // new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()
                        ))
                        .build(),
                200);
    }

    database = FirebaseDatabase.getInstance();

    if (uid != null) {
        charRef = database.getReference("Users").child(uid).child("Character");

        charRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                    myCharacter = dataSnapshot.getValue(Runner.class);
                    SnickNameBottom = myCharacter.getNickname();
                    currentSpeed = myCharacter.getSpeed();
                    currentStr = myCharacter.getStrength();
                    currentStamina = myCharacter.getStamina();
                    currentIntuition = myCharacter.getIntuition();
                    SlevelBottom = getString(R.string.level) + myCharacter.getCurrentLevel();
                    nickNameBottom = (TextView) findViewById(R.id.nickNameBottom);
                    levelBottom = (TextView) findViewById(R.id.levelBottom);
                    nickNameBottom.setText(SnickNameBottom);
                    levelBottom.setText(SlevelBottom);
                    stamFromEq = myCharacter.getStaminaFromEquipment();
                    strFromEq = myCharacter.getStrengthFromEquipment();
                    spdFromEq = myCharacter.getSpeedFromEquiment();
                    winsInARow = myCharacter.getWinsInARow();
                    wins = myCharacter.getWins();
                    defeats = myCharacter.getDefeats();
                    tournamentsTotal = myCharacter.getTournamentsTotal();
                    winsInTournaments = myCharacter.getWinsInTournaments();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value


            }
        });
    }
    if (savedInstanceState == null) {
        getFragmentManager()
                .beginTransaction()
                .add(R.id.container, new CardFrontFragment())
                .commit();
    }

}

Код метода onCreateView() фрагмента:

@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.card_front, container, false);
            nickNameBottom = (TextView) view.findViewById(R.id.nickNameBottom);
            levelBottom = (TextView) view.findViewById(R.id.levelBottom);
            progressStr = (RoundCornerProgressBar) view.findViewById(R.id.strengthbar);
            progressSpd = (RoundCornerProgressBar) view.findViewById(R.id.speedbar);
            progressStamina = (RoundCornerProgressBar) view.findViewById(R.id.staminabar);
            progressIntuition = (RoundCornerProgressBar) view.findViewById(R.id.intuitionBar);

            nickNameBottom.setText(SnickNameBottom);
            levelBottom.setText(SlevelBottom);

            statsSum = (float) currentSpeed + currentStamina + currentStr;
            progressStr.setMax(statsSum);
            progressStr.setProgress((float)currentStr);
            progressStr.setSecondaryProgress((float) strFromEq);

            progressSpd.setMax(statsSum);
            progressSpd.setProgress((float)currentSpeed);
            progressSpd.setSecondaryProgress((float)spdFromEq);

            progressStamina.setMax(statsSum);
            progressStamina.setProgress((float)currentStamina);
            progressStamina.setSecondaryProgress((float)stamFromEq);

            progressIntuition.setMax(statsSum);
            progressIntuition.setProgress((float) currentIntuition);

            TextView totalPlayed = (TextView) view.findViewById(R.id.total);
            totalPlayed.setText(getString(R.string.total) + " " + (wins + defeats));

            TextView winsT = (TextView) view.findViewById(R.id.wins);
            winsT.setText(getString(R.string.wins) + " " + wins);

            TextView defeatsT = (TextView) view.findViewById(R.id.defeats);
            defeatsT.setText(getString(R.string.defeats) + " " + defeats);

            TextView tournamentsTotalT = (TextView) view.findViewById(R.id.tournamentsTotal);
            tournamentsTotalT.setText(getString(R.string.tournamentsTotal) + " " + tournamentsTotal);

            TextView tournamentsWinsT = (TextView) view.findViewById(R.id.tournamentsWins);
            tournamentsWinsT.setText(getString(R.string.tournamentsWins) + " " + winsInTournaments);

            TextView winsInARowT = (TextView) view.findViewById(R.id.winsInARow);
            winsInARowT.setText(getString(R.string.winsInARow) + " " + winsInARow);

            return view;

Провел эксперимент, запустил активность, выключил интернет, нажал назад и перезапустил - все заполнилось. Значит все данные уже загружены с первого раза.

Вот видео, в котором наглядно всё показано.

1
  • если есть какие-то вопросы, задавайте, возможно я что-то нужное не сказал.
    – Maxgmer
    21 ноя 2016 в 5:16

2 ответа 2

1
+50

У вас данные могут быть получены уже после вызова onCreateView фрагмента. Не совсем понимаю как у вас данные передаются из активити во фрагмент, я бы предложил загружать данные во фрагменте или как-то проинформировать его о том что данные загружены. Например во фрагменте:

private boolean mViewCreated = false;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.card_front, container, false);
    nickNameBottom = (TextView) view.findViewById(R.id.nickNameBottom);
    levelBottom = (TextView) view.findViewById(R.id.levelBottom);
    progressStr = (RoundCornerProgressBar) view.findViewById(R.id.strengthbar);
    progressSpd = (RoundCornerProgressBar) view.findViewById(R.id.speedbar);
    progressStamina = (RoundCornerProgressBar) view.findViewById(R.id.staminabar);
    progressIntuition = (RoundCornerProgressBar) view.findViewById(R.id.intuitionBar);

    return view;
}

public void onDataLoaded() {
    tryShowData();
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mViewCreated = true;
    tryShowData();
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    mViewCreated = false;
}

private void tryShowData() {
    if (!mViewCreated) {
        return;
    }
    nickNameBottom.setText(SnickNameBottom);
    levelBottom.setText(SlevelBottom);

    statsSum = (float) currentSpeed + currentStamina + currentStr;
    progressStr.setMax(statsSum);
    progressStr.setProgress((float)currentStr);
    progressStr.setSecondaryProgress((float) strFromEq);

    progressSpd.setMax(statsSum);
    progressSpd.setProgress((float)currentSpeed);
    progressSpd.setSecondaryProgress((float)spdFromEq);

    progressStamina.setMax(statsSum);
    progressStamina.setProgress((float)currentStamina);
    progressStamina.setSecondaryProgress((float)stamFromEq);

    progressIntuition.setMax(statsSum);
    progressIntuition.setProgress((float) currentIntuition);

    TextView totalPlayed = (TextView) view.findViewById(R.id.total);
    totalPlayed.setText(getString(R.string.total) + " " + (wins + defeats));

    TextView winsT = (TextView) view.findViewById(R.id.wins);
    winsT.setText(getString(R.string.wins) + " " + wins);

    TextView defeatsT = (TextView) view.findViewById(R.id.defeats);
    defeatsT.setText(getString(R.string.defeats) + " " + defeats);

    TextView tournamentsTotalT = (TextView) view.findViewById(R.id.tournamentsTotal);
    tournamentsTotalT.setText(getString(R.string.tournamentsTotal) + " " + tournamentsTotal);

    TextView tournamentsWinsT = (TextView) view.findViewById(R.id.tournamentsWins);
    tournamentsWinsT.setText(getString(R.string.tournamentsWins) + " " + winsInTournaments);

    TextView winsInARowT = (TextView) view.findViewById(R.id.winsInARow);
    winsInARowT.setText(getString(R.string.winsInARow) + " " + winsInARow);
}

И в активити:

charRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // This method is called once with the initial value and again
        // whenever data at this location is updated.
            myCharacter = dataSnapshot.getValue(Runner.class);
            SnickNameBottom = myCharacter.getNickname();
            currentSpeed = myCharacter.getSpeed();
            currentStr = myCharacter.getStrength();
            currentStamina = myCharacter.getStamina();
            currentIntuition = myCharacter.getIntuition();
            SlevelBottom = getString(R.string.level) + myCharacter.getCurrentLevel();
            nickNameBottom = (TextView) findViewById(R.id.nickNameBottom);
            levelBottom = (TextView) findViewById(R.id.levelBottom);
            nickNameBottom.setText(SnickNameBottom);
            levelBottom.setText(SlevelBottom);
            stamFromEq = myCharacter.getStaminaFromEquipment();
            strFromEq = myCharacter.getStrengthFromEquipment();
            spdFromEq = myCharacter.getSpeedFromEquiment();
            winsInARow = myCharacter.getWinsInARow();
            wins = myCharacter.getWins();
            defeats = myCharacter.getDefeats();
            tournamentsTotal = myCharacter.getTournamentsTotal();
            winsInTournaments = myCharacter.getWinsInTournaments();

            Fragment fragment = getSupportFragmentManager()
                    .findFragmentById(R.id.container);
            if (fragment != null) {
                ((CardFrontFragment)fragment).onDataLoaded();
            }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value


    }
});
7
  • в tryShowData() нужно передать view фрагмента для метода view.findViewById(), использующегося внутри фрагмента. Как это сделать из активити?
    – Maxgmer
    22 ноя 2016 в 17:15
  • Не нужно. view инициализируется в onCreateView. Соответственно levelBottom и прочие - это поляфрагмента, которые заполняются в onCreateView. Если onDataChange вызовется когда после вызова onCreateView, то будут заполнены сохраненные вью, если нет, то данные отобразятся как только вызовется onCreateView. Но я по прежнему не понимаю как вы передаете данные из активити во фрагмент. Т.е., например, currentSpeed. Где он передается во фрагмент? Или фрагмент - это вложенный класс активности? Вложенный класс фрагмента это не очень хорошо.
    – lllyct
    22 ноя 2016 в 17:31
  • вложенный класс у меня, почему не хорошо?
    – Maxgmer
    22 ноя 2016 в 17:34
  • а, не нужен view, просто перенесу в onCreateView, точно
    – Maxgmer
    22 ноя 2016 в 17:37
  • В вашем случае вложенный класс будет работать, но, теоретически, это могло бы поломать жизненный цикл фрагмента. Я бы посоветовал избегать вложенных классов, так как они содержат неявную ссылку на экземпляр внешнего класса, если не помечены как static. А это может привести к неожиданным результатам.
    – lllyct
    22 ноя 2016 в 17:41
0

Попробуйте устанавливать данные в методе onViewCreated() фрагмента после выполнения super.onViewCreated();

1
  • не помогло, все также:(
    – Maxgmer
    21 ноя 2016 в 20:33

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.