-2

In my application i am running a thread in which some text file operations are performed .During this period i also want to keep updating the results on the UI using setText. Please suggest a way.

testThread = new Thread(){
          public void run()
          {
            Log.i("TestApp","Test Thread Running");
            runTest();

          }

        };

As i understand , it is not good to perform time consuming operations on the UI thread to avoid ANR. Please suggest a way where i can do both at the same time.

4 Answers4

1

Instead of using use AsyncTask, it will be better, here is one sample

class GetStuffAsyncly extends AsyncTask<String, String, String> {
   //What ever variables, you needed



    @Override
    protected String doInBackground(String... args) {
        // do stuff in background...
        //When you want to update something in the middle use the below method
        publishProgress(Value);    
        return args[0];
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String jsonString) {
       //Here the thread execution ends.

    }
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
       //Here you will get the value what you want to update while running the thread.
    }
}

and to run this you can use

new GetStuffAsyncly().execute();
Nigam Patro
  • 2,760
  • 1
  • 18
  • 33
1

Try this:

  private void runThread() {

    new Thread() {
        public void run() {
            while (i++ < 1000) {
                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                           //Do something on your UI
                        }
                    });
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}
Jas
  • 3,207
  • 2
  • 15
  • 45
0

There are several ways. One common pattern is to use AsyncTask, but if you need to do several intermediate progress updates, AsyncTask is mostly suitable if each step is similar (such as downloading a file and updating the UI accordingly for every x kB downloaded). But for many many cases this will be fine.

If your task is more complex than that, constisting of several completely different steps, each one requiring the UI to be changed in some way, you may either divide your task into several AsyncTasks, or simply spawn a worker thread and use a Handler (created in the UI thread before the task starts) to post Runnables with whatever code you need to run in the UI thread.

final Handler handler = new Handler();
new Thread() {
  public void run() {

    // do time-consuming step 1

    handler.post(new Runnable() {
      public void run() {
        // update UI after step 1
      }
    });

    // do time-consuming step 2

    handler.post(new Runnable() {
      public void run() {
        // update UI after step 2
      }
    });

    // do time-consuming step 3

    handler.post(new Runnable() {
      public void run() {
        // update UI after step 3
      }
    });

  }
}.start();

Really, it's up to the level of control you need whether AsyncTask fits your needs or not.

JHH
  • 8,567
  • 8
  • 47
  • 91
0
     Thread background = new Thread(new Runnable() {

                private final HttpClient Client = new DefaultHttpClient();
                private String URL = "http://blahblahxxx.com/media/webservice/getPage.php";

                // After call for background.start this run method call
                public void run() {
                    try {

                        String SetServerString = "";
                        HttpGet httpget = new HttpGet(URL);
                        ResponseHandler<String> responseHandler = new BasicResponseHandler();
                        SetServerString = Client.execute(httpget, responseHandler);
                        threadMsg(SetServerString);

                    } catch (Throwable t) {
                        // just end the background thread
                        Log.i("Animation", "Thread  exception " + t);
                    }
                }

                private void threadMsg(String msg) {

                    if (!msg.equals(null) && !msg.equals("")) {
                        Message msgObj = handler.obtainMessage();
                        Bundle b = new Bundle();
                        b.putString("message", msg);
                        msgObj.setData(b);
                        handler.sendMessage(msgObj);
                    }
                }

                // Define the Handler that receives messages from the thread and update the progress
                private final Handler handler = new Handler() {

                    public void handleMessage(Message msg) {

                        String aResponse = msg.getData().getString("message");

                        if ((null != aResponse)) {

                            // ALERT MESSAGE
                            Toast.makeText(
                                    getBaseContext(),
                                    "Server Response: "+aResponse,
                                    Toast.LENGTH_SHORT).show();
                        }
                        else
                        {

                                // ALERT MESSAGE
                                Toast.makeText(
                                        getBaseContext(),
                                        "Not Got Response From Server.",
                                        Toast.LENGTH_SHORT).show();
                        }    

                    }
                };

            });
            // Start Thread
            background.start();  //After call start method thread called run Method
Zin Win Htet
  • 2,448
  • 4
  • 32
  • 54