HamidTB
HamidTB

Reputation: 1501

Closing the application from a fragment causes returning to the parent activity

I tried several ways to end application from inside of a fragment, like:

system.exit(1)
android.os.Process.killProcess(android.os.Process.myPid());
getActivity().finish();

and it is all of fragment code;Exit code put on exitDialog.setPositiveButton oncliklistener that in my try cuse backing to parent activity instead exit

package com.TB.mylistprojct;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class ActFooter extends Fragment
{
    View            EMyView         =null;

    Button          BtnExit         =null;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater Inflater,ViewGroup Container,Bundle SavedInstanceState)
{
    View MyView=Inflater.inflate(R.layout.actfooter, Container,false);
    EMyView=MyView;
    InitialUI();
    return MyView;
}

public void InitialUI()
{
    BtnExit=(Button)EMyView.findViewById(R.id.Btn_exit);
    BtnExit.setOnClickListener(BtnExit_OnClick);
}

public OnClickListener BtnExit_OnClick=new OnClickListener()
{

    @Override
    public void onClick(View arg0)
    {
        AlertDialog.Builder exitDialog=new AlertDialog.Builder(getActivity());

        exitDialog.setTitle("Warning");
        exitDialog.setMessage("Exit Program");
        exitDialog.setPositiveButton("YSE", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                // Exit Code PUT Here
            }
        });
        exitDialog.setNegativeButton("NO", null);
        exitDialog.show();
    }
};
}

But the app returns to the parent activity

Upvotes: 4

Views: 17444

Answers (9)

aryeahtyagi
aryeahtyagi

Reputation: 1

You Just need to hold the instance of the parent activity in your fragment to call it's functions like in this case function is to close the app so just in your fragment type

syntax is -> referencesObj = activity cast as "parentClass"

kotlin -> val parentActivity = activity as MainActivity
Java   -> MainAcitivity parentAcitivity = (MainActivity) getActivity();

and then just use it's function like finish():

parentActivity.finish()

    

Upvotes: 0

Shubham Bhardwaj
Shubham Bhardwaj

Reputation: 1

I had the same problem today and i tried this code and it worked fine for me and i hope will word for everyone.

put this code in fragment
Intent intent = new Intent(fragment_name.this, MainActivity_name.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("LOGOUT", true);
            startActivity(intent);
            fragment_name.this.finish();

and put this code inside onCreate function

    if (getIntent().getBooleanExtra("LOGOUT", false))
        {
            finish();
            System.exit(0);
        }

thanks to @HamidTB :)

Upvotes: 0

Rishijay Shrivastava
Rishijay Shrivastava

Reputation: 559

Apart from :

getActivity().finish()

This also worked for me :

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Upvotes: 0

Mr. Droid
Mr. Droid

Reputation: 340

Recently I was having the same issue with my app. I used two exit button one in main activity other one in a fragment

For main activity:- first I create a button in main activity.xml file with onClick attributes then in java I used:

Inside MainActivity.java:

For Fragment:- I use setOnClickListener: Inside HomeFragment.java:

Below is the code which works for me for fragment inside MainActivity.java

public void clickExit(View v){
finish();
}

inside Fragment.java

button_2=(Button) view.findViewById(R.id.home_exit_btn);
    button_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Closing application...",   Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        });
        return view;
    }

Upvotes: 1

Kamala Dhar
Kamala Dhar

Reputation: 11

you can use .....

if(keyCode == KeyEvent.KEYCODE_BACK)
{
   getActivity().moveTaskToBack(true);
}

Upvotes: 0

Satya Sundar Patra
Satya Sundar Patra

Reputation: 1

The app will only exit if there are no activities in the back stack. So, add android:noHistory="true" to all the activities(which you don't want to be back stacked) in your manifest file. And, then to close the app call the finish() in the OnBackPressed() method.

<activity 
    android:name=".activities.MainActivity" 
    android:noHistory="true" />

Upvotes: 0

Inari
Inari

Reputation: 1

This work very well for me (all go in the Activity that have the fragment container):

private void backStack(){
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        getSupportFragmentManager().popBackStack();
    }else
    if(getSupportFragmentManager().getBackStackEntryCount()==1){
        this.finish();
    }
}

you must use this code in here:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    boolean back = false;
    if(keyCode == KeyEvent.KEYCODE_BACK){
        back = true;
        backStack();
    }
    return back;

}

Upvotes: 0

Dyna
Dyna

Reputation: 2305

try this:

getActivity().moveTaskToBack(true); 
getActivity().finish();

Upvotes: 10

HamidTB
HamidTB

Reputation: 1501

Finally i find the solution

first i add fllowing code in fragment

Intent intent = new Intent(getActivity(), ACTMain.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("LOGOUT", true);
                startActivity(intent);

                getActivity().finish();

and in main activity(in onCreate function) i check status with if statement and exit :)

        if (getIntent().getBooleanExtra("LOGOUT", false))
    {
        finish();
    }

Upvotes: 7

Related Questions