Pass a Message From Thread to Update UI

19,149

Solution 1

Check out AsyncTask for this kind of stuff. It's really much more elegant than rolling your own handler and passing messages back and forth.

http://developer.android.com/reference/android/os/AsyncTask.html

Solution 2

It seems passing simple messages is int based... What I needed to do was pass a Bundle

using Message.setData(Bundle) and Message.getData(Bundle)

So Happy =0)

//Function From Within The Thread

public void newProjectCreation() {

Message msg =  new Message();
Bundle bundle = new Bundle();

bundle.putString("Test", "test value");
msg.setData(bundle);

handler2.sendMessage(msg);
}

//Handler in The UI Thread Retreieves The Data
//And Can Update the GUI as Required

private Handler handler2 = new Handler() {
    @Override
    public void handleMessage(Message msg) {

    Bundle bundle = msg.getData();
    Toast.makeText(New_Project.this,bundle.getString("Test"),Toast.LENGTH_SHORT).show();

}

};
Share:
19,149
Jay Dee
Author by

Jay Dee

Updated on June 11, 2022

Comments

  • Jay Dee
    Jay Dee almost 2 years

    Ive created a new thread for a file browser. The thread reads the contents of a directory. What I want to do is update the UI thread to draw a graphical representation of the files and folders. I know I can't update the UI from within a new thread so what I want to do is:

    whilst the file scanning thread iterates through a directories files and folders pass a file path string back to the UI thread. The handler in the UI thread then draws the graphical representation of the file passed back.

    public class New_Project extends Activity implements Runnable {
    
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.d("New Thread","Proccess Complete.");
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }
        };
    
    
        public void fileScanner(){
            //if (!XMLEFunctions.canReadExternal(this)) return;
            pd = ProgressDialog.show(this, "Reading Directory.",
                    "Please Wait...", true, false);
    
            Log.d("New Thread","Called");
            Thread thread = new Thread(this);
            thread.start();
        }
    
    
        public void run() {
            Log.d("New Thread","Reading Files");
            getFiles();
            handler.sendEmptyMessage(0);
        }
    
    
        public void getFiles() {
            for (int i=0;i<=allFiles.length-1;i++){
                //I WANT TO PASS THE FILE PATH BACK TU A HANDLER IN THE UI
                //SO IT CAN BE DRAWN.
                **passFilePathBackToBeDrawn(allFiles[i].toString());**
            } 
        }
    
    }