Monday, September 2, 2013

Implement callback function with interface

This example demonstrate how to implement callback function with interface.

Implement callback function with interface

Create a MyAsyncTask class extends AsyncTask. Inside MyAsyncTask, interface DoSomething declared. MyAsyncTask class handle the background timing only, know knowing about the actual jobs. The actual jobs are in the class implement DoSomething.

package com.example.androidcallback;

import android.os.AsyncTask;
import android.os.SystemClock;

public class MyAsyncTask extends AsyncTask<Void, Void, Void> {

 interface DoSomething {
  void doInBackground(int progress);
  void doPostExecute();
 }

 DoSomething myDoSomethingCallBack;
 int myMax;
 
 MyAsyncTask(DoSomething callback, int max){
  myDoSomethingCallBack = callback;
  myMax = max;
 }

 @Override
 protected Void doInBackground(Void... params) {
  for (int i = 0; i <= myMax; i++) {
   SystemClock.sleep(100);
   myDoSomethingCallBack.doInBackground(i);
  }
  return null;
 }

 @Override
 protected void onPostExecute(Void result) {
  super.onPostExecute(result);
  myDoSomethingCallBack.doPostExecute();
 }

}


MainActivity.java, implements DoSomething. Itself (this) will be passed to MyAsyncTask constructor, to implement callback function.
package com.example.androidcallback;

import com.example.androidcallback.MyAsyncTask.DoSomething;

import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity implements DoSomething{
 
 ProgressBar myProgressBar;
 MyAsyncTask myAsyncTask;
 int myProgress;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  myProgressBar = (ProgressBar)findViewById(R.id.myprogressbar);
  
  myProgress = 0;
  myAsyncTask = new MyAsyncTask(this, 100);
  myAsyncTask.execute();
 }

 @Override
 public void doInBackground(int i) {
  myProgressBar.setProgress(i);
 }

 @Override
 public void doPostExecute() {
  Toast.makeText(MainActivity.this, 
    "Finish", Toast.LENGTH_LONG).show();
 }

}


layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    
    <ProgressBar 
        android:id="@+id/myprogressbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        android:progress="0" />

</LinearLayout>


download filesDownload the files.

9 comments:

Anonymous said...

Very Good Example.... :)
Keep it up..

Guihgo said...

this blog... always helping me so much.


THANKSSSS :)

za said...

great thank

Anonymous said...

you just learn me for new way of programming... thanks !!

Anonymous said...

Hey man, you make my day!!
Thank you.

Anonymous said...

Thank you. This is cool.

Unknown said...

i undrestand object oriented programming with your post. thanks. i o you too much

Anonymous said...

no me sale
----layout--















----activity--


public class MainActivity extends AppCompatActivity implements OneFragment.Callback {

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

Bundle arg = new Bundle();
arg.putString(OneFragment.ARG_NOMBRE, "Luis Rios");

OneFragment oneFragment = (OneFragment) Fragment.instantiate(MainActivity.this,OneFragment.class.getName(),arg);

//ACA ESTOY ASIGNANDO DE MANERA MANUAL QUIEN IMPLEMENTA LA INTERFAZ DEL FRAGMENTO
oneFragment.setCallback(MainActivity.this);

getFragmentManager()
.beginTransaction()
.replace(R.id.flMainConteiner,oneFragment)
.commit();
}

@Override
public void onOneFragmentClick() {
Toast.makeText(MainActivity.this,"El usuario presiono el fragmento",Toast.LENGTH_SHORT).show();
}
}
public class OneFragment extends Fragment {
public final static String ARG_NOMBRE = "arg_nombre";

private final View.OnClickListener tvOneFragOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if(mCallback!=null)
mCallback.onOneFragmentClick();
}
};

interface Callback{
void onOneFragmentClick();
}

private TextView tvOneFrag;
private Callback mCallback;

public void setCallback(Callback callback) {
mCallback = callback;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_one,container,false);

tvOneFrag = (TextView) view.findViewById(R.id.tvOneFrag);
tvOneFrag.setOnClickListener(tvOneFragOnClickListener);


Bundle args = getArguments();


tvOneFrag.setText(args.getString(ARG_NOMBRE));



return view;
}
}

Anonymous said...

Nice Example its really help me.

#Thankssss.....!!