how can i run Webservice code in Thread?

53 views Asked by At

I wanna get some data from server with this code :

public class Webservice {

    public static String readUrl(String url, ArrayList<NameValuePair> params) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost method = new HttpPost(url);

            if (params != null) {
                method.setEntity(new UrlEncodedFormEntity(params));
            }

            HttpResponse response = client.execute(method);

            InputStream inputStream = response.getEntity().getContent();
            String result = convertInputStreamToString(inputStream);

            return result;
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    private static String convertInputStreamToString(InputStream inputStream) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder builder = new StringBuilder();

            String line = "";

            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            return builder.toString();
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

but there is some delay and pause in the application , so i wanna run this code in the Thread , but when i tried to do it , i got some error , for example i couldn't return the result or ...

1

There are 1 answers

1
Sergey Maksimenko On

Take a look at AsyncTask:

Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post Multithreading For Performance.

In the following snippet, the myClickHandler() method invokes new DownloadWebpageTask().execute(stringUrl). The DownloadWebpageTask class is a subclass of AsyncTask.

public class HttpExampleActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);   
    urlText = (EditText) findViewById(R.id.myUrl);
    textView = (TextView) findViewById(R.id.myText);
}

// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
public void myClickHandler(View view) {
    // Gets the URL from the UI's text field.
    String stringUrl = urlText.getText().toString();
    ConnectivityManager connMgr = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        new DownloadWebpageTask().execute(stringUrl);
    } else {
        textView.setText("No network connection available.");
    }
}

 // Uses AsyncTask to create a task away from the main UI thread. This task takes a 
 // URL string and uses it to create an HttpUrlConnection. Once the connection
 // has been established, the AsyncTask downloads the contents of the webpage as
 // an InputStream. Finally, the InputStream is converted into a string, which is
 // displayed in the UI by the AsyncTask's onPostExecute method.
 private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        textView.setText(result);
   }
}
... }