I have a map that i want to update from a separate thread. Im having some issues when i try to update the UI from my class that extends asynctask. And when i move the code to a handler in the main thread i get NetworkOnMainThreadException. Below is my asynctask. Is there any way to modify it to make it work?
@Override
protected Integer doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://83.xx.xx:8080/android/service.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "getusers"));
nameValuePairs.add(new BasicNameValuePair("interval", Integer.toString(interval)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String jsonString = EntityUtils.toString(response.getEntity());
Gson gson = new GsonBuilder().create();
Type listType = new TypeToken<ArrayList<User>>() {}.getType();
ArrayList<User> userList = gson.fromJson(jsonString, listType);
((GoogleMapsActivity) activity).removeOverlayItems();
for(User user : userList ){
((GoogleMapsActivity) activity).addOverlayItem(Double.parseDouble(user.last_lat), Double.parseDouble(user.last_lng), user.bluetooth_name, "test desc");
}
return 1;
} catch (Exception e) {
e.printStackTrace();
}
return null;
Rather than touching the map in your doInBackground, return your data into onPostExecute. Then update the map from onPostExecute.
Please note that you should never retain a reference to your Activity from inside your AsyncTask or you could cause a memory leak.
Ideally, you should create an observer that can return data to your Activity.
Then, you instantiate your AsyncTask with a reference to this observer.
Just make sure you call onActivityDestroyed() from your activity’s onDestroy method. Otherwise your Activity will leak.