简体   繁体   中英

How to call an activity method from a fragment?

I need to call a method that is in an activity from a fragment, i can't even instatiate the activity in the fragment, I don't know how to approach this problem. I need to call the activity's method from an onClick that is part of the fragment, because i need to update a value because it changed (ex: the value is 1, after onClick the value is 2 but the activity doesn't update).

This is the method from the activity:

   public void onUpdate(){

    //setCount.setText(Integer.toString(new Database(this).getCountCart(FirebaseAuth.getInstance().getCurrentUser().getUid())));
    setCount.setText(Integer.toString(new Database(this).getTotalCount(FirebaseAuth.getInstance().getCurrentUser().getUid())));

    cart = new Database(this).getCarts(FirebaseAuth.getInstance().getCurrentUser().getUid());
    int total = 0;
    for(OrderModel order:cart)
        total+=(Integer.parseInt(String.valueOf(order.getPret()))) *(order.getCantitate());
    Locale locale = new Locale("ro","RO");
    NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
    totalPrice.setText(fmt.format(total));

}

Here is where i try to call it from the fragment:

fragmentItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
  new Database(getActivity().getBaseContext()).increaseCart(FirebaseAuth.getInstance().getCurrentUser().getUid(),fragmentUnuModel.getDenumire());
  food.onUpdate();
}

And here is the error:

  java.lang.NullPointerException: Attempt to invoke virtual method 'void com.cosnila.orderme.Food.onUpdate()' on a null object reference
    at com.cosnila.orderme.Fragments.FragmentUnu$1$1.onClick(FragmentUnu.java:123)

If you have method onUpdate in your activity and want to call an activity method from fragment, call it as below in fragment where required.

((YouActivityName) getActivity()).onUpdate();

Be sure to replace your activity name.

img_search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent displayFlights = new Intent(getActivity(), SelectFlight.class);
            startActivity(displayFlights);
        }
    });

You can make onUpdate() static .

Your method header should look like this:

public static void onUpdate() {
   // your code
}

If you are using Kotlin instead of java you should try this

(activity as yourActivityName?)?.yourPublicMethod()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM