Issue
I want to run a block of code similar to the following code. The purpose of the code is to make an HTTP request at a one-second period without blocking the UI thread.
private void GetCodeFromTheServer()
{
WebClient client = new WebClient();
string code = client.DownloadString(new Uri(@"http://example.com/code"));
Toast.MakeText(this, "Code: " + code, ToastLength.Long).Show();
}
Solution
You will not be able make a call to web on Activity main thread. Use Async Task to execute your code. The Async Task will run in background and when the content is downloaded will show Toast for you. The sample below will help.
private class GetStringTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String str = "...";
/** String From Web **/
return str;
}
@Override
protected void onPostExecute(String address) {
// Show Toast Here
}
}
Answered By - Ashu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.