I'm trying to get a user name from the database and set it as text on the screen.
I have 3 Activity and Fragment objects.
The first activity is RegisterActivity. After the user inserts his email and password, and clicks the next button, a pop up with input fields for user details appears.
Users should fill all fields and click the save button.
For the OnClick action of the save button, all users details are written to a real time database.
In the main Activity, I want to show the user name from the database.
In debug mode, I get the user name, but it won't show on the TextView (private TextView mWelcomeText).
Here is what I've done:
package com.enjoyapp.weddapp.Activities;
public class MainActivity extends AppCompatActivity {
private TextView mWelcomeText;
private String mGreetings;
private String mDisplayName;
private FirebaseAuth mAuth;
private FirebaseDatabase db;
private DatabaseReference users;
private MethodManager mm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
users = db.getReference("Users");
mWelcomeText = findViewById(R.id.mWelcomeText);
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
getDataFromUsersDetails();
mWelcomeText.setText(mDisplayName);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment())
.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_favorites:
selectedFragment = new FavoritesFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment)
.commit();
return true;
}
};
public void getDataFromUsersDetails() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
mDisplayName = ds.child(mAuth.getCurrentUser().getUid()).child("mEventOwnerName").getValue(String.class);
Log.d("Database reader", mDisplayName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
users.addListenerForSingleValueEvent(eventListener);
}
public String getGreetings() {
mm = new MethodManager();
if (mm.getTime() >= 6 && mm.getTime() < 12) {
return "Good morning";
} else if (mm.getTime() >= 12 && mm.getTime() < 18) {
return "Good afternoon";
} else if (mm.getTime() >= 18 && mm.getTime() < 22) {
return "Good evening";
} else if (mm.getTime() >= 22 && mm.getTime() < 6) {
return "Good night";
}
return null;
}
}
I want the text to be displayed on the screen, in the field of private TextView mWelcomeText.
In the layout_main I can see the text view with the tool:text="something";
But when I am running it on a real device or an emulator, just an empty place appears.
UPDATE:
public void getDataFromUsersDetails() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
mDisplayName = ds.child(mAuth.getCurrentUser().getUid()).child("mEventOwnerName").getValue(String.class);
Log.d("Database reader", mDisplayName);
user = new User();
user.setmDisplayName(mDisplayName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
users.addListenerForSingleValueEvent(eventListener);
}
mWelcomeText = findViewById(R.id.mWelcomeText);
mWelcomeText.setText(user.setGreetingsOnTop());
public String setGreetingsOnTop(){
MethodManager mm = new MethodManager();
String greetings = null;
if (mm.getTime() >= 6 && mm.getTime() < 12) {
greetings = "Good morning";
} else if (mm.getTime() >= 12 && mm.getTime() < 18) {
greetings = "Good afternoon";
} else if (mm.getTime() >= 18 && mm.getTime() < 22) {
greetings = "Good evening";
} else if (mm.getTime() >= 22 && mm.getTime() < 6) {
greetings = "Good night";
}
return getmDisplayName() +""+greetings;
}
I would request you take a look on this two line of Main Activity.
getDataFromUsersDetails();
mWelcomeText.setText(mDisplayName); //mDisplayName is null initially
getDataFromUsersDetails is making an asynchronous call using valueEventListener. When the response is coming you are assigning the value to mDisplayName but it will not update in textView.
In the For loop you need to explicitly update mWelcomeText.setText(mDisplayName);
You can must update the textview inside the valueEventListener
for (DataSnapshot ds : dataSnapshot.getChildren()) {
mDisplayName = ds.child(mAuth.getCurrentUser().getUid()).child("mEventOwnerName").getValue(String.class);
Log.d("Database reader", mDisplayName);
mWelcomeText.setText(mDisplayName);//here
}
Related
I wanted to ask for your help with something that eating my brain out since I am new at Firebase and android studio. I created this attendance app but only the admin can log into the system then as the admin he has the ability to add students and teachers so that they can have access to the system when they want to log in the system. but once I add a teacher he cannot log in the system. the system saying incorrect username and password while the credentials are all well-typed. is there a way to give access to a user without creating the sign-up page. I am using firebase as the database. here is my code for adding a teacher
public class FacultyAddActivity extends AppCompatActivity {
private Toolbar addFacTool;
private EditText facName, facEmail, facPhone, facID, facAddress;
private Spinner facSpinner;
private String[] designList;
private String selectDesign;
private Button addFacBtn;
private String intentMode, intentFac;
private DatabaseReference facReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_add);
addFacTool = findViewById(R.id.toolAdd);
setSupportActionBar(addFacTool);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
intentFac = intent.getStringExtra("FACULTY");
intentMode = intent.getStringExtra("MODE");
facName = findViewById(R.id.txtLName);
facEmail = findViewById(R.id.txtLEmail);
facAddress = findViewById(R.id.txtLAddress);
facPhone = findViewById(R.id.txtLPhone);
facID = findViewById(R.id.txtLID);
addFacBtn = findViewById(R.id.btnLSubmit);
facSpinner = findViewById(R.id.spnDes);
designList = getResources().getStringArray(R.array.designation);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(FacultyAddActivity.this, android.R.layout.simple_list_item_1, designList);
facSpinner.setAdapter(arrayAdapter);
facSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectDesign = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
addFacBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addFaculty();
}
});
}
private void addFaculty() {
String name = facName.getText().toString();
String email = facEmail.getText().toString();
String address = facAddress.getText().toString();
String phone = facPhone.getText().toString();
String ID = facID.getText().toString();
if (name.isEmpty()){
facName.setError("Enter lecturer name");
facName.requestFocus();
}
else if (email.isEmpty()){
facEmail.setError("Enter lecturer email");
facEmail.requestFocus();
}
else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
facEmail.setError("Enter lecturer email");
facEmail.requestFocus();
}
else if (address.isEmpty()){
facAddress.setError("Enter lecturer address");
facAddress.requestFocus();
}
else if (phone.isEmpty()){
facPhone.setError("Enter lecturer phone number");
facPhone.requestFocus();
}
else if (selectDesign.isEmpty() && selectDesign.equals("Select Designation")){
Toast.makeText(getApplicationContext(), "Select Designation", Toast.LENGTH_SHORT).show();
}
else if (ID.isEmpty()){
facID.setError("Enter lecturer ID");
facID.requestFocus();
}
else{
facReference = FirebaseDatabase.getInstance().getReference().child("Department").child("Lecturer");
String key = facReference.push().getKey();
FacultyConstructor facultyConstructor = new FacultyConstructor(ID, name, intentFac, selectDesign, phone, email, address, "123456", intentMode);
facReference.child(key).setValue(facultyConstructor).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Lecturer added successfully", Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId() == android.R.id.home){
this.finish();
}
return super.onOptionsItemSelected(item);
}
}
public class UserprofileActivity extends AppCompatActivity {
// VARIABLES
TextView fullName, userName, location, motorcycle;
TextInputLayout fullNameInput, emailInput, motorcycleInput, passwordInput;
// GLOBAL VARIABLES TO HOLD USER DATA INSIDE THIS ACTIVITY
String _NAME, _USERNAME, _EMAIL, _LOCATION, _MOTORCYCLE, _PASSWORD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userprofile);
reference = FirebaseDatabase.getInstance().getReference("users");
// HOOKS
fullName = findViewById(R.id.profileFullName);
userName = findViewById(R.id.profileUsername);
location = findViewById(R.id.profileLocalization);
motorcycle = findViewById(R.id.profileMotorcycle);
fullNameInput = findViewById(R.id.profile_FullName);
emailInput = findViewById(R.id.profile_Email);
motorcycleInput = findViewById(R.id.profile_Motorcycle);
passwordInput = findViewById(R.id.profile_Password);
// SHOW ALL DATA
showAllUserData();
}
private void showAllUserData() {
Intent intent = getIntent();
_NAME = intent.getStringExtra("name");
_USERNAME = intent.getStringExtra("username");
_EMAIL = intent.getStringExtra("email");
_LOCATION = intent.getStringExtra("location");
_MOTORCYCLE = intent.getStringExtra("motorcycle");
_PASSWORD = intent.getStringExtra("password");
// this variable goes to (TextInputLayout "fullNameInput) and (TextView fullName) this goes to update the full name of the user and also is motorcycle brand. It should update both TextViews(Full Name and Motorcycle) with the data retrieved from the database at the same time and as soon as i would click the update button below the form. But it only updates after a new login. (The table name of the Database is users and the first child is the Username). enter image description here
fullName.setText(_NAME);
userName.setText(_USERNAME);
location.setText(_LOCATION);
motorcycle.setText(_MOTORCYCLE);
Objects.requireNonNull(fullNameInput.getEditText()).setText(_NAME);
Objects.requireNonNull(emailInput.getEditText()).setText(_EMAIL);
Objects.requireNonNull(motorcycleInput.getEditText()).setText(_MOTORCYCLE);
Objects.requireNonNull(passwordInput.getEditText()).setText(_PASSWORD);
}
private boolean isNameChanged() {
if (!_NAME.equals(Objects.requireNonNull(fullNameInput.getEditText()).getText().toString())) {
reference.child(_USERNAME).child("name").setValue(fullNameInput.getEditText().getText().toString());
fullName.getText().equals(_NAME);
return true;
} else {
return false;
}
}
private boolean isMotorcycleChanged() {
if (!_MOTORCYCLE.equals(Objects.requireNonNull(motorcycleInput.getEditText()).getText().toString())) {
reference.child(_USERNAME).child("motorcycle").setValue(motorcycleInput.getEditText().getText().toString());
return true;
} else {
return false;
}
}
public void update(View view) {
if (isNameChanged() || isEmailChanged() || isMotorcycleChanged() || isPasswordChanged()) {
Toast.makeText(this, "Data has been Updated Successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Data is the Same and therefore Cannot be Updated", Toast.LENGTH_LONG).show();
}
}
}
I'm new to using Firebase and Android Studio and I need multiple nodes to save to a realtime database in Firebase from my android app, these include users, budgets and spending as it's an expense tracking app. I've got the user information to save under its own node but I can't figure out how to create nodes for budget and spending. The code below is what I'm having difficulty with :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
setupUIViews();
firebaseAuth = getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
btn_subCat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate()){
sendUserBudgets();
Toast.makeText(Categories.this, "Completed!", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(Categories.this, Menu.class ));
}else{
Toast.makeText(Categories.this, "Submission failed", Toast.LENGTH_LONG).show();
}
}
});
}
private void setupUIViews() {
travel_input = (EditText)findViewById(R.id.travel_input);
entertainment_input = (EditText)findViewById(R.id.entertainment_input);
fitness_input = (EditText)findViewById(R.id.fitness_input);
beauty_input = (EditText)findViewById(R.id.beauty_input);
clothes_input = (EditText)findViewById(R.id.clothes_input);
holiday_input = (EditText)findViewById(R.id.holiday_input);
food_input = (EditText)findViewById(R.id.food_input);
mobile_input = (EditText)findViewById(R.id.mobile_input);
btn_subCat = (Button)findViewById(R.id.btn_subCat);
}
private Boolean validate() {
boolean result = false;
travel_budget = Double.parseDouble(travel_input.getText().toString().trim());
entertainment_budget = Double.parseDouble(entertainment_input.getText().toString().trim());
fitness_budget = Double.parseDouble(fitness_input.getText().toString().trim());
beauty_budget = Double.parseDouble(beauty_input.getText().toString().trim());
clothes_budget = Double.parseDouble(clothes_input.getText().toString().trim());
holiday_budget = Double.parseDouble(holiday_input.getText().toString().trim());
food_budget = Double.parseDouble(food_input.getText().toString().trim());
mobile_budget = Double.parseDouble(mobile_input.getText().toString().trim());
if(travel_budget.equals(null) || entertainment_budget.equals(null) || fitness_budget.equals(null) || beauty_budget.equals(null) || clothes_budget.equals(null) || holiday_budget.equals(null) || food_budget.equals(null) ||
mobile_budget.equals(null)){
Toast.makeText(Categories.this, "Please enter all fields", Toast.LENGTH_LONG).show();
} else {
result = true;
}
return result;
}
private void sendUserBudgets() {
String currentUserID = firebaseAuth.getUid();
CategoriesDB catDb = new CategoriesDB(travel_budget, entertainment_budget, fitness_budget, beauty_budget, clothes_budget, holiday_budget, food_budget, mobile_budget);
mDatabase.child("User").child(currentUserID).child("Budgets").setValue(catDb);
}
private void validate() {
boolean result = false;
travel_budget = Double.parseDouble(travel_input.getText().toString().trim());
entertainment_budget = Double.parseDouble(entertainment_input.getText().toString().trim());
fitness_budget = Double.parseDouble(fitness_input.getText().toString().trim());
beauty_budget = Double.parseDouble(beauty_input.getText().toString().trim());
clothes_budget = Double.parseDouble(clothes_input.getText().toString().trim());
holiday_budget = Double.parseDouble(holiday_input.getText().toString().trim());
food_budget = Double.parseDouble(food_input.getText().toString().trim());
mobile_budget = Double.parseDouble(mobile_input.getText().toString().trim());
if(travel_budget.equals(null) || entertainment_budget.equals(null) || fitness_budget.equals(null) || beauty_budget.equals(null) || clothes_budget.equals(null) || holiday_budget.equals(null) || food_budget.equals(null) ||
mobile_budget.equals(null)){
Toast.makeText(Categories.this, "Please enter all fields", Toast.LENGTH_LONG).show();
} else {
sendUserBudgets(travel_budget, fitness_budget, beauty_budget, clothes_budget, holiday_budget, food_budget, mobile_budget);
}
}
private void sendUserBudgets(double travel_budget, double fitness_budget, double beauty_budget, double clothes_budget, double holiday_budget, doublefood_budget, double mobile_budget) {
String currentUserID = firebaseAuth.getUid();
CategoriesDB catDb = new CategoriesDB(travel_budget, entertainment_budget, fitness_budget, beauty_budget, clothes_budget, holiday_budget, food_budget, mobile_budget);
mDatabase.child("User").child(currentUserID).child("Budgets").setValue(catDb);
}
Here once you have obtained all the user inputs and have done all the validations, you need to call the function sendUserBudgets() to save it to the database.
I want to hide a WebView object (txtCode) if the code property of a custom object Arraylist (arrQues) contains nothing.
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
Its an ArrayList of custom objects fetched from a database table which is shown below
And if the code property does contains code then I have dynamically added rules to layout as shown below:
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
}
The issue is when I load the second question and so on... the layout gets messed up and the current question number does not shows as 2 even if its 2 as shown in below:
Both of these issues only arises whenever I use...
arrQues.get(count).code.isEmpty() in the code
I have also tried using "" instead of isEmpty() and even null, but the result was same.
Also what I have noticed is only those questions are loaded from database which have something in the code column.
Below is the complete code for Java file
public class QuestionsFragment extends Fragment implements View.OnClickListener {
TextView txtTimer, txtStatus;
LinearLayout boxA, boxB, boxC, boxD, mainContainer;
RelativeLayout submitContainer;
RelativeLayout.LayoutParams submit_params;
RelativeLayout.LayoutParams main_params;
ScrollView scrollView;
Button btnSubmit;
DBHelper dbHelper;
SharedPreferences sharedPreferences;
TextView txtQues;
WebView txtCode;
TextView txtOptA, txtOptB, txtOptC, txtOptD;
String ans;
ArrayList<QuestionModal> arrQues = new ArrayList<>();
ArrayList<String> arrAnswers = new ArrayList<>();
CountDownTimer countDownTimer;
boolean timerSwitch;
int selectedVal, id;
int curr_quesNo = 0;
int count = 0;
int right = 0;
int non_attempted = 0;
public QuestionsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_questions, container, false);
txtQues = view.findViewById(R.id.txtQues);
txtOptA = view.findViewById(R.id.txtOptionA);
txtOptB = view.findViewById(R.id.txtOptionB);
txtOptC = view.findViewById(R.id.txtOptionC);
txtOptD = view.findViewById(R.id.txtOptionD);
txtCode = view.findViewById(R.id.txtCode);
txtStatus = view.findViewById(R.id.txtStatus);
boxA = view.findViewById(R.id.boxA);
boxB = view.findViewById(R.id.boxB);
boxC = view.findViewById(R.id.boxC);
boxD = view.findViewById(R.id.boxD);
scrollView = view.findViewById(R.id.scrollView);
btnSubmit = view.findViewById(R.id.btnSubmit);
submitContainer = view.findViewById(R.id.submitContainer);
mainContainer = view.findViewById(R.id.mainContainer);
submit_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
main_params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT);
sharedPreferences = getActivity().getSharedPreferences("PrefFile", MODE_PRIVATE);
timerSwitch = sharedPreferences.getBoolean("timer_switch", true);
selectedVal = sharedPreferences.getInt("selectedVal", 10);
dbHelper = DBHelper.getDB(getActivity(), sharedPreferences.getString("db_name", null));
if (!dbHelper.checkDB()) {
dbHelper.createDB(getActivity());
}
dbHelper.openDB();
String levelKey = sharedPreferences.getString("level_key", null);
arrQues = dbHelper.getQues(levelKey, selectedVal);
loadQues(timerSwitch);
txtTimer = view.findViewById(R.id.txtTimer);
switch (sharedPreferences.getString("db_name", null)) {
case "Android":
((MainActivity) getActivity()).setFragTitle("Android Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "Java":
((MainActivity) getActivity()).setFragTitle("Java Quiz");
// topicLogo.setImageResource(R.drawable.ic_nature_people_black_24dp);
break;
case "C":
((MainActivity) getActivity()).setFragTitle("C Quiz");
((MainActivity) getActivity()).setFragLogo(R.drawable.ic_home_black_24dp);
break;
case "C++":
((MainActivity) getActivity()).setFragTitle("C++ Quiz");
break;
case "Python":
((MainActivity) getActivity()).setFragTitle("Python Quiz");
break;
case "Kotlin":
((MainActivity) getActivity()).setFragTitle("Kotlin Quiz");
break;
}
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (timerSwitch)
countDownTimer.cancel();
if (id == 0) {
non_attempted++;
arrAnswers.add("NotAttempted");
Toast.makeText(getActivity(), "Not Attempted!", Toast.LENGTH_SHORT).show();
}
switch (id) {
case R.id.boxA:
arrAnswers.add("A");
break;
case R.id.boxB:
arrAnswers.add("B");
break;
case R.id.boxC:
arrAnswers.add("C");
break;
case R.id.boxD:
arrAnswers.add("D");
break;
}
if ((id == R.id.boxA && ans.equals("A"))
|| (id == R.id.boxB && ans.equals("B"))
|| (id == R.id.boxC && ans.equals("C"))
|| (id == R.id.boxD && ans.equals("D"))) {
right++;
count++;
Toast.makeText(getActivity(), "RIGHT!", Toast.LENGTH_SHORT).show();
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
} else {
count++;
if (count < arrQues.size()) {
loadQues(timerSwitch);
} else {
sendResult();
}
}
}
});
return view;
}
public void setBtnDefault() {
boxA.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxB.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxC.setBackgroundColor(getResources().getColor(android.R.color.transparent));
boxD.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
public void sendResult() {
int attempted = selectedVal - non_attempted;
Gson gson = new Gson();
String jsonAnswers = gson.toJson(arrAnswers);
String jsonQues = gson.toJson(arrQues);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("right_key", right);
editor.putInt("wrong_key", attempted - right);
editor.putInt("total_key", selectedVal);
editor.putInt("attempted_key", attempted);
editor.putString("arr_answers", jsonAnswers);
editor.putString("arr_ques", jsonQues);
editor.commit();
((MainActivity) getActivity()).AddFrag(new ResultFragment(), 1);
}
public void LoadTimer() {
countDownTimer = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("0:" + millisUntilFinished / 1000);
}
#SuppressLint("SetTextI18n")
#Override
public void onFinish() {
txtTimer.setText("Time Over");
}
};
}
#SuppressLint("NewApi")
public void loadQues(boolean timer_switch) {
try {
id = 0;
setBtnDefault();
if (timer_switch) {
LoadTimer();
countDownTimer.start();
}
curr_quesNo++;
txtStatus.setText(curr_quesNo + "/" + selectedVal);
txtOptC.setVisibility(View.VISIBLE);
txtOptD.setVisibility(View.VISIBLE);
txtCode.setVisibility(View.VISIBLE);
main_params.removeRule(RelativeLayout.ABOVE);
submit_params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.addRule(RelativeLayout.BELOW, mainContainer.getId());
submit_params.topMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 70));
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
txtQues.setText(arrQues.get(count).ques);
txtOptA.setText(arrQues.get(count).optionA);
txtOptB.setText(arrQues.get(count).optionB);
txtOptC.setText(arrQues.get(count).optionC);
txtOptD.setText(arrQues.get(count).optionD);
txtCode.loadDataWithBaseURL(null, arrQues.get(count).code, "text/html", null, null);
if (txtOptC.getText().toString().isEmpty())
txtOptC.setVisibility(View.GONE);
if (txtOptD.getText().toString().isEmpty())
txtOptD.setVisibility(View.GONE);
if (arrQues.get(count).code.isEmpty())
txtCode.setVisibility(View.GONE);
if (!(arrQues.get(count).code.isEmpty())) {
submit_params.removeRule(RelativeLayout.BELOW);
submit_params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
submit_params.bottomMargin = (int) convertPxToDp(getContext(), convertDpToPx(getContext(), 15));
main_params.addRule(RelativeLayout.ABOVE, submitContainer.getId());
mainContainer.setLayoutParams(main_params);
submitContainer.setLayoutParams(submit_params);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
scrollView.arrowScroll(View.FOCUS_DOWN);
}
}, 1000);
}
ans = arrQues.get(count).answer;
boxA.setOnClickListener(this);
boxB.setOnClickListener(this);
boxC.setOnClickListener(this);
boxD.setOnClickListener(this);
} catch (Exception e) {
((MainActivity) getActivity()).AddFrag(new QuestionsFragment(), 1);
}
}
#Override
public void onClick(View v) {
setBtnDefault();
id = v.getId();
v.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
public float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}
}
I solved it, all issues were happening because arrQues.get(count).code was fetching null values from the database(The column "Code" had null values). As soon as I replaced null values with empty strings "" isEmpty() worked perfectly. I guess isEmpty() doesn't work with null values and is only intended for empty strings.
The reason for the crash is a NullPointerException which is thrown because the fragment's UI Components are null for some reason.
Exception is thrown at this line:
private void setGameInfo(Game game) {
// Stop/hide all ongoing progress bars (loading)
mSummaryLoading.setVisibility(View.GONE);
}
Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
This is my (very long) fragment code where the progress bar mSummaryLoading can be found
public class GameInfoFragment extends Fragment implements GamePageActivity.OnDataLoadedListener {
public GameInfoFragment() {
// Required empty public constructors
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game_info, container, false);
String dateFormat = SharedPrefManager.read(SharedPrefManager.KEY_PREF_DATE_FORMAT, getString(R.string.default_date_format));
mDateFormatterGMT = new SimpleDateFormat(dateFormat);
mDateFormatterGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
mTodayTimeMillis = Calendar.getInstance().getTimeInMillis();
mDatabaseHelper = DatabaseHelper.getDatabaseHelper(getActivity());
mAlarmReceiver = new AlarmReceiver();
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// onViewCreated make sure the view is fully created, called after onCreateView
super.onViewCreated(view, savedInstanceState);
// Summary UI
mTextSummary = view.findViewById(R.id.summary);
mReadMore = view.findViewById(R.id.read_more);
mSummaryLoading = view.findViewById(R.id.summary_loading);
// Platforms UI
mPlatformsLayout = view.findViewById(R.id.platforms);
mPlatformsLayoutExtra = view.findViewById(R.id.platforms_2);
// Countdown UI
mHeaderReleasesTitle = view.findViewById(R.id.header_count_down);
mHeaderReleaseDate = view.findViewById(R.id.header_release_date);
mCountdownLayout = view.findViewById(R.id.countdown_view);
mOutNowTxt = view.findViewById(R.id.out_now_txt);
mDaysTxt = view.findViewById(R.id.days_txt);
mHoursText = view.findViewById(R.id.hours_txt);
mMinutesText = view.findViewById(R.id.minutes_txt);
mSecondsText = view.findViewById(R.id.seconds_txt);
mCategoryText = view.findViewById(R.id.category_txt);
mNoteTxt = view.findViewById(R.id.note_txt);
// Release dates table UI
mSpinnerRegions = view.findViewById(R.id.spinner_regions);
mNoReleaseDatesTxt = view.findViewById(R.id.empty_releases);
mReleaseTableLoading = view.findViewById(R.id.releases_loading);
mTableReleaseDates = view.findViewById(R.id.table_release_dates);
// Websites (Social link) UI
mWebsitesList = view.findViewById(R.id.websitesList);
mNoWebsitesTxt = view.findViewById(R.id.empty_websites_list);
mSocialLoading = view.findViewById(R.id.social_loading);
mWebsitesAdapter = new WebsitesAdapter(getContext());
mWebsitesList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
mWebsitesList.setAdapter(mWebsitesAdapter);
// Start progressbar
mSummaryLoading.setVisibility(View.VISIBLE);
mSocialLoading.setVisibility(View.VISIBLE);
mReleaseTableLoading.setVisibility(View.VISIBLE);
// User region
String region = SharedPrefManager.read(SharedPrefManager.KEY_PREF_REGION, "north_america");
mRegion = SharedPrefManager.getRegionToFilter(region);
// Release social actions
// The RELEASE DATA OBJECT
mRelease = ((GamePageActivity)getActivity()).getRelease();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
// When the user signs in in this page [refresh]
initHypes(mRelease.getId());
}
}
};
mReleasesActions = view.findViewById(R.id.release_actions);
// Favorite
mAddToFavorite = view.findViewById(R.id.favorite);
mAddNote = view.findViewById(R.id.add_note);
mEditAlarms = view.findViewById(R.id.alarms);
mShareRelease = view.findViewById(R.id.share);
mDatabaseHelper = DatabaseHelper.getDatabaseHelper(getActivity());
// HYPE!!!
mHypeLoading = view.findViewById(R.id.hype_loading);
mHypeRelease = view.findViewById(R.id.hype);
mHypeCountTxt = view.findViewById(R.id.hype_count);
mHypeCountTxt.setText("0 hypes");
// Release actions icons
mStarIcon = view.findViewById(R.id.star_icon);
mHeartIcon = view.findViewById(R.id.favorite_icon);
mNoteIcon = view.findViewById(R.id.note_icon);
mAlarmIcon = view.findViewById(R.id.alarm_icon);
// Default colors [hype]
mStarIcon.setImageResource(R.drawable.ic_star);
mHeartIcon.setImageResource(R.drawable.ic_favorite);
mNoteIcon.setImageResource(R.drawable.ic_note);
mAlarmIcon.setImageResource(R.drawable.ic_notification);
// Init likes (hypes) and puts color to yellow if liked
// if game has't been released yet or has been released for a week
if (mRelease.getDate() >= mTodayTimeMillis - 604800000) {
initHypes(mRelease.getId());
mHypeRelease.setVisibility(View.VISIBLE);
} else {
mHypeRelease.setVisibility(View.GONE);
}
// Social actions, favorite, alarm, note, etc.
initReleaseActions();
// Countdown
initCountdown(mRelease);
// Platforms
initPlatforms(mRelease);
// The release date
mHeaderReleaseDate.setText(mDateFormatterGMT.format(mRelease.getDate()));
// Expandable TextView
mReadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if (mTextSummary.isExpanded()) {
mTextSummary.collapse();
mReadMore.setText("Read more");
} else {
mTextSummary.expand();
mReadMore.setText("Collapse");
}
}
});
// Like [hype up] game
mHypeRelease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAuth.getCurrentUser() != null) {
onStarClicked(mRelease, mAuth.getCurrentUser().getUid());
} else {
startActivity(new Intent(getActivity(), SignInActivity.class));
}
}
});
}
public void loadHypeLayout() {
if (mHypeLoading.getVisibility() == View.VISIBLE) {
mHypeLoading.setVisibility(View.GONE);
mHypeCountTxt.setVisibility(View.VISIBLE);
mStarIcon.setVisibility(View.VISIBLE);
} else {
mHypeLoading.setVisibility(View.VISIBLE);
mHypeCountTxt.setVisibility(View.GONE);
mStarIcon.setVisibility(View.GONE);
}
}
public void initReleaseActions() {
// User saved release actions
if (mDatabaseHelper.favoriteExists(mRelease)) {
mHeartIcon.setImageResource(R.drawable.ic_favorite_red);
mAddNote.setVisibility(View.VISIBLE);
// If game already out, can't have alarms
if (mRelease.getDate() >= Calendar.getInstance().getTimeInMillis()) {
mEditAlarms.setVisibility(View.VISIBLE);
} else {
mEditAlarms.setVisibility(View.GONE);
}
} else {
mAddNote.setVisibility(View.GONE);
mEditAlarms.setVisibility(View.GONE);
}
if (mDatabaseHelper.alarmExists(mRelease)) {
mAlarmIcon.setImageResource(R.drawable.ic_notification_blue);
}
if (mDatabaseHelper.noteExists(mRelease)) {
mNoteIcon.setImageResource(R.drawable.ic_note_red);
mNoteTxt.setText("Edit note");
}
mAddToFavorite.setOnClickListener(new FavoriteOnClickListener(getContext(), mRelease, mAlarmIcon, mHeartIcon, mNoteIcon,
mAddNote, mEditAlarms));
mAddNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddNoteFragment addNoteFragment = new AddNoteFragment();
addNoteFragment.setDatabaseHelper(mDatabaseHelper);
addNoteFragment.setRelease(mRelease);
addNoteFragment.setIcon(mNoteIcon);
addNoteFragment.setNoteTxt(mNoteTxt);
addNoteFragment.show(getFragmentManager(), addNoteFragment.getTag());
}
});
mEditAlarms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditAlarmsFragment editAlarmsFragment = new EditAlarmsFragment();
editAlarmsFragment.setDatabaseHelper(mDatabaseHelper);
editAlarmsFragment.setRelease(mRelease);
editAlarmsFragment.setIcon(mAlarmIcon);
editAlarmsFragment.show(getFragmentManager(), editAlarmsFragment.getTag());
}
});
mShareRelease.setOnClickListener(new ShareOnClickListener(getContext(), mRelease, mAPISearchedGame));
}
public void initPlatforms(Release release) {
List<Integer> platforms = release.getPlatforms();
if (platforms != null) {
for (int i = 0; i < platforms.size(); i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 18, 0);
TextView current = new TextView(getActivity());
current.setId(i + 1);
current.setLayoutParams(params);
current.setPadding(8, 8, 8, 8);
current.setTextSize(14);
current.setGravity(Gravity.CENTER);
current.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_text));
switch (platforms.get(i)) {
case 6:
current.setText("Win");
current.setBackgroundResource(R.drawable.round_pc);
break;
case 49:
current.setText("Xbox One");
current.setBackgroundResource(R.drawable.round_xboxone);
break;
case 48:
current.setText("PS4");
current.setBackgroundResource(R.drawable.round_ps4);
break;
case 9:
current.setText("PS3");
current.setBackgroundResource(R.drawable.round_ps3);
break;
case 46:
current.setText("PS Vita");
current.setBackgroundResource(R.drawable.round_psvita);
break;
case 12:
current.setText("Xbox 360");
current.setBackgroundResource(R.drawable.round_xbox360);
break;
case 130:
current.setText("Nintendo Switch");
current.setBackgroundResource(R.drawable.round_switch);
break;
case 41:
current.setText("Wii U");
current.setBackgroundResource(R.drawable.round_wiiu);
break;
case 37:
current.setText("3DS");
current.setBackgroundResource(R.drawable.round_3ds);
break;
case 3:
current.setText("Linux");
current.setBackgroundResource(R.drawable.round_linux);
break;
case 14:
current.setText("Mac");
current.setBackgroundResource(R.drawable.round_mac);
break;
case 34:
current.setText("Android");
current.setBackgroundResource(R.drawable.round_android);
break;
case 39:
current.setText("IOS");
current.setBackgroundResource(R.drawable.round_ios);
break;
case 5:
current.setText("Wii");
current.setBackgroundResource(R.drawable.round_wii);
break;
}
// if (i == 7; change to platform_2)
if (i < 7) {
mPlatformsLayout.addView(current);
} else {
mPlatformsLayoutExtra.setVisibility(View.VISIBLE);
mPlatformsLayoutExtra.addView(current);
}
}
}
}
public void initCountdown(Release release) {
// https://stackoverflow.com/questions/46332398/android-countdown-based-on-gmt-utc-and-not-the-users-timezone
// Set the release date in millis to calender set to GMT timezone (universal)
Calendar releaseCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
releaseCalendar.setTimeInMillis(release.getDate());
// Get the release date
LocalDate localReleaseDate = null;
boolean success = false;
int dayOfMonth = releaseCalendar.get(Calendar.DAY_OF_MONTH);
while (!success) {
try {
localReleaseDate = LocalDate.of(releaseCalendar.get(Calendar.YEAR),
releaseCalendar.get(Calendar.MONTH) + 1,
dayOfMonth);
success = true;
} catch (DateTimeException dateTimeException) {
// Invalid date e.g 'November 31' Small fix?
dayOfMonth -= 1;
}
}
LocalTime localReleaseTime = LocalTime.of(0, 0, 0); // midnight release
// Set to the user's timezone
ZoneId zoneId = ZoneId.of(TimeZone.getDefault().getID());
ZonedDateTime zonedDateTime = ZonedDateTime.of(localReleaseDate, localReleaseTime, zoneId);
// Convert from a time zone to UTC. Same point on the timeline
Instant instant = zonedDateTime.toInstant();
Duration d = Duration.between(Instant.now(), instant);
mCountdownTimer = new CountDownTimer(d.toMillis() , 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished) {
// 1 sec = 1000 millis
long seconds = millisUntilFinished / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
mDaysTxt.setText(String.valueOf(days));
mHoursText.setText(String.valueOf(hours % 24));
mMinutesText.setText(String.valueOf(minutes % 60));
mSecondsText.setText(String.valueOf(seconds % 60));
}
public void onFinish() {
mHeaderReleasesTitle.setText("Released on");
mOutNowTxt.setVisibility(View.VISIBLE);
mCountdownLayout.setVisibility(View.GONE);
// Games already out, can't have alarms, but they can still be hyped for a week after release
mEditAlarms.setVisibility(View.GONE);
}
};
mCountdownTimer.start();
long updatedAt = release.getUpdatedAt();
if (updatedAt != 0) {
mTxtLastUpdatedOnRelease.setText("Release date last updated on " + mDateFormatterGMT.format(updatedAt));
}
}
private void setGameInfo(Game game) {
// Stop/hide all ongoing progress bars (loading)
mSummaryLoading.setVisibility(View.GONE);
mSocialLoading.setVisibility(View.GONE);
mReleaseTableLoading.setVisibility(View.GONE);
loadHypeLayout();
// The category
String category = game.getCategory();
if (category != null) {
mCategoryText.setText(game.getCategory());
}
String summary = game.getSummary();
if (summary != null) {
mTextSummary.setText(summary);
} else {
mTextSummary.setText("No summary available");
mReadMore.setVisibility(View.GONE);
}
List<Website> websites = game.getWebsites();
if (websites != null) {
mWebsitesAdapter.setData(websites);
} else {
mWebsitesList.setVisibility(View.GONE);
mNoWebsitesTxt.setVisibility(View.VISIBLE);
}
// Organizing Table Release dates
List<ReleaseDate> releaseDates = game.getReleaseDates();
if (releaseDates != null) {
// Creating the Hash map / Every region that exists will have a list of release dates
mRegionsReleaseHashMap = new HashMap<>();
for (ReleaseDate releaseDate : releaseDates) {
String region = releaseDate.getRegionName();
// Doesn't contain region
if (!mRegionsReleaseHashMap.containsKey(region)) {
mRegionsReleaseHashMap.put(region, new ArrayList<ReleaseDate>());
}
mRegionsReleaseHashMap.get(region).add(releaseDate);
}
// Setting first the spinner, then the data
if (!mRegionsReleaseHashMap.isEmpty()) {
List<String> regions = new ArrayList<>();
for (String region : mRegionsReleaseHashMap.keySet()) {
if (!regions.contains(region)) { regions.add(region); }
}
Collections.sort(regions); // By alpha order
// Spinner takes an ArrayAdapter as adapter
ArrayAdapter spinnerAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, regions);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerRegions.setAdapter(spinnerAdapter);
/*
I removed this
// First spinner item is always the user's region
String defaultRegion = ((GamePageActivity) getActivity()).mRegion;
if (regions.contains(defaultRegion)) {
mSpinnerRegions.setSelection(spinnerAdapter.getPosition(defaultRegion));
} else if (regions.contains("Worldwide")) {
mSpinnerRegions.setSelection(spinnerAdapter.getPosition("Worldwide"));
} */
// Spinner listener [called on selected and on shown]
mSpinnerRegions.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
initReleaseDatesTable(mRegionsReleaseHashMap.get(mSpinnerRegions.getSelectedItem().toString()));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} else {
mNoReleaseDatesTxt.setVisibility(View.VISIBLE);
mTableReleaseDates.setVisibility(View.GONE);
}
long updatedAt = game.getUpdatedAt();
if (updatedAt != 0) {
mTxtLastUpdatedOnGame.setText("Game data last updated on " + mDateFormatterGMT.format(updatedAt));
}
}
public void initReleaseDatesTable(List<ReleaseDate> releaseDates) {
mTableReleaseDates.removeAllViews();
TableRow tblRowHeader = new TableRow(getContext());
TextView txtPlatform = new TextView(getContext());
txtPlatform.setTextSize(16);
txtPlatform.setText("Platform");
tblRowHeader.addView(txtPlatform);
TextView txtReleaseDate = new TextView(getContext());
txtReleaseDate.setTextSize(16);
txtReleaseDate.setText("Release Date");
tblRowHeader.addView(txtReleaseDate);
TextView txtCountdown = new TextView(getContext());
txtCountdown.setTextSize(16);
txtCountdown.setText("Days left");
tblRowHeader.addView(txtCountdown);
mTableReleaseDates.addView(tblRowHeader);
// Creating rows
// One row: platform, release date and pre-order
for (int i = 0; i < releaseDates.size(); i++) {
TableRow tblRowData = new TableRow(getContext());
TextView textPlatformData = new TextView(getContext());
String platform = releaseDates.get(i).getPlatformName();
// Gaming Reminder doesn't support/recognize this platform ;)
if (!platform.isEmpty()) {
textPlatformData.setTextSize(16);
textPlatformData.setText(platform);
tblRowData.addView(textPlatformData);
TextView textReleaseDateData = new TextView(getContext());
textReleaseDateData.setTextSize(16);
long releaseTimeMillis = releaseDates.get(i).getDate();
textReleaseDateData.setText(mDateFormatterGMT.format(releaseTimeMillis));
tblRowData.addView(textReleaseDateData);
TextView textCountdownData = new TextView(getContext());
textCountdownData.setTextSize(16);
long daysLeft = AppUtil.daysBetween(releaseTimeMillis);
if (daysLeft <= 0) {
textCountdownData.setText("Now Out");
} else {
textCountdownData.setText(daysLeft + " days");
}
tblRowData.addView(textCountdownData);
mTableReleaseDates.addView(tblRowData);
}
}
}
// Shows the number of likes in our respective likes count view
private void initHypes(final long releaseId) {
// Toast.makeText(getContext(), "Loading likes...", Toast.LENGTH_SHORT).show();
DatabaseReference likeRef = mLikesRef.child(mRegion);
likeRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(String.valueOf(releaseId)).exists()) {
long starCount = dataSnapshot.child(String.valueOf(releaseId)).child("starCount").getValue(Long.class);
mHypeCountTxt.setText(starCount + " hypes");
// Now check if current logged in user hyped it (the release) up
if (mAuth.getCurrentUser() != null) {
// the stars node is only used to check if the current user hyped up the current game
if (dataSnapshot.child(String.valueOf(releaseId)).child("stars").hasChild(mAuth.getCurrentUser().getUid())) {
mStarIcon.setImageResource(R.drawable.ic_star_yellow);
} else {
mStarIcon.setImageResource(R.drawable.ic_star);
}
}
} // else : no votes yet for this release
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
}
private void onStarClicked(final Release release, final String uid) {
final DatabaseReference postRef = mLikesRef.child(mRegion).child(String.valueOf(release.getId()));
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
// When p is null this means, the release object [no node exists] hasn't been added to likes
p = new Post();
p.setStarCount(1);
p.setRelease(release);
p.setDate(release.getDate());
p.getStars().put(uid, true);
mutableData.setValue(p);
return Transaction.success(mutableData);
}
if (p.getStars().containsKey(uid)) {
// Unstar the post and remove self from stars
p.setStarCount(p.getStarCount() - 1);
if (p.getStarCount() == 0) {
// Delete the node
postRef.removeValue();
}
// remove the entire key
p.getStars().remove(uid);
} else {
// Star the post and add self to stars
p.setStarCount(p.getStarCount() + 1);
// Update the date [flawed, some release dates saved in likes can have a different release date]
// Update the release each time the user puts a star
p.setRelease(release);
p.getStars().put(uid, true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onDataLoaded(Game game) {
mCategoryText.setText("but");
setGameInfo(game);
}
}
When you app is put in the background and brought back, it can kill the fragment and recreated it. If you method setGameInfo is being called with nulls its because the method is being called between when the Fragment is recreated and when its onViewCreated (where you set up the view references) is called.
From your code, I have to guess there is something happening in the owning Activity that invokes the fragment's onDataLoaded method while the fragment is still be initialized.
Use your debugger to put a breakpoint at this method and in onViewCreated to see which is being called first and why.
I think the problem, or most part of it at least is where you are initializing the views.
As a rule of thumb, anything that needs to be created for the Fragment which is not a View should be declared in onCreate(), and anything with a findViewById() should go in onCreateView(), not onViewCreated().
For example, I would move this part to onCreate():
String dateFormat = SharedPrefManager.read(SharedPrefManager.KEY_PREF_DATE_FORMAT, getString(R.string.default_date_format));
mDateFormatterGMT = new SimpleDateFormat(dateFormat);
mDateFormatterGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
mTodayTimeMillis = Calendar.getInstance().getTimeInMillis();
mDatabaseHelper = DatabaseHelper.getDatabaseHelper(getActivity());
mAlarmReceiver = new AlarmReceiver();
Also put here the creation of the adapter and the database helper:
mWebsitesAdapter = new WebsitesAdapter(getContext());
Other candidates for onCreate() are:
String region = SharedPrefManager.read(SharedPrefManager.KEY_PREF_REGION, "north_america");
mRegion = SharedPrefManager.getRegionToFilter(region);
// Release social actions
// The RELEASE DATA OBJECT
mRelease = ((GamePageActivity)getActivity()).getRelease();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
// When the user signs in in this page [refresh]
initHypes(mRelease.getId());
}
}
};
And most if not all you have in onViewCreated() to onCreateView()
I didn't run your code and it is quite long, so there may be exceptions to this in what you have done, but onViewCreated() should remian practically empty after the refactoring.
Note: I think the databasehelper is set twice, after moving it ot onCreate() you shouldn't need to repeat the initialization somewhere else.