How to Define Callbacks in Android

How to Define Callbacks in Android?

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

Just as a random example:

// The callback interface
interface MyCallback {
void callbackCall();
}

// The class that takes the callback
class Worker {
MyCallback callback;

void onEvent() {
callback.callbackCall();
}
}

// Option 1:

class Callback implements MyCallback {
void callbackCall() {
// callback code goes here
}
}

worker.callback = new Callback();

// Option 2:

worker.callback = new MyCallback() {

void callbackCall() {
// callback code goes here
}
};

I probably messed up the syntax in option 2. It's early.

What are callbacks and how do I implement them in Android?

Do you mean callback using interface?
if yes here's an example

this is callbackmenu.java

package com.example.test.callback;

public interface CallbackCalendar {
public void onClick();
}

this is an example how you implement it

public class CallbackCell implements CallbackCalendar{

@Override
public void onClick() {
Log.i("TAG", "IT WORKS!);
addChild(2);
}
}

this is an example that will allow you to access a view from another view
like what I use in my calendar library, I create 3 view classes, calendar View, calendar row, calendar cell

with passing this callback from calendar view to calendar cell we can add view,set value or anything else in the calendar view from the calendar cell (calendar cell is a part of calendar row and calendar row is a part of calendar view) in this example I'm trying to set whenever the user click the cell we will add another view in the calendar view (main view)

this is the example of using callback in the calendar cell

public CalendarCell(Context context,int day,final CallbackCalendar callback)
{
super(context);
final int temp = day;
this.context = context;
this.setBackgroundColor(Color.parseColor("#FFFFFFFF"));
LinearLayout.LayoutParams lpCalendarCell = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lpCalendarCell.weight = 1;
this.setLayoutParams(lpCalendarCell);
this.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
callback.onClick();
}
});
addContainer(day);
}

so I set the callback in the calendar view and pass it to the calendar row and pass it again to the calendar cell and call the onClick in the calendar cell

I think that's all if you have any question feel free to write in the comment :)

Callback Method Android

Chris, Imagine that you have a function:

fun test() {
...
}

Then you decided to add some magic to it. For instance, add 'block' that could be done after function test finished its job. So, here we need to put some extra into code:

interface CallbackInterface {
fun doJob()
}

and your function become:

fun test(block: CallbackInterface) {
...
block.doJob()
}

so then you can call your test function like this (or pass CallbackInterface into test function):

test(object: CallbackInterface {
override fun doJob() {
...
}
})

In general, the point is to pass the interface as a parameter in function and call it whenever you want and do on another end do whatever you want with the results.

or in Kotlin you can do like this:

fun test(block: ()-> Unit) {
...
block.invoke() // or just block()
}

and use it:

test {
...
}

What is callback in Android?

Here is a nice tutorial, which describes callbacks and the use-case well.

The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".

Here's a example:

class A implements ICallback {
MyObject o;
B b = new B(this, someParameter);

@Override
public void callback(MyObject o){
this.o = o;
}
}

class B {
ICallback ic;
B(ICallback ic, someParameter){
this.ic = ic;
}

new Thread(new Runnable(){
public void run(){
// some calculation
ic.callback(myObject)
}
}).start();
}

interface ICallback{
public void callback(MyObject o);
}

Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.

In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.

implementing a callback in android with Activities

I would do it like this :

Create an interface :

public interface MyReceiver {
public void onReceive();
}

In you activity :

public class MyActivity implements MyReceiver{

public static MyReceiver myReceiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_new_booking);
super.onCreate(savedInstanceState);
myReceiver = this;
}

@Override
protected void onDestroy() {
myReceiver = null;
}


@Override
public void onReceive(){
//Implement your code here or send objects in the parameters
}

}

To Call it just use this:

if(MyActivity.myReceiver!=null){
MyActivity.myReceiver.onReceive();
}

No need to create activity instances.

In this case i would also suggest you to use startActivityForResult.

Hope this helps.

How to pass different callbacks to same function in android

I would like to recommend to have a separate interface class without keeping it inside of a Class or Activity.

So declare an interface like this. Create a separate file.

public interface VolleyCallback {
void onSuccess(String result);
}

Then create a public instance of the VolleyCallback interface in your VolleyAPIService class like the following. Remove the parameter from the volleyPost method for cleaner implementation.

public class VolleyAPIService {

public VolleyCallback callback;

public void volleyPost(String URL, Map<String, String> param, Context context) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
final Map<String, String> params = param;

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
callback.onSuccess(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() {;
return params;
}
};
requestQueue.add(stringRequest);
}
}

Now from your MainActivity, implement the interface that you have created and override the callback function like the following.

public class MainActivity extends AppCompatActivity implements VolleyCallback {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

companyLogin("abc", "123");
}
public interface VolleyCallback {
void onSuccess(String result);
}

public void companyLogin(String companyname, String password) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
final Map<String, String> params = new HashMap<String, String>();
params.put("name", companyname);
params.put("pwd", password);

Intent volley_service = new Intent(MainActivity.this, VolleyAPIService.class);
MainActivity.this.startService(volley_service);

VolleyAPIService volleyAPIService = new VolleyAPIService();

// Assign the callback here to listen the response from the API service.
volleyAPIService.callback = this;
volleyAPIService.volleyPost(URL, params, MainActivity.this);
}

@Override
public void onSuccess(String result) {
// Handle the success or failure here
if (!result.isEmpty()) {
Intent userLoginActivity = new Intent(MainActivity.this, UserLogin.class);
startActivity(userLoginActivity);
} else {
AlertDialog.Builder login_failed = new AlertDialog.Builder(MainActivity.this);
login_failed.setMessage("Login Failed, invalid credentials")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

}
});

AlertDialog alert = login_failed.create();
alert.show();
}
}
}

Do the same for your UserLogin class.

In case of having multiple API calls in a single Activity or Fragment, you might want to keep a flag in the VolleyAPIService class and passing that to the callback function you can detect which API response you are getting in your onSuccess callback.

Hope that is clear. Please feel free to ask any questions.

How to realize a callback in android?

You can easily use an interface and handle the callback accordingly from your calling activity/class/other thread. Here is an example.

Define an interface like the following first.

public interface ThreadFinishListener {
void onFinish();
}

Let us assume you are instantiating a Thread from an Activity. Hence implement the listener in your Activity like the following.

public class MainActivity extends AppCompatActivity implements ThreadFinishListener {
// .... Other functions in your activity

@Override
void onFinish() {
// Do something when the Thread is finished and returned back to the activity
// This is actually your callback function.
}
}

Now modify the constructor of your Thread class so that you can pass the listener to it.

public class MyThread extends Thread {
private ThreadFinishListener listener;

public MyThread(ThreadFinishListener listener){
this.listener = listener;
}

public void run(){
//Do some stuff
finish();
}

public void finish() {
// This will invoke the function call in your activity
listener.onFinish();
}
}

Now while initializing your Thread, you might want to pass the listener to it as follows.

MyThread thread = new MyThread(this);
thread.run();

I hope that suffices.



Related Topics



Leave a reply



Submit