Android : Passing value from helper thread to main thread

on Tuesday, October 28, 2014


I have a thread with a try-catch block. Inside the try block I have the HTML stored in a variable which I want to load into a webview. Now Android/Java doesn't allow Webview to be called any other place apart from main thread.


How can I pass this String variable value outside the scope of thread? Making string variable final and declaring outside thread doesn't help.



public class MyCustomView extends LinearLayout {
//UI elements
private WebView mWebView;


new Thread(new Runnable() {

@Override
public void run() {
try {

//Using thread because accessing network
URL obj = new URL(adrequesturl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");


if (con.getResponseCode() == 200) {

//*****Need this variable's value in the Main Thread
String dataToLoad="some_custom_html";


//mWebView is a webview that I have created and below can not get executed from inside helper thread
//mWebView.loadData(dataToLoad, "text/html", "utf-8");-

} else {
//Some code
}

} catch (Exception e) {
//Some code
}
}

}).start();


//Now we are back to main thread

//********Main Problem**************
//Below mWebView.loadData is allowed but I can not get dataToLoad value here
mWebView.loadData(dataToLoad, "text/html", "utf-8");

}

0 comments:

Post a Comment