Implement ad banner Admob in Fragment android - java

I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment).
the issues is that, Where should I write the java code for this admob banner.
if anyone can explain to me how correctly add banner in fragment android studio
into this code:
Here is the java code as well as
public WalletFragment() { // Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
FragmentWalletBinding binding;
FirebaseFirestore database;
User user;
private AdView mAdView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
;
binding = FragmentWalletBinding.inflate(inflater, container, false);
database = FirebaseFirestore.getInstance();
database.collection("users")
.document(FirebaseAuth.getInstance().getUid())
.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
user = documentSnapshot.toObject(User.class);
binding.currentCoins.setText(String.valueOf(user.getCoins()));
//binding.currentCoins.setText(user.getCoins() + "");
}
});
binding.sendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user.getCoins() > 200000) {
String uid = FirebaseAuth.getInstance().getUid();
String payPal = binding.emailBox.getText().toString();
WithdrawRequest request = new WithdrawRequest(uid, payPal, user.getName());
database
.collection("withdraws")
.document(uid)
.set(request).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getContext(), "Request sent successfully.", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getContext(), "You need more coins to get withdraw.", Toast.LENGTH_SHORT).show();
}
}
});
return binding.getRoot();
}
}```

Related

Navigates to second fragment again by pressing back button previous data exists

I have two fragments and one activity (Main Activity). Now when I go from fragment 1 to fragment 2 data in fragment 2 loads from api. But when I press back button, navigates to fragment 1 and again I go from fragment 1 to fragment 2 then the previous loaded data is there for some secs and then fragment loads new data. Why it is so? I want that whenever I go to the fragment 2 it should reload again all the data (without showing the previous data for some secs first). Which method I should use?
Here is my onclick method from fragment 1 for navigating to fragment 2.
private void bind(FragmentUserInputFormBinding binding) {
binding.btnFetchOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isAllFieldChecked = validateAllFields(binding);
if (isAllFieldChecked) {
Bundle bundle = new Bundle();
bundle.putString("appid", binding.etAppId.getText().toString());
bundle.putString("uid", binding.etUserId.getText().toString());
bundle.putString("token", binding.etToken.getText().toString());
OfferWallListFragment offerWallListFragment = new OfferWallListFragment();
offerWallListFragment.setArguments(bundle);
requireActivity().getSupportFragmentManager().beginTransaction()
.replace(((ViewGroup) requireView().getParent()).getId(), offerWallListFragment,"offerListFragment")
.setReorderingAllowed(true)
.addToBackStack("offerListFragment")
.commit();
}
}
});
}
Now I have my second fragment designed as follows fragment 2.
#AndroidEntryPoint
public class OfferWallListFragment extends BaseFragment<FragmentOfferWallListBinding> {
private RecyclerViewAdapter recyclerViewAdapter;
private int currentPage = FIRST_PAGE;
public OfferWallListFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Objects.requireNonNull(((AppCompatActivity) requireActivity()).getSupportActionBar()).setTitle("Offers List");
initViewModel(FragmentOfferWallListBinding.bind(view));
}
#NonNull
#Override
protected FragmentOfferWallListBinding initBinding(#NonNull LayoutInflater inflater, #Nullable ViewGroup container) {
return FragmentOfferWallListBinding.inflate(inflater, container, false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_offer_wall_list, container, false);
}
private void initViewModel(FragmentOfferWallListBinding binding) {
OfferWallViewModel offerWallViewModel = new ViewModelProvider(this).get(OfferWallViewModel.class);
offerWallViewModel.getLiveData(currentPage).observe(getViewLifecycleOwner(), new Observer<OfferResponse>() {
#Override
public void onChanged(OfferResponse offerResponse) {
if (offerResponse != null) {
recyclerViewAdapter = new RecyclerViewAdapter();
recyclerViewAdapter.setOfferResponse(offerResponse);
binding.rvOfferData.setHasFixedSize(true);
binding.rvOfferData.setLayoutManager(new LinearLayoutManager(getContext()));
binding.rvOfferData.setAdapter(recyclerViewAdapter);
binding.rvOfferData.setVisibility(View.VISIBLE);
}
RecyclerViewPaginator recyclerViewPaginator = new RecyclerViewPaginator(binding.rvOfferData) {
#Override
public boolean isLastPage() {
return currentPage == offerResponse.getPages();
}
#Override
public void loadMore(int _currentPage) {
currentPage = _currentPage;
offerWallViewModel.getLiveData(Math.toIntExact(_currentPage));
}
};
binding.rvOfferData.addOnScrollListener(recyclerViewPaginator);
}
});
offerWallViewModel.getNetworkStateMutableLiveData().observe(getViewLifecycleOwner(), new Observer<NetworkState>() {
#Override
public void onChanged(NetworkState networkState) {
if (networkState == NetworkState.Companion.getLOADING()) {
binding.pbLoadingItems.setVisibility(View.VISIBLE);
} else if (networkState == NetworkState.Companion.getERROR()) {
Toast.makeText(getContext(), "Something went wrong, please check the parameters are filled perfectly", Toast.LENGTH_SHORT).show();
if (!CheckInternetConnection.isInternetAvailable(getContext())) {
Toast.makeText(getContext(), "No Internet Connection Available", Toast.LENGTH_SHORT).show();
binding.txtNoConnection.setText("No Internet Connection Available");
binding.txtNoConnection.setVisibility(View.VISIBLE);
}
binding.pbLoadingItems.setVisibility(View.GONE);
} else {
binding.pbLoadingItems.setVisibility(View.GONE);
}
}
});
}
}
Also I have handled onBackPressed method from MainActivity as follows.
#AndroidEntryPoint
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentContainerView);
if (navHostFragment != null) {
NavController navController = navHostFragment.getNavController();
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.userInputFormFragment, R.id.offerWallListFragment
).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
}
}
#Override
public void onBackPressed(){
int count = getSupportFragmentManager().getBackStackEntryCount();
if(count == 0) {
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
}
}
Please have a look on it ?

User profile fragment Setting

i am creating small app with login and signup option and also with profile fragment so that user can update their profile later. i design my user profile layout but don't know how to code with java so when user open profile fragment he changed his detail . i am using firebasefirestore
please help me
public class ProfileFragment extends Fragment {
FirebaseAuth auth;
FirebaseFirestore database;
UserDetail userDetail;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
FragmentProfileBinding binding;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = FragmentProfileBinding.inflate( inflater, container,false );
database = FirebaseFirestore.getInstance();
database.collection( "Users" )
.document( FirebaseAuth.getInstance().getUid() )
.get().addOnSuccessListener( new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
userDetail = documentSnapshot.toObject( UserDetail.class );
}
} );
binding.updateButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
String name, cityName, mobileNumber, whatsappNumber, email, password;
name = binding.nameBox.getText().toString();
cityName = binding.cityNameBox.getText().toString();
mobileNumber = binding.mobileNumberBox.getText().toString();
whatsappNumber = binding.whatsappNumberBox.getText().toString();
email = binding.emailBox.getText().toString();
password = binding.passwordBox.getText().toString();
final UserDetail userDetail = new UserDetail(name, email, password, cityName, mobileNumber, whatsappNumber);
}
} );
return binding.getRoot();
}
}
Override this method in your fragment :
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
this.isHidden = hidden;
if (isHidden) {
//todo do something
} else {
//todo do something
}
}

RecyclerView disappearing after switching between fragments on a particular Activity

The problem I have been facing with the development is that there is a recyclerview inside my fragment which gets disappeared after I switch between two fragments on a particular activity. On the first time when the fragment loads everything works fine but afterwards I don't understand what goes wrong. I had tried to refer to various ways that people had posted over github like notifyDatasetChanged, etc. But nothing seems to work. I would appreciate if someone could help me out with this issue.
So here are my classes.
The ProfileFragment.java :
public class ProfileFragment extends Fragment {
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
RecyclerView itemRecycler;
List<ModelProfile> modelProfiles;
AdapterProfile adapterProfile;
String storagePath= "Users_Profile_Cover_Image/-";
ImageView avatarIv,dp;
CardView card,cardArrow;
TextView nameTv, emailTv, phoneTv;
Button logout,update;
ExtendedFloatingActionButton fab;
ProgressDialog pd;
//..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view= inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user= firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference= getInstance().getReference();
loadItems();
return view;
}
private void loadItems() {
//Problem could be here
GridLayoutManager layoutManager= new GridLayoutManager(getContext(),3);
itemRecycler.setHasFixedSize(true);
itemRecycler.setLayoutManager(layoutManager);
itemRecycler.setVisibility(View.VISIBLE);
CollectionReference ref =FirebaseFirestore.getInstance().collection("All_Posts");
com.google.firebase.firestore.Query query = ref.whereEqualTo("uid",uid);
FirestoreRecyclerOptions<ModelProfile> options = new FirestoreRecyclerOptions.Builder<ModelProfile>()
.setQuery(query,ModelProfile.class).build();
adapterProfile = new AdapterProfile(options,getActivity());
itemRecycler.setAdapter(adapterProfile);
adapterProfile.startListening();
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
assert value != null;
Log.i("Size",String.valueOf(value.getDocuments().size()));
if (value.getDocuments().size() > 0) { // List is populated
card.setVisibility(View.GONE);
cardArrow.setVisibility(View.GONE);
} else { // List is empty
card.setVisibility(View.VISIBLE);
cardArrow.setVisibility(View.VISIBLE);
}
}
});
}
//
// #Override
// public void onStart() {
// super.onStart();
// adapterProfile.startListening();
// }
//
//
//
// #Override
// public void onStop() {
// super.onStop();
// adapterProfile.stopListening();
// }
#Override
public void onResume() {
super.onResume();
adapterProfile.startListening();
}
}
Adapter:-
public class AdapterProfile extends FirestoreRecyclerAdapter<ModelProfile,AdapterProfile.MyHolder> {
Context context;
public String im;
public AdapterProfile(#NonNull FirestoreRecyclerOptions<ModelProfile> options, Activity Context) {
super(options);
context = Context;
}
#Override
protected void onBindViewHolder(#NonNull MyHolder holder, int position, #NonNull ModelProfile model) {
String uid = model.getUid();
String uEmail =model.getuEmail();
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//..
}
class MyHolder extends RecyclerView.ViewHolder{
//..
}
Activity on which Fragment switching takes place
public class LandingActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference userDbRef;
FirebaseUser user;
String uid,dp;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
//problem could be here as well.........
#Override
public void onItemSelected(int i) {
Fragment fragment=null;
switch(i) {
case R.id.bottom_nav_2:
fragment = new CltFragment();
break;
case R.id.bottom_nav_3:
fragment = new MaceFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
}
private void checkUserStatus()
{
FirebaseUser user= firebaseAuth.getCurrentUser();
if(user !=null)
{
uid=user.getUid();
}
else
{
startActivity(new Intent(LandingActivity.this,MainActivity.class));
finish();
}
}
#Override
public void onResume() {
//Problem could be here
super.onResume();
Intent intent = getIntent();
String frag = "";
if(intent.hasExtra("frag")) {
frag = intent.getExtras().getString("frag");
}
else
{
//..
}
switch(frag)
{
//..
case "ProfileFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
chipNavigationBar.setItemSelected(R.id.bottom_nav_profile,true);
break;
}
}
}
Thanks for having looked at my Problem!
Try using this
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new InventoryFragment()).commit();
Instead of this
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();

Why is my code always receiving a null pointer exception when I have binded the element in to it? I am using Java in Android Studio

I am receiving java.lang.NullPointerException, although I have binded the element correctly.
Tried to check the ID of the element, it matches, but still I receive the same exception.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text to Speech
tts = new TextToSpeech(this, this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
speakButton = view.findViewById(R.id.speakButton);
}
}
It should be running fine, But I am receiving the java.lang.NullPointerException
You button code should be declared in you fragment not in you activity as the button is in your fragment.xml. As you are accessing the button in onCreate method of the activity it will give nullpointer exception because you fragment's view is not yet rendered.The best practice is to access the view in onViewCreated function of your fragment.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Text to Speech
tts = new TextToSpeech(getActivity(), this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
}
void speakOut(){
}
The solution is to implement TextToSpeech.OnInitListener in the project and make the public variables to be private.
public class TranslatorFragment extends Fragment implements TextToSpeech.OnInitListener{
private Button speakButton; // public Button speakButton;
private TextToSpeech tts;
private EditText speechText; // public EditText speechText;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tts = new TextToSpeech(getActivity(), this);
speakButton = view.findViewById(R.id.speakButton);
speechText = view.findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
}
private void speakOut(){
String text = speechText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status){
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getActivity(), "Language not supported!", Toast.LENGTH_SHORT).show();
} else {
speakButton.setEnabled(true);
speakOut();
}
}
else
{
Toast.makeText(getActivity(), "Initilization failed!", Toast.LENGTH_SHORT).show();
}
}
public void onDestroy() {
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}

FragmentActivity, AppCompatActivity, and Fragments

I added this to be more clear and more easily to understand the problem.
1st Scenario: I launch the activity > opens the LoginFragment > I click the TextView to navigate to FragmentActivity. So there is no error here. Now in 2nd Scenario, I logged in a user > navigated to the MainActivity then pressed the Logout Button > navigated to the LogoutConfirmation (Remember, this is a another Activity to open the LogoutConfirmation, the LogoutConfirmation is a Fragment) then I pressed Logout button to logout and > navigated to the LoginFragment again. Lastly, I pressed the TextView to navigate again to the RegisterFragment but this time it gives me error.
This is the error I got:
java.lang.IllegalArgumentException: No view found for id 0x7f07002e (com.example.asus.perfectlogin:id/container) for fragment RegisterFragment{5285de6c #2 id=0x7f07002e}
What I notice here why the system can't find the id:container because the time I logged in then pressed the Logout button > navigate to the LogoutConfirmation (because I call this Fragment to LogoutFragment extends AppCompatActivity then to open this I use Intent and call the LogoutFragment) So now it is another Activity that contains another container, because in my code of LoginFragment to navigate the Fragment I used the id: container but the running activity is the LogoutFragment which is the id: container2. I hope you understand all of my explanation. Thank you!
Here are my codes: Main Activity extends FragmentActity
This is my Launcher.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogout = findViewById(R.id.btnLogout);
mAuth = FirebaseAuth.getInstance();
//mAuth.signOut();
logOut();
setupFirebaseAuth();
}
public void logOut(){
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, LogoutFragment.class);
startActivity(intent);
}
});
}
/*
-------------------------------Firebase--------------------------------
*/
/*
check if the user is logged in
*/
private void checkCurrentUser(FirebaseUser user){
Log.d(TAG, "checkCurrentUser: checking if user is logged in.");
if (user == null){
Intent intent = new Intent(this, MainFragment.class);
startActivity(intent);
}
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
//checking if the user is logged in or not
checkCurrentUser(user);
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
checkCurrentUser(mAuth.getCurrentUser());
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Codes for: MainFragment extends AppCompatActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
LoginFragment loginFragment = new LoginFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, loginFragment, loginFragment.getTag()).commit();
}
Codes for: fragment_main
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container">
</FrameLayout>
Codes for: LoginFragment extends Fragment
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, container, false);
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mForRegister = view.findViewById(R.id.tvForRegister);
mHeading = view.findViewById(R.id.heading);
eEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
btnLogin = view.findViewById(R.id.btnLogin);
// Progress Bar and Text view : GONE
mPleaseWait = view.findViewById(R.id.pleaseWait);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
//Firebase
mAuth = FirebaseAuth.getInstance();
navigatetoRegister();
setupFirebaseAuth();
signInUser();
return view;
}
public void navigatetoRegister(){
mForRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new RegisterFragment());
fr.commit();
}
});
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
---------------------------------Firebase-----------------------------------
*/
private void signInUser(){
// Button = to sign in the user.
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getActivity(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
//To sign in users
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(), "Sign in Successful!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}else {
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Could not sign in. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Codes for: RegisterFragment extends Fragment
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
mEmail = view.findViewById(R.id.tvEmail);
mPassword = view.findViewById(R.id.tvPassword);
mForLogin = view.findViewById(R.id.tvForLogin);
mHeading = view.findViewById(R.id.heading);
eEmail = view.findViewById(R.id.etEmail);
ePassword = view.findViewById(R.id.etPassword);
btnRegister = view.findViewById(R.id.btnRegister);
// Progress Bar and Text view : GONE
mPleaseWait = view.findViewById(R.id.pleaseWait);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
navigateToLogin();
registerNewUser();
setupFirebaseAuth();
return view;
}
public void navigateToLogin(){
mForLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new LoginFragment());
fr.commit();
}
});
}
private boolean isStringNull(String string){
if (string.equals("")){
return true;
}
return false;
}
/*
To check if the user is creating a same email.
*/
public void checkUserId(){
if (mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
/*
---------------------------------Firebase-----------------------------------
*/
public void registerNewUser(){
// To register new user
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = eEmail.getText().toString();
String password = ePassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(getContext(), "You must field out all the fields.", Toast.LENGTH_SHORT).show();
}else {
//Progress Bar and TextView be visible
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
//To create/register new user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
//user is succesfully registered and logged in
checkUserId(); //Checking if the user is create same email
Log.d(TAG, "onComplete: AuthstateChange: " + userID);
Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_SHORT).show();
//AFter Registering account it will navigate to the Login Fragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container, new LoginFragment());
fr.commit();
}else {
mProgressBar.setVisibility(View.GONE);
mPleaseWait.setVisibility(View.GONE);
Toast.makeText(getActivity(), "Please check your internet. Or maybe you registered same email.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
//This is the listener to check the Firebase if there is user logged in or not.
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
Codes for: LogoutFragment extends AppCompatActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logout_fragment);
LogOutConfirmation fragment = new LogOutConfirmation();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container2, fragment, null).commit();
}
Codes for: fragment_logout.xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container2">
</FrameLayout>
Codes for: LogoutConfirmation extends Fragment
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.logout_confirmation, container, false);
mLogout = view.findViewById(R.id.heading);
mPleaseWait = view.findViewById(R.id.tvPleaseWait);
mProgressBar = view.findViewById(R.id.progressBar);
btnLogout = view.findViewById(R.id.btnLogout);
mPleaseWait.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
signOut();
setupFirebaseAuth();
return view;
}
/*
//This is the button to sign out. Then system will read next the `setupFirebaseAuth`. So if mAuthListener
knows there is no user signed it so it will navigate to the LoginFragment
*/
public void signOut(){
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAuth.signOut();
//Progress Bar and TextView
mPleaseWait.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
Log.d(TAG, "onClick: attempting to log out.");
}
});
}
/*
--------------------------------------Firebase-------------------------------------------
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
//checking if the user is logged in or not
if (user != null){
//User is signed in
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: signed_out");
//After logging out, it will navigate to LoginFragment
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container2, new LoginFragment());
fr.commit();
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}

Categories

Resources