Reputation: 171
I'm currently working toward a mobile android application. The main thing that this app will have trouble with for load times is a Webservice json string that at this current stage is taking too long to load and sometimes causing the app to force close (stalling for too long).
Splash -> MainActivity -> HomeActivity This is how our application starts.
First we display a Splash, and behind that we run the MainActivity, which consists of the following code:
public class HomeActivity : Activity
{
NewsObject[] news;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
var request = HttpWebRequest.Create(string.Format(@"http://rapstation.com/webservice.php"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if(string.IsNullOrWhiteSpace(content)) {
Console.Out.WriteLine("Response contained empty body...");
Toast toast = Toast.MakeText (this, "No Connection to server, Application will now close", ToastLength.Short);
toast.Show ();
}
else {
news = JsonConvert.DeserializeObject<NewsObject[]>(content);
}
}
Console.Out.WriteLine ("Now: \r\n {0}", news[0].title);
}
var list = FindViewById<ListView> (Resource.Id.list);
list.Adapter = new HomeScreenAdapter (this, news);
list.ItemClick += OnListItemClick;
var Listen = FindViewById<Button> (Resource.Id.btnListen);
var Shows = FindViewById<Button> (Resource.Id.btnShows);
Listen.Click += (sender, e) => {
var second = new Intent (this, typeof(RadioActivity));
StartActivity (second);
};
Shows.Click += (sender, e) => {
var second = new Intent (this, typeof(ShowsActivity));
StartActivity (second);
};
}
protected void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
var listView = sender as ListView;
var t = news[e.Position];
var second = new Intent (this, typeof(NewsActivity));
second.PutExtra ("newsTitle", t.title);
second.PutExtra ("newsBody", t.body);
second.PutExtra ("newsImage", t.image);
second.PutExtra ("newsCaption", t.caption);
StartActivity (second);
Console.WriteLine("Clicked on " + t.title);
}
}
The problem I am running into is the app will stick on the Splash page and the Application output will tell me that I am running too much on the Main thread.
What is a way to separate the download request to work in the background?
Upvotes: 2
Views: 296
Reputation: 35363
If the .Net/Mono version you're using supports async/await then you can simply do
async void DisplayNews()
{
string url = "http://rapstation.com/webservice.php";
HttpClient client = new HttpClient();
string content = await client.GetStringAsync(url);
NewsObject[] news = JsonConvert.DeserializeObject<NewsObject[]>(content);
//!! Your code to add news to some control
}
if Not, then you can use Task's
void DisplayNews2()
{
string url = "http://rapstation.com/webservice.php";
Task.Factory.StartNew(() =>
{
using (var client = new WebClient())
{
string content = client.DownloadString(url);
return JsonConvert.DeserializeObject<NewsObject[]>(content);
}
})
.ContinueWith((task,y) =>
{
NewsObject[] news = task.Result;
//!! Your code to add news to some control
},null,TaskScheduler.FromCurrentSynchronizationContext());
}
Upvotes: 0
Reputation: 4187
private class myTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
// Runs on the background thread
return null;
}
@Override
protected void onPostExecute(Void res) {
}
}
and to run it
new myTask().execute();
Upvotes: 6