user742030
user742030

Reputation:

How do I add a Thread?

This is continuing from this post's Question.

I cannot figure how to add a separate thread from the main UI thread to do work of gathering data from the server. I have never done threads before and I think this instance in my constructed class makes it a little more advanced then any of the examples I can find.

Any help and a posted revision of my class would be appreciated.

Thank_you!

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getIntent().getExtras();
        setContentView(R.layout.list_view2);

        /**
         * Get the query string from last activity and pass it to this
         * activity-----------------------------------------------------
         */
        String p = null;
        if (extras != null) {
            p = extras.getString(PHP_KEY);          
        }
        loadQuery(p);
    }

    void loadQuery(String p) {

        String qO = getIntent().getStringExtra("QUERY_ORDER");

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // http post
        try {

             HttpClient httpclient = new DefaultHttpClient();
             HttpPost httppost = new HttpPost("http://10.0.2.2/App/php/" +
             p + qO + ".php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();
            result = sb.toString();

        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        setListAdapter(new QueryAdapter(this, result));
    }

See my answer below

Upvotes: 3

Views: 604

Answers (4)

user742030
user742030

Reputation:

....loadQuery();
    }

    void loadQuery() {

        new Thread(new Runnable() {

            public void run() {

                String qO = getIntent().getStringExtra("QUERY_ORDER");
                String php = getIntent().getStringExtra("PHP_KEY");

                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                // http post
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            "http://10.0.2.2/Andaero/php/" + php + qO + ".php");

                    Log.e("log_tag", "Fetched " + php + qO + ".php");

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();

                } catch (Exception e) {

                    Log.e("log_tag", "Error in http connection " + e.toString());
                }

                // convert response to string
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(is, "iso-8859-1"), 8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");

                    String line = "0";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }

                    is.close();
                    result = sb.toString();

                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result " + e.toString());
                }

            }

        }).start();
    }

Upvotes: 1

ahodder
ahodder

Reputation: 11439

I would use an extension of the AsyncTask. Here is a sample:

public TestSync extends AsyncTask<Void, Integer, Integer> {
    TextView mTv = null;
    String mURL;
    public TestSync(TextView tv, String url) {
        mTv = tv;
        mURL = url;
    }

    @Override public Void doInBackground(Void... voids) {
        int count = 0;
        URL url = null;
        BufferedReader br = null;
        try {
            url = new URL(mURL);
            br = new BufferedReader(new InputStreamReader(url.openStream));
            String log = null;

            while ((log = br.readLine()) != null) {
                Log.d("Testo", log);
                count++;
                publishProgress(new int[] {count});
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) 
                    is.close();
            } catch (Exception e) { /* eat*/ }
        }

        return count;
    }

    @Override public void onProgressUpdate(Integer... vals) {
        mTv.setText(vals[0]);
    }

    @Override public void onPostExecute(Integer inte) {
        Toast.makeText(context, "We read " + inte + " lines from the url.", Toast.LENGTH_LONG).show();
    }
}

Upvotes: 2

dmon
dmon

Reputation: 30168

Use AsyncTasks, Luke.

Upvotes: 3

coder_For_Life22
coder_For_Life22

Reputation: 26971

You should simply use an AsyncTask

Here is a good tutorial on how to use itTutorial

Here is an example of downloading a webpage and returning the results to the main UI.

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            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;
    }

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

Upvotes: 7

Related Questions