当我尝试连接到互联网时出现 android.os.NetworkOnMainThreadException 错误。我知道更高版本的 android(从 HoneyComb 开始)不允许您在 UI 线程上执行网络 IO,这就是我的原因在代码上使用 AsyncTask.no 错误但是当它运行时,我得到 android.os.NetworkOnMainThreadException 错误 代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
new GetProductDetails().execute();
}
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
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("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
txtName = (EditText) findViewById(R.id.inputName);
txtPrice = (EditText) findViewById(R.id.inputPrice);
txtDesc = (EditText) findViewById(R.id.inputDesc);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
我已经读到一个可能的解决方案是使用 StrictMode 策略,但我有点不愿意使用它,因为它只推荐在开发环境中使用。这里有什么问题?
最佳答案
What's the problem here?
您正在主应用程序线程上执行网络 I/O,从您使用 runOnUiThread()
的 Runnable
内部。
去掉 runOnUiThread()
和 Runnable
。将网络代码放在 doInBackground()
中。在 onPostExecute()
中更新您的小部件。您通过 doInBackground()
的返回值将数据从 doInBackground()
传递到 onPostExecute()
(它成为传递给 onPostExecute()
) 或 AsyncTask
本身内部的数据成员。
关于java - 即使在 AsyncTask 中运行时也出现 android.os.NetworkOnMainThreadException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221097/