So how can I pass a function as a parameter to another function, for example i want to pass this function:
public void testFunkcija(){
Sesija.forceNalog(reg.getText().toString(), num);
}
in this:
public static void dialogUpozorenjaTest(String poruka, Context context, int ikona, final Method func){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Stanje...");
alertDialogBuilder
.setMessage(poruka)
.setIcon(ikona)
.setCancelable(true)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//here
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
the simplest way is using runnable
let's see how
//this function can take function as parameter
private void doSomethingOrRegisterIfNotLoggedIn(Runnable r) {
if (isUserLoggedIn())
r.run();
else
new ViewDialog().showDialog(MainActivity.this, "You not Logged in, please log in or Register");
}
now let's see how can I pass any function it it (I will not use lambda expression)
Runnable r = new Runnable() {
@Override
public void run() {
startActivity(new Intent(MainActivity.this, AddNewPostActivity.class));
}
};
doSomethingOrRegisterIfNotLoggedIn(r);
let's pass another function
Runnable r = new Runnable() {
@Override
public void run() {
if(!this.getClass().equals(MyProfileActivity.class)) {
MyProfileActivity.startUserProfileFromLocation( MainActivity.this);
overridePendingTransition(0, 0);
}
}
};
doSomethingOrRegisterIfNotLoggedIn(r);
thas's it. happy big thinking...
You can use a Runnable to wrap your method:
Runnable r = new Runnable() {
public void run() {
Sesija.forceNalog(reg.getText().toString(), num);
}
}
Then pass it to your method and call r.run();
where you need it:
public static void dialogUpozorenjaTest(..., final Runnable func){
//.....
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
func.run();
}
});
}
Well, since there are no dellegates in Java (oh C# I miss you so bad), the way you can do it is creating a class that implements a interface, maybe runnable or some custom interface and than you can call your method through the interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With