Skip to content

Instantly share code, notes, and snippets.

@rameshvoltella
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rameshvoltella/cdbae1318c3327692fe9 to your computer and use it in GitHub Desktop.
Save rameshvoltella/cdbae1318c3327692fe9 to your computer and use it in GitHub Desktop.
Working of interface for beginners Android
public class AsyncHttp extends AsyncTask<String, String, String> {
CallbackToActivity mCallback;//Interface class for callback
public AsyncHttp(CallbackToActivity mCallback) {
this.mCallback = mCallback;
}
@Override
protected String doInBackground(String... params) {
return null;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
//After the task ends we can call the interface and pass the ststus to the target class
mCallback.mStatus(true,,"TaskOver");
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
//Interface class handling the status transfer
public interface CallbackToActivity {
public void mStatus(boolean status,String message);
/*You can add more than one method as your need with more than one arguments*/
}
// implement the interface class to your activity class or fragamet class where you need to get the call back after the async task
//in the example am usng a activitycalss
public class ClassName extends Activity implements CallbackToActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
AsyncHttp mAsyncHttp=new AsyncHttp(ClassName.this);//You sould implement CallbackToActivity othere wise this methord will show error
mAsyncHttp..execute();
}
//override methord comes when we implement the CallbackToActivity.class
@Override
public void mStatus(boolean status,String message) {
//This methord execute only when user gives a call back from the Asyc Task AsyncHttp.java (in this example)
Log.d("Message", "" + message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment