Question

Hi I have created a sample android project to learn how android can access the network task in background thread and how it will update UI thread. I have successfully done it in MainActivity.java

here is my code for MainActivity.java

package com.example.wcfconsumer;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.concurrent.ExecutionException;
import com.example.wcfconsumer.R;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private Button button;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                try {
                    getdata();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    private void getdata() throws InterruptedException, ExecutionException,
            MalformedURLException {
        String url = "GetNoPara";
        String toaststring = new String("");
        // AsyncTask<String, Integer, String> theString;
        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(url);
        toaststring = ((TextView) findViewById(R.id.text_wcfconsumer_response))
                .getText().toString();
        Toast.makeText(this, toaststring + "\n", Toast.LENGTH_LONG).show();

    }

    private class DownloadWebPageTask extends
            AsyncTask<String, Integer, String> {

        private final static String SERVICE_URI = "http://192.168.0.104:80/Service1.svc/";

        protected void onPostExecute(String result) {
            ((TextView) findViewById(R.id.text_wcfconsumer_response))
                    .setText(result);
        }

        @Override
        protected String doInBackground(String... params) {
            String response = "";
            HttpGet httpGet = new HttpGet(SERVICE_URI + params[0].toString());
            httpGet.setHeader("Accept", "application/json");
            httpGet.setHeader("Content-type", "application/json");
            DefaultHttpClient client = new DefaultHttpClient();
            // JSONArray jsaPersons = null ;
            // String theString = new String("");
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }
    }

}

but I was now trying to do it such a way so that I can call different different service methods and the background result will come back to UI thread where I can use result as per project requirement. I have thought to define this background task in different file(say BackgroundTask.java) but I don't know how to return result back to Main_Activity.java(from where BackgroundTask.execute is called)?

Please help me to it... Thanks for your response.

Regards, Sourabh

Was it helpful?

Solution

I have found the way to perform background task in non UI thread. for that you have to extends AsyncTask and have to implement doInBackground method. to know more on AsyncTask you can refer android developer website.

here is my code I have done with.

public class BackgroundTask extends AsyncTask<Object, Integer, String> {

    private final static String SERVICE_URI = "http://192.168.0.105:80/Service1.svc/";

    //runs after doInBackground completed
    protected void onPostExecute(String result) {
        Register_activity.emailV.setText(result);
    }

    @Override
    protected String doInBackground(Object... params) {
        Bitmap image = (Bitmap)params[1];
        String msg = new String();
        String methodname = params[0].toString();
         try {
                byte[] data = SaveImage.toByteArray(image);
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(SERVICE_URI+methodname);
                postRequest.setHeader("Content-type","application/octet-stream");
                ByteArrayBody bab = new ByteArrayBody(data, Register_activity.mobileV.getText().toString()+".jpg");
                // File file= new File("/mnt/sdcard/forest.png");
                // FileBody bin = new FileBody(file);
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("uploaded", bab);
                reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                System.out.println("Response: " + s);
                msg = s.toString();
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        return msg;
    }


}

here AsyncTask have 3 datatype :
Object represents the type of array data which will be passed to doInBackground method.
Integer represents the type of data which will be used to pass into onProgressUpdate Method.
String represents the type of data which will be used to pass into onPostExecute Method.

there are more options to perform tasks on NonUI thread like java thred. Options are yours.
Happy Coding...
Regards,
Sourabh

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top