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 textVie
Solution 1:
Try using AsyncTask instead of the Thread. To modify views on your ui thread use the runOnUiThread() method in your activity.
runOnUiThread(newRunnable() {
@Overridepublicvoidrun() {
tv1.setText("...");
}
});
Solution 2:
Use an AsyncTask instead of a raw Thread:
newAsyncTask<URL, Object, Document>() {
protectedDocumentdoInBackground(URL... urls) {
// parse URL and return document
}
protectedvoidonPostExecute(Document result) {
// this runs in UI thread// show document in UI
}
}).execute(myURL);
Solution 3:
There are two ways to d it-
1)- Using AsyncTask
2)- Using Handler
ThreadnewsThread=newThread()
{
publicvoidrun()
{
Documentdoc=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();
}
Elementsmyin= doc.getElementsByClass("news_list");
loggity = myin.toString();
mHandler.post(newRunnable()
{
@Overridepublicvoidrun()
{
try
{
tv1.setText(loggity);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
Log.i("ELEMENTS HTML", loggity);
}
};
newsThread.start();
You can initialize the Hanlder in the start.
Solution 4:
try this sample code, don't know if this is the better way:
publicclassMainThread {
publicstaticvoidmain(String args[]) {
Thread2 t2 = newThread2();
Thread nextThread = newThread(t2);
nextThread.start();
try {
nextThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println();
System.out.println(t2.getStr());
}
privatestaticclassThread2implementsRunnable{
privateString str;
@Overridepublicvoidrun() {
setStr("T2 Thread String");
}
publicStringgetStr() {
return str;
}
publicvoidsetStr(String str) {
this.str = str;
}
}
}
Post a Comment for "How To Transfer The Value Of The String From Thread To Another?"