简体   繁体   中英

How to transfer the value of the string from thread to another?

I am using Jsoup to parse a part of a website and then put it into a string. I want to visualize this string into a textView, but since only the thread that had created the textView can modify it i need to pass the value of the string into the main thread. how?

This is the code: (ignore the tabhost stuff)

public class NewsAndAnnouncements extends Activity {

    TabHost host;
    FlyOutContainer container;
    Button bttoggle;
    Button bt1;
    String loggity;
    TextView tv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.container = (FlyOutContainer) this.getLayoutInflater().inflate(
                R.layout.newsandannouncements, null);
        this.setContentView(container);

        host = (TabHost) findViewById(R.id.tabhost);
        host.setup();

        TabSpec specs = host.newTabSpec("TAGGITY EINZ");
        specs.setContent(R.id.tab1);
        specs.setIndicator("News");
        host.addTab(specs);

        specs = host.newTabSpec("TAGGITY ZWEI");
        specs.setContent(R.id.tab2);
        specs.setIndicator("Notices");
        host.addTab(specs);

        specs = host.newTabSpec("TAGGITY DREI");
        specs.setContent(R.id.tab3);
        specs.setIndicator("Events");
        host.addTab(specs);

        tv1 = (TextView) findViewById(R.id.textView1);

        /*
         * bttoggle = (Button) findViewById(R.id.bttoggle); bt1 = (Button)
         * findViewById(R.id.Button1);
         * 
         * bttoggle.setOnClickListener(new OnClickListener() {
         * 
         * @Override public void onClick(View v) { // TODO Auto-generated method
         * container.toggleMenu(); } });
         * 
         * bt1.setOnClickListener(new OnClickListener() {
         * 
         * @Override public void onClick(View v) { // TODO Auto-generated method
         * container.toggleMenu(); } });
         */

        Thread newsThread = new Thread() { 
            public void run() {

                Document doc = null;
                try {
                    doc = Jsoup
                            .connect(
                                    "http://acs.bg/Home/About_ACS/News_and_Events/News.aspx")
                            .get();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Elements myin = doc.getElementsByClass("news_list");
                loggity = myin.toString();


                        Log.i("ELEMENTS HTML", loggity);

            }
        };
        newsThread.start();

        tv1.setText(loggity);

    }

}

Try using AsyncTask instead of the Thread. To modify views on your ui thread use the runOnUiThread() method in your activity.

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        tv1.setText("...");
    }
});

Use an AsyncTask instead of a raw Thread:

new AsyncTask<URL, Object, Document>() {
    protected Document doInBackground(URL... urls) {
        // parse URL and return document
    }

    protected void onPostExecute(Document result) {
        // this runs in UI thread
        // show document in UI
    }
}).execute(myURL);

There are two ways to d it-

1)- Using AsyncTask

2)- Using Handler

Thread newsThread = new Thread() 
{ 
            public void run() 
            {
                Document doc = null;
                try {
                    doc = Jsoup
                            .connect(
                                    "http://acs.bg/Home/About_ACS/News_and_Events/News.aspx")
                            .get();
                } 
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Elements myin = doc.getElementsByClass("news_list");
                loggity = myin.toString();

                mHandler.post(new Runnable() 
                {
                    @Override
                    public void run() 
                    {
                            try 
                            {
                                    tv1.setText(loggity);
                            } catch (Exception e) 
                            {
                                    e.printStackTrace();
                            }
                    }
            });
            Log.i("ELEMENTS HTML", loggity);
            }
        };
        newsThread.start();

You can initialize the Hanlder in the start.

try this sample code, don't know if this is the better way:

public class MainThread {


public static void main(String args[]) {
    Thread2 t2 = new Thread2();
    Thread nextThread = new Thread(t2);
    nextThread.start();

    try {
        nextThread.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println();
    System.out.println(t2.getStr());

}

private static class Thread2 implements Runnable{
    private String str;

    @Override
    public void run() {
        setStr("T2 Thread String");

    }
    public String getStr() {
        return str;
    }
    public void setStr(String str) {
        this.str = str;
    }

}


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM