У меня есть приложение с двумя активностями. Когда перехожу во вторую активность, с базы данных 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;
Провел эксперимент, запустил активность, выключил интернет, нажал назад и перезапустил - все заполнилось. Значит все данные уже загружены с первого раза.
Вот видео, в котором наглядно всё показано.