Issue
I want to grab some data from remote database and I have some networking in my AsyncTask subclass of my activity, but when I try to load my program it shows NetworkOnMainThreadException.
here is my code:
public class MyMapLocationActivity extends MapActivity {
private MapView mapView;
private static String url_product_details = "http://myurl.com/readfromdb";
private static final String TAG_SUCCESS = "success";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
private static final String TAG_POINT = "point";
JSONParser jsonParser = new JSONParser();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
ReadLocations Read = new ReadLocations();
Read.execute();
}
//And my networking AsyncTask:
class ReadLocations extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
Log.d("debug", "START DOINBACKGROUND");
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "16"));
// getting product details by making HTTP request
// Note that product details url will use GET request
Log.d("debug", "before http request");
JSONObject json = jsonParser.makeHttpRequest(
url_product_details, "POST", params);
Log.d("debug", "after http request");
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_POINT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
@Override
protected void onPostExecute(String text) {
// dismiss the dialog once done
Log.d("debug", "ONPOSTEXECUTE");
}
The LogCat shows "before http request" but doesn't show my "after http request" check.
What is wrong?
Solution
Your Network code is on MainUiThread of Application not in worker thread...
remove
runOnUiThread(new Runnable() {
public void run() {
from doInBackground()
and put the WebRequest code only in doInBackground()
of AsyncTask..
Update:
Actually your AsyncTask implementation for doInBackground()
is wrong. As doInBackground()
runs in worker thread for lengthy and network related operation. And you are trying to run MainUiThread form it using runOnUiThread()
which is not in rule.. If you want to make any UI related work do it in onPostExecute()
, onPreExecute()
and other methods of ASyncTask.
Answered By - user370305
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.