call a method in the parent activity after dialog fragment is dismissed - java

I have a activity which prompts a dialog fragment. I want to call a method in the parent activity when the dialog fragment is dismissed. Here is the activity that contains the dialog fragment.
public class HomScr extends AppCompatActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.das_boa);
initialize();
}
private void initialize(){
tv = findViewById(R.id.tv);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProEdiCon dia_fra = new ProEdiCon();
dia_fra.show((this).getSupportFragmentManager(), "pro_edi_con");
}
}
}
private void method_to_run_onDismiss(){
tv.setText("method to run is executed");
Toast.makeText(this, "method to run successfully executed on dismiss Dialog Fragment", Toast.LENGTH_SHORT).show();
}
}
And the below code is the DialogFragment which gets dismissed in certain point and after that the parent activity must call the method to run on dismiss.
public class ProEdiCon extends DialogFragment {
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle bun) {
View pro_vie = inflater.inflate(R.layout.pro_edi_dat, container, false);
TextView tv = pro_vie.findViewById(R.id.tv);
tv.setText("I am the Dialog Fragment who is gonna be dismissed soon");
Button btn = pro_vie.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
}
return pro_vie;
}
}
So can anybody help me do this?

You can use Dialog and set Dismiss listener and listen for the event when dialog will be dismissed
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProEdiCon dia_fra = new ProEdiCon();
dia_fra.show();
dia_fra.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//do some action here
}
});
}
}
and your Dialog will be like this:
public class ProEdiCon extends Dialog {
public ProEdiCon (#NonNull Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pro_edi_dat);
TextView tv = pro_vie.findViewById(R.id.tv);
tv.setText("I am the Dialog Fragment who is gonna be dismissed soon");
Button btn = pro_vie.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
}
}

You must create interface like this
CallBackListener.java
public interface CallBackListener {
void onDismiss();
}
Then in your fragment
public class ProEdiCon extends DialogFragment {
private CallBackListener callBackListener;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//getActivity() is fully created in onActivityCreated and instanceOf differentiate it between different Activities
if (getActivity() instanceof CallBackListener)
callBackListener = (CallBackListener) getActivity();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle bun) {
View pro_vie = inflater.inflate(R.layout.pro_edi_dat, container, false);
TextView tv = pro_vie.findViewById(R.id.tv);
tv.setText("I am the Dialog Fragment who is gonna be dismissed soon");
Button btn = pro_vie.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(callBackListener != null)
callBackListener.onDismiss();
dismiss();
}
}
return pro_vie;
}
}
And finally in your Activity
public class HomScr extends AppCompatActivity implements CallBackListener {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.das_boa);
initialize();
}
private void initialize(){
tv = findViewById(R.id.tv);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProEdiCon dia_fra = new ProEdiCon();
dia_fra.show((this).getSupportFragmentManager(), "pro_edi_con");
}
}
}
private void method_to_run_onDismiss(){
tv.setText("method to run is executed");
Toast.makeText(this, "method to run successfully executed on dismiss Dialog Fragment", Toast.LENGTH_SHORT).show();
}
#Override
public void onDismiss() {
method_to_run_onDismiss();
}
}

You might want to use a DialogListener interface inside your Dialog class and call it before the dialog is dissmissed.
Interface with your method
public interface MyInterface {
void method_to_run_onDismiss();
}
Dialog - create an instance of the interface and call it right before dismiss();
public class ProEdiCon extends DialogFragment {
private MyInterface myInterface;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle bun) {
...
myInterface = (MyInterface) context;
Button btn = pro_vie.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myInterface.method_to_run_onDismiss();
dismiss();
}
}
return pro_vie;
}
}
Activity class implement the interface and use the method you already have
Public class HomScr extends AppCompatActivity implements MyInterface {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.das_boa);
initialize();
}
private void initialize(){
tv = findViewById(R.id.tv);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProEdiCon dia_fra = new ProEdiCon();
dia_fra.show((this).getSupportFragmentManager(), "pro_edi_con");
}
}
}
private void method_to_run_onDismiss(){
tv.setText("method to run is executed");
Toast.makeText(this, "method to run successfully executed on dismiss Dialog Fragment", Toast.LENGTH_SHORT).show();
}
}

Related

setOnClickListener button doesn't work Android studio

I'm new in java and I have tried to make a food app in android studio. I have a bar in app and when I click on cart my app is crashing.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView.Adapter adapter, adapter2;
private RecyclerView recyclerViewCategotyList, recyclerViewPopularList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewCategoty();
recyclerViewPopular();
bottomNavigation();
}
private void bottomNavigation() {
LinearLayout homeBtn=findViewById(R.id.homeBtn);
LinearLayout cartBtn=findViewById(R.id.cartBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,CartActivity.class));
}
});
}
And I have this error: at com.example.food.Activity.MainActivity$2.onClick(MainActivity.java:48)
This is CartActivity
public class CartActivity extends AppCompatActivity {
private RecyclerView.Adapter adapter;
private RecyclerView recyclerViewList;
private ManagementCart managementCart;
private TextView totalFeeTxt, taxTxt, deliveryTxt, totalTxt, emptyTxt;
private double tax;
private ScrollView scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
managementCart = new ManagementCart(this);
initView();
initList();
bottomNavigation();
calculateCard();
}
private void bottomNavigation() {
LinearLayout homeBtn = findViewById(R.id.homeBtn);
LinearLayout cartBtn = findViewById(R.id.cartBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
}
I don't know what's wrong and why my setOnClickListener doesn't work.
Thank you.
I think your button R.id.homeBtn is not LinearLayout, can you show your xml file?
If your buttons are Button classes, try this
private void bottomNavigation() {
Button homeBtn = findViewById(R.id.homeBtn);
Button cartBtn = findViewById(R.id.cartBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
}

Button in MainActivity, Reset spinner in a DialogFragment

I have two buttons in MainActivity, the first one opens a custom DialogFragment with some spinners and in the other button it resets the spinners of this DialogFragment.
When I click the reset button it calls this method that is in the DialogFragment:
public class FilterDialogFragment extends DialogFragment {
private View view;
// ...
#Nullable
#Override
public View onCreateView(#NotNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dialog_filters, container, false);
// start the spinners and adapters here
return view;
}
public void resetFilters() {
if (view != null) {
categorySpinner.setSelection(0);
productSpinner.setSelection(0);
priceSpinner.setSelection(0);
}
}
// some more codes here
}
My MainActivity:
public class MainActivity extends AppCompatActivity {
private FilterDialogFragment filterDialog;
private Button button_clear;
private Button button_filter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_clear = findViewById(R.id.button_clear);
button_filter = findViewById(R.id.button_filter);
filterDialog = new FilterDialogFragment();
button_filter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show the dialog containing filter options
filterDialog.show(getSupportFragmentManager(), FilterDialogFragment.TAG);
}
});
button_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//reset all filters
filterDialog.resetFilters();
}
});
//some more codes here
}
//some more methods here
}
But by clicking the button that opens the DialogFragment, the values of the Spinners remain the same instead of returning the data of position 0 of each spinner.
Would anyone know how to solve this? I've tried everything and I can not.
The simplest way I ended up finding, was to delete the resetFilters method, and instead I did so:
button_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//reset all filters
filterDialog = new FilterDialogFragment(); }
});

Passing data through Fragments

My app is simple just i have a FragmentA and FragmentB first one has a single button pass String data ("Hi i'm A") through second fragment who has a text to show this message My question is
Why my "ModifyTxt" method doesn't work ?
public class newFragmentA extends Fragment{
Button button;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.newfragmenta_layout,container,false);
}
newFragmentB newfragmentB;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = getActivity().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
newfragmentB.ModifyTxT("Hi I'm A");
}
});
}
}
And this is my second Fragment(FragmentB)
public class newFragmentB extends Fragment {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.newfragmentb_layout,container,false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textView = getActivity().findViewById(R.id.TV);
}
public void ModifyTxT(String string){
textView.setText(string); }
}
Try this:
public class FragmentB extends Fragment {
// ...
public static FragmentB newInstance() {
return new FragmentB();
}
}
In FragmentA :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentB newFragment = FragmentB.newInstance();
newFragment.modifyTxT("Hi I'm A");
}
});
Be careful to coding rules : uppercase first letter for class name, lowercase first letter for method...
Prefer using Interface to communicate with Fragments
public class FragmentA extends Fragment{
public interface MyCallback{
void modifyTxT(String text); // method naming convention start with small letter.
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button = getActivity().findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (newfragmentB instanceof MyCallback) {
((MyCallback)newfragmentB).modifyTxT("Hi I'm A");
}
}
});
}
}
public class FragmentB extends Fragment implements FragmentA.MyCallback{
public static FragmentB getInstance(){
return new FragmentB();
}
#Override
public void modifyTxT() {
}
}

How to switch between fragments using buttons

Fragment 1:
public class homePage extends Fragment {
private OnFragmentInteractionListener mListener;
private View view;
public homePage() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home_page, container, false);
Button btnLogin = (Button) view.findViewById(R.id.login);
Button btnRegister = (Button) view.findViewById(R.id.register);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginView();
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerView();
}
});
return view;
}
public static homePage newInstance() {
homePage fragment = new homePage();
Bundle args = new Bundle();
return fragment;
}
public void registerView(){}
public void loginView(){}
public interface OnFragmentInteractionListener {
}
}
Acitivty :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
homePage homepage = new homePage();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, homepage)
.commit();
}
}
}
My fragment1 has two buttons with the id's "login" and "register". Whenever login is clicked, I want to go to my fragment_login.xml, and when register is clicked I want to go to my fragment_register.xml. Should I create these functions in my activity or in my fragment? And how should I do this? I'm fairly new to android and I'm trying to learn these basic things atm. Thanks for the help :(
Login context: "com.example.hoofdgebruiker.winkelskortrijk.login"
Register context: "com.example.hoofdgebruiker.winkelskortrijk.register"
You have to make a communication between Fragment objects via an Interface.
The Activity that make the switch between your fragments needs to implement that Interface.
So, in your case your classes must be defined as follows. This is your Interface, it helps you to tell your activity that a button has been clicked from within your Fragment:
public interface HomeClickListener {
void onLoginClick();
void onRegisterClick();
}
Your Activity needs to implement the above interface in order to be notified when a button has been clicked:
public class HomeActivity extends Activity implements HomeClickListener {
void onLoginClick() {
// Your activity code to replace your current Fragment with your Login fragment
}
void onRegisterClick() {
// Your activity code to replace your current Fragment with your Register fragment
}
}
Your fragment is hosted by an Activity, so you need to have a reference to it and notify it via an Interface:
public class LoginFragment extends Fragment {
final HomeClickListener homeClickListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
homeClickListener = (homeClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnHeadlineSelectedListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home_page, container, false);
Button btnLogin = (Button) view.findViewById(R.id.login);
Button btnRegister = (Button) view.findViewById(R.id.register);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homeClickListener.onLoginClick();
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
homeClickListener.onRegisterClick();
}
});
return view;
}
}
More information here.

Android :- Separate class for handling views clicks etc;

I am new to development field. I am developing android application where in my activity_main layout I have many different items. On clicking one of the button the top layout is replaced with a new layout.
Now instead of defining the new layouts buttons, textview etc in my main class , I want to have a separate class which can initialize my buttons etc, and also in that class I can declare onClickListners.
In my main Activity I want:-
public void onCreate(){
button bb = (Button)findViewById(R.id.mybutton);
View CurrentContentView= getLayoutInflater().inflate(R.layout.activity_main, null, false);
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyNewViewInit(CurrentContentView);
}
});
}
In my MyNewViewInit() class :-
public class MyNewViewInit{
ImageButton backbutton;
ChipsMultiAutoCompleteTextview search;
ImageButton searchclear;
ImageButton modeTime;
ImageButton modeTag;
TextView modeTimeTxt;
TextView modeTagTxt;
ScrollView mainScroll;
ScrollView selectedScroll;
public MyNewViewInit(View v){
backbutton = (ImageButton)v.findViewById(R.id.backbutton);
search = (ChipsMultiAutoCompleteTextview)v.findViewById(R.id.search);
searchclear = (ImageButton)v.findViewById(R.id.searchclear);
modeTime = (ImageButton)v.findViewById(R.id.modeTime);
modeTag = (ImageButton)v.findViewById(R.id.modeTag);
modeTimeTxt = (TextView)v.findViewById(R.id.modeTimeTxt);
modeTagTxt = (TextView)v.findViewById(R.id.modeTagTxt);
mainScroll = (ScrollView)v.findViewById(R.id.HAT1);
selectedScroll = (ScrollView)v.findViewById(R.id.HAT2);
tag = new OtherHelper().arrayread();
mainHashTag.setVisibility(View.GONE);
selectedHashTag.setVisibility(View.GONE);
clickListners();
}
public void clickListners(){
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
searchclear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTimeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTagTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
So when I try using this code the onclicklistners are not working.
What is the best way to do this.
Thanks
Write an Interface in your class,
class MyNewViewInit{
public interface ClickListenerInterface{
void onCLickSomething(Something something);
}
ClickListenerInterface mClickListener;
...
public MyNewViewInit(View v,ClickListenerInterface clickListener){
mClickListener = clickListener;
...
}
public void clickListners(){
...
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mClickListener!=null){
mClickListener.onCLickSomething(v);
}else{
//throw an error that activity should implement ClickListenerInterface
}
}
});
}
}
In your Activity,
class MyActivity extends Activity implements ClickListenerInterface{
public void onCreate(){
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyNewViewInit(CurrentContentView,this);
//if using Android Studio, then use the context menu to implement the interface
}
});
}
void onCLickSomething(Something something){
//do something with something
}
}
You can try do a abstract class extends Activity, like :
public abstract class MyInitActivity extends Activity
{
EditText editText;
TextView textView;
#Override
public void setContentView(int layoutResID)
{
super.setContentView(layoutResID);
editText = (EditText)findViewById(R.id.editText);
textView = (TextView)findViewById(R.id.textView);
}
}
and in your main activity you can extend your abstract class, like :
public class MainActivity extends MyInitActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*********** Listener ************/
public void onButtonClick(View v)
{
textView.setText(editText.getText().toString());
}
}
you can also implement onClick() in the abstract class
i don't know if its a good practice , i prefer do the methods with view arguments and set this methods in the layout.xml file .
I had use this in one of code
STEP 1
Declare button in layout(XML file)
STEP 2
Declare all ur button like this--
Button btn1 = (Button)findViewById(R.id.btn1);
Button btn2 = (Button)findViewById(R.id.btn2);
Button btn3 = (Button)findViewById(R.id.btn3);
............so on
STEP 3
implement View.OnClickListener
Now after step 2 do this
btn1.setOnClickListener(this);
.
.
.
same way for all
STEP 4:
Use switch case inside Onclick
public void OnClick(View v)
{
case:R.id.btn1{
//ur command similarly use multiple case stmt for many button
}
}

Categories

Resources