Arun Kumar
Arun Kumar

Reputation: 877

Falied to assign value to textview in a thread class

I have a textview in one of the page named txtdownloadStatus.I have thread class that downloads some data and if completed i want to show completed in the textview that is placed in the page i told earilier.

My user interface name is

download_manifest.txtdownloadStatus.setText("Completed Download");

The thread class is as given below

public class thread_download extends Thread {
    private download_helper downloadhelper;
    private Context context;
    public thread_download(Context context) {
        this.context = context;
    }
     public void run() {

           downloadhelper = new download_helper(this.context);

            try {
                downloadhelper.DownloadProblemAndReasonCode();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                downloadhelper.DownloadNewManifest();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                downloadhelper.DownloadNewMessages();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            downloadhelper.DeleteOldManifest();
            try {
            download_manifest.txtdownloadStatus.setText("Cpmpleted");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

}

The problem is that when i tried to set value to the textview in the thread class.It shows an error like given below

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Will anyone help me

Upvotes: 0

Views: 64

Answers (3)

MByD
MByD

Reputation: 137282

You cannot modify the UI from a thread other than the UI thread. You should use a Handler, AsyncTask, or runOnUiThread to modify the UI.

Upvotes: 1

Yashwanth Kumar
Yashwanth Kumar

Reputation: 29121

you have to run it on UIthread. as the error says any operation on the UI elements have to performed in the UIthread.

you have to use runOnUIThread() method.

Use AsyncTask , it creates a separate thread automatically for you and postExecute and preExecute methods of it run on UI thread . you don't have to do anything complex, if you use asyncTask, it was designed for this purposes i think.

Upvotes: 1

blessanm86
blessanm86

Reputation: 31779

In android all the UI stuff should be done on the UI thread. You can either use the runOnUIThread method or when you are done processing in the background thread, use a handler to update the textview. Your error will be fixed.

Upvotes: 0

Related Questions