-3

**Edit : solved **

I am testing sample code on AsyncTask functionality . But the dobackGround() Method is not calling the Code . I took the Help of some of the posts and Refactor my code , But still it is not working

this is Main Layout

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1">
    </EditText>

    <Button
        android:text="Get Name"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>

    <TextView
        android:text="from Web service"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

MainActivity.java

public class MainActivity  extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}

WebServiceActivity.java

public class WebServiceActivity extends Activity implements View.OnClickListener {

    Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.button1:
                new LongOperation().execute("");
                break;
        }
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.textView1);
            txt.setText("Executed"); // txt.setText(result);

        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}

WebServiceActivity containts Inner Class LongOperation which extends AsyncTask . Is it my layout not correctly bind ?

Need some suggestion

Neeraj Verma
  • 2,174
  • 6
  • 30
  • 51
  • The link below can be useful: http://stackoverflow.com/questions/9671546/asynctask-android-example – Dhruvi Jul 06 '16 at 05:04

4 Answers4

1

Should I need to Move the Entire View to Async Task ? I am not able to find relevant post

=> No you should not move entire things to AsyncTask. First understand the purpose of four different methods of AsyncTask and move your things accordingly.

  • onPreExecute() - Something that you want to prepare before execution begins. For example, display progress bar or dialog
  • doInBackground() - Write down long running operations in this method like making a web API call
  • onProgressUpdate() - You can push partial update to UI from this method. For example 1/10 kind of output in progress bar
  • onPostExecute() - UI update or any other operations which you want to perform post execution of long running operations i.e. web API call

Some other points:

  • These days AsyncTask is not being used that much but some other approach.

  • There are some third party and best libraries available which would help you in implementing long running task. Example libraries are Retrofit, OkHttp

  • Currently developers have started using Reactive approach and so using RxJava, RxAndroid libraries.

Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
1

I think you need an example of AsyncTask , So here it is .This is an example of loginTask using AsyncTask . Hope it will Help you...

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;

/**
  * Created by jatin khattar on 01-10-2015.
 */
public class LoginTask extends AsyncTask<String, Integer, String> {


Context context;
User user;
private ConnectivityManager conMgr;
private Resources r;
private ProgressDialog dialog;
private Session session;


private final static String API_PARAM_TYPE="type";
private final static String API_PARAM_EMAIL="email";
private final static String API_PARAM_PASSWORD="password";



public LoginTask(Context context, User user, ConnectivityManager conMgr){
    this.context = context;
    this.user = user;
    this.conMgr = conMgr;
    r=context.getResources();
    session=new Session(context);
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog=ProgressDialog.show(context, r.getString(R.string.progress_message), "Please Wait");
}

@Override
protected String doInBackground(String... params) {
    API api=new API(this.context, conMgr);
    api.setAPI("user");
    api.setAction("login");
    api.setParam(API_PARAM_TYPE, "general");
    api.setParam(API_PARAM_EMAIL, user.email);
    api.setParam(API_PARAM_PASSWORD, user.pass);
    String result=api.process();
    Log.d("API Response", result);
    return result;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    dialog.dismiss();
    try {
        JSONObject res=new JSONObject(result);
        if(res.getBoolean("success")){
            session.CreateSession(res.getInt("id"), res.getString("name"), res.getString("auth_key"), res.getString("email"));
            Toast.makeText(this.context, "Logged in Successfully", Toast.LENGTH_LONG).show();
            Intent intnt = new Intent(context, MainActivity.class);
            intnt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(intnt);
        }else{
            if(res.has("message")){
                Toast.makeText(this.context, res.getString("message"), Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this.context, r.getString(R.string.error_message_unknown), Toast.LENGTH_SHORT).show();
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this.context, r.getString(R.string.error_invalid_response_message), Toast.LENGTH_SHORT).show();
    }

}

}
0

You no need to put entire code inside asynctask, you have to put the network operation code inside doInBackground() of asynctask.

public class MainActivity extends Activity
{
    /**
     * Called when the activity is first created.
     */
    private static final String SOAP_ACTION ="http://tempuri.org/HelloWorld";

    private static final String OPERATION_NAME = "findContact";

    private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

    private static final String SOAP_ADDRESS = "http://10.0.2.2:31736/WebSite3/Service.asmx";
    TextView tvData1;
    EditText edata;
    Button button;
    String studentNo;


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

        tvData1 = (TextView) findViewById(R.id.textView1);
        button = (Button) findViewById(R.id.button1);
        edata = (EditText) findViewById(R.id.editText1);

        button.setOnClickListener(new OnClickListener()
        {

            public void onClick(View v)
            {
                studentNo = edata.getText().toString();

                new BackgroundTask().execute();
            }
        });

    }


    class BackgroundTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
            PropertyInfo propertyInfo = new PropertyInfo();
            propertyInfo.type = PropertyInfo.STRING_CLASS;
            propertyInfo.name = "eid";

            request.addProperty(propertyInfo, studentNo);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);

            HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

            try
            {
                httpTransport.call(SOAP_ACTION, envelope);
                Object response = envelope.getResponse();
                return response.toString();
            } catch (Exception exception)
            {
                return exception.toString() + "  Or enter number is not Available!";
            }
        }

        @Override
        protected void onPostExecute(String s)
        {
            tvData1.setText(s);
        }
    }

}
Kumar M
  • 994
  • 6
  • 21
0

ok , I figure out the Code .. this is my working Code of Asyntask . Only one Main Class and one Inner class is needed

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText1">
    </EditText>

    <Button
        android:text="Get Name"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Button>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>

    </LinearLayout>

MainActivity.java

public class MainActivity  extends Activity
{

TextView tvData1;
EditText edata;
Button button;

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

    tvData1 = (TextView)findViewById(R.id.textView1);


    button=(Button)findViewById(R.id.button1);

    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            new LongOperation().execute("");

        }
    });
}


private class LongOperation extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.interrupted();
            }
        }
        return "executed";
    }

    @Override
    protected void onPostExecute(String result) {
        tvData1.setText(result);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}
}
Neeraj Verma
  • 2,174
  • 6
  • 30
  • 51