'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)
Solution 1:[1]
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.
Solution 2:[2]
img_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent displayFlights = new Intent(getActivity(), SelectFlight.class);
startActivity(displayFlights);
}
});
Solution 3:[3]
You can make onUpdate() static
.
Your method header should look like this:
public static void onUpdate() {
// your code
}
Solution 4:[4]
If you are using Kotlin instead of java you should try this
(activity as yourActivityName?)?.yourPublicMethod()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Muhammad Maqsood |
Solution 2 | bunty785 |
Solution 3 | |
Solution 4 | Safi Ullah |