Skip to main content

Tutorial :- How to implement reusable Asyntask in android

How to implement reusable Asyntask in Android  :-
What is AsyncTask?  
Answer :-
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

/**
 * Activites that wish to be notified about results
 * in onPostExecute of an AsyncTask must implement
 * this interface.
 *
 * This is the basic Observer pattern.
 */
public interface ResultsListener {
    public void onResultsSucceeded(String result);
}

package com.example;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;

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

    ResultsListener listener;

    private static final String SOAP_ACTION = "http://tempuri.org/name";
    private static final String METHOD_NAME = "name";
    private static final String NAMESPACE = "http://tempuri.org/";
    public static String URL = "url";
    private SoapPrimitive resultsRequestSOAP = null;

    public void setOnResultsListener(ResultsListener listener) {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(Void... voids) {
        String someString = "foo bar";
        String results = null;
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        // SoapObject
        request.addProperty("address", "shivaji nagar pune");
        request.addProperty("mile", "20");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            results = resultsRequestSOAP.toString();
        } catch (SoapFault e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return results;

    }

    @Override
    protected void onPostExecute(String result) {
        listener.onResultsSucceeded(result);

    }

}

MyAsyncTask task = new MyAsyncTask();
        /**
         * Set this Activity as the listener on the AsyncTask. The AsyncTask
         * will now have a refence to this Activity and will call
         * onResultsSucceeded() in its onPostExecute method.
         */
        task.setOnResultsListener(this);
                       

Comments

Popular posts from this blog

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *     ...

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {        ...

Get Android phone call history/log programmatically

Get Android phone call history/log programmatically To get call history programmatically first add read conact permission in Manifest file : <uses-permission android:name="android.permission.READ_CONTACTS" /> Create xml file. Add the below code in xml file : <Linearlayout android:layout_height="fill_parent"  android:layout_width="fill_parent" android:orientation="vertical"> <Textview android:id="@+id/call" android:layout_height="fill_parent" android:layout_width="fill_parent"> </Textview> </Linearlayout> Now call the getCallDetails() method in java class : private void getCallDetails() { StringBuffer sb = new StringBuffer(); Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null); int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE ); int date = managedCur...