Logout from Navigation Drawer - firebase

I would like to create a logout alert dialog from my applications navigation drawer. All the other items in the nav drawer are fragments and I would like for this item to just show an alert dialog
Navigation Drawer
I previously had a button in my MainActivity that used an on click listener and firebase.getInstance.signOut() to take the user back to the login activity:
Previous button on click listener
//on click listener for logout
/*btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
}
});*/
After some redesign I created a navigation drawer that utilizes fragments and i would like when the user selects logout to be prompted with an alert dialog asking are they sure , then for the button to act just how my previous one did and send the user back to the login activity.
I dont see the need of creating another fragment to logout but, correct me if I'm wrong.
Mainactivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.
OnNavigationItemSelectedListener,MainFragment.onFragmentBtnSelected{
public TextView verifyMsg;
public Button btnLogout, verifyEmailBtn;
FirebaseAuth fauth;
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
public NavigationView navigationView;
AlertDialog.Builder reset_alert;
LayoutInflater inflater;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//xml map to java
//btnLogout = findViewById(R.id.btnLogout);
verifyMsg = findViewById(R.id.verifyEmailMsg);
verifyEmailBtn = findViewById(R.id.btnVerifyEmail);
fauth = FirebaseAuth.getInstance();
reset_alert = new AlertDialog.Builder(this);
inflater =this.getLayoutInflater();
//new stuff
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new
ActionBarDrawerToggle(this, drawerLayout,
toolbar, R.string.nav_open, R.string.nav_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
actionBarDrawerToggle.syncState();
//fragment manager - creates instance of a fragment
//load default fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container_fragment,new MainFragment());
fragmentTransaction.commit();
//if the user email is not verified still show verify msg
if(!fauth.getCurrentUser().isEmailVerified()){
verifyEmailBtn.setVisibility(View.VISIBLE);
verifyMsg.setVisibility(View.VISIBLE);
}
//on click listener for verify email button
verifyEmailBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//send verification email
fauth.getCurrentUser().sendEmailVerification()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this,"Verification Sent",Toast.LENGTH_SHORT).show();
verifyEmailBtn.setVisibility(View.GONE);
verifyMsg.setVisibility(View.GONE);
}
});
}
});
}
//able to select the items in nav drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//auto close drawer
drawerLayout.closeDrawer(GravityCompat.START);
//Fragment fragment;
int mId = item.getItemId();
}
if (mId == R.id.homeItem){
//load default fragment
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment,new MainFragment());
fragmentTransaction.commit();
}
if (mId == R.id.profileSettings){
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment,new ProfileFragment());
fragmentTransaction.commit();
}
if (mId == R.id.logoutItem){
}
return true;
}
#Override
public void onBtnSelected() {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_fragment,new ProfileFragment());
fragmentTransaction.commit();
} }
MainFragment.java
public class MainFragment extends Fragment {
private onFragmentBtnSelected listener;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main,container,false);
Button clickme = view.findViewById(R.id.clickHF);
clickme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onBtnSelected();
}
});
return view;
}
#Override
public void onAttach(#NonNull Context context){
super.onAttach(context);
if(context instanceof onFragmentBtnSelected ){
listener =(onFragmentBtnSelected) context;
}
else {
throw new ClassCastException(context.toString() + " must implement listiner");
}
}
public interface onFragmentBtnSelected{
public void onBtnSelected();
}
}
nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:title="General">
<menu>
<item
android:id="#+id/homeItem"
android:icon="#drawable/ic_baseline_home_24"
android:title="#string/Home" />
</menu>
</item>
<item android:title="Account Settings">
<menu>
<item
android:id="#+id/profileSettings"
android:icon="#drawable/ic_baseline_account_circle_24"
android:title="Profile" />
</menu>
</item>
<item android:title="App Features">
<menu>
<item
android:id="#+id/logoutItem"
android:icon="#drawable/ic_baseline_power_settings_new_24"
android:title="#string/logout" />
</menu>
</item></menu>
Any help would be greatly appreatiated , having trouble best utilizing fragments in a navigation drawer

Mainactivity.java:
onNavigationItemSelected method inside this
without Alert Dialog
if (mId == R.id.logoutItem){
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
}
with Alert Dialog use
if (mId == R.id.logoutItem){
MaterialAlertDialogBuilder(this)
.setTitle("Title")
.setMessage("Message")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Ok") { _, _ ->
FirebaseAuth.getInstance().signOut();
startActivity(new
Intent(getApplicationContext(),LoginActivity.class));
finish();
}
.setNegativeButton("Cancel") { _, _ ->
Toast.makeText(this, "clicked Cancel", Toast.LENGTH_LONG).show()
}
.show()
}

Related

Hide Main Activity while using fragment

It has been awhile so I am struggling with fragments a bit. I am working on demos right now to get familiar again. What I am doing is in the main activity, I have a button to click which opens a fragment to enter information like name, address, etc. For some reason, the main activity doesn't go away and shows over the fragment. What am I doing wrong???
Note: I have not wired the cancel button yet to go back to Main Activity without doing anything.
Main Activity:
public class MainActivity extends AppCompatActivity {
public static User mUser = new User();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button requestServiceButton = findViewById(R.id.servicesButton);
requestServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
NewUser fragment = new NewUser();
transaction.replace(R.id.fragmentHolder, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
NewUser Class:
public class NewUser extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.dialog_new_user, container, false);
final EditText fName = v.findViewById(R.id.firstNameEditText);
final EditText lName = v.findViewById(R.id.lastNameEditText);
final EditText address = v.findViewById(R.id.editTextAddress);
final EditText city = v.findViewById(R.id.cityEditText);
final EditText email = v.findViewById(R.id.editTextEmailAddress);
final EditText password = v.findViewById(R.id.editTextPassword);
final EditText phoneNumber = v.findViewById(R.id.editTextPhone);
final EditText username = v.findViewById(R.id.usernameEditText);
final EditText zipCode = v.findViewById(R.id.zipEditText);
Button okButton = v.findViewById(R.id.btnOK);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.mUser.setFirstName(fName.getText().toString());
MainActivity.mUser.setLastName(lName.getText().toString());
MainActivity.mUser.setAddress(address.getText().toString());
MainActivity.mUser.setCity(city.getText().toString());
MainActivity.mUser.setEmailAddress(email.getText().toString());
MainActivity.mUser.setPassword(password.getText().toString());
MainActivity.mUser.setPhoneNumber(phoneNumber.getText().toString());
MainActivity.mUser.setUsername(username.getText().toString());
MainActivity.mUser.setZipCode(zipCode.getText().toString());
}
});
Button cancelButton = v.findViewById(R.id.btnCancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return v;
}

Button in fragment is not working after orientation change

the code works fine at the first time but when i rotate the screen to landscape it is disabling my fragment button even it is no longer usable after i change the orientation back to normal(portrait). why this is happening??
Main Activity
public class MainActivity extends AppCompatActivity {
Button button;
EditText editText;
TextView textView;
fragment_one fragment_one;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment_one = new fragment_one();
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.container,fragment_one).commit();
button = (Button) findViewById(R.id.mybutton_main);
textView = (TextView) findViewById(R.id.mytextView_main);
editText = (EditText) findViewById(R.id.myedittext_main);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("button Clicked");
editText.setText("button Clicked");
}
});
}
}
Fragment
public class fragment_one extends Fragment implements View.OnClickListener {
Button button;
TextView textView;
public fragment_one() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment_one, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.mybutton_frag);
textView = (TextView) getActivity().findViewById(R.id.mytextView_frag);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
textView.setText("clicked");
}
}
Try this:
if (savedInstanceState == null) {
fragment_one = new fragment_one();
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.container,fragment_one)
.commit();
}

OnClickListener() doesn't allow me to start the program

this is oncreate function im calling Appdata() inside this method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=new DatabaseHelper(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
email=(EditText)findViewById(R.id.editText4);
pass=(EditText)findViewById(R.id.editText5);
conpass=(EditText)findViewById(R.id.editText6);
register=(Button)findViewById(R.id.btn_register);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
AddData();
}
public void AddData() {
register.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
boolean isInserted = db.insertData(email.getText().toString(),pass.getText().toString(), conpass.getText().toString());
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
In Appdata function OnClickListener() is created but my problem is when i run this program app become stop and restart
when i hide inside code of Appdata() program ,its run without any error
i uploaded image click here
There is no button exists with the id R.id.btn_register in your xml file this is causes NullPointerException when you tried to set up the click listener. Add the buttons and EditTexts in your xml layout and you're good to go.
Add the below code in your activity_main.xml
<include
layout= "#layout/your_extra_layout_file"/>
You can use android:onclick="function_name" attribute with the button
And implement the function in the activity like below.
public void function_name(View view) {
//do the action here
}

calling fragment from another fragment on button click

public class MasterDetailFragment extends Fragment {
public interface onButtonItemSelected {
public void onButtonItemSelected(int id);
}
onButtonItemSelected mListner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Defines the xml file for the fragment
View view = inflater.inflate(R.layout.masterdetail_fragment, container, false);
// Setup handles to view objects here
// etFoo = (EditText) view.findViewById(R.id.etFoo);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button _fragment0=(Button) getActivity().findViewById(R.id.button1);
Button _fragment1=(Button) getActivity().findViewById(R.id.button2);
Button _fragment2=(Button) getActivity().findViewById(R.id.button3);
mListner=(onButtonItemSelected) getContext();
_fragment1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
System.out.println(" ************ GENERATED ID IS : " + id);
if( id==R.id.fragment1) {
FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
fragTransaction.replace(R.id.masterdetail_fragment,new MovieDetailFragment() );
fragTransaction.addToBackStack(null);
fragTransaction.commit();
System.out.println(" ************ button1 " + id);
}
}
});
_fragment0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
System.out.println(" ************ GENERATED ID IS : " + id);
if( id==R.id.fragment0) {
mListner.onButtonItemSelected(R.id.myname);
System.out.println(" ************ button2 : " + id);
}
}
});
}
}
I am trying load movieDetail fragment from masterDetail fragment in a button click event.
I am not able to add new instance of movieDetail fragment as it throws the following compile time error. What should I do to be able to add new instance of the movie details fragment.
When you want to go to another fragment from current fragment class you should use
getChildFragmentManager()
instead of
getFragmentManager()
That's solve your problem.

Button state change when opening option menu

Why does a button that is pressed, lose it's state when opening the options menu?
I made a sample activity to make it clear:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button1);
btn.setPressed(true); // set the state
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
}
We set the button in our view to the pressed state.
When you run the project and then open the options menu, the pressed state is gone. It looks like the button has removed it's state.
What is the solution/workaround to keep the button state without redrawing the whole activity? Perhaps the implementation of a Button is not ment to have this behaviour and a toggle button needs to be used?
public class MainActivity extends Activity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn; = (Button) findViewById(R.id.button1);
btn.setPressed(true); // set the state
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
//here you can set your state....
btn. //set the state...
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
}

Resources