[英]Android:NetworkOnMainThreadException error inside AsyncTask
好的,所以我創建了一個內部類,該類擴展了AsycTask,以便我的代碼與UI線程一起運行。 但是我收到此錯誤,所以我認為這意味着我的onPostExecute的某些部分需要在doInBackground中完成,但是我無法弄清楚這到底是什么
public class asyncTask extends AsyncTask<String, Integer, String> {
ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);
@Override
protected void onPreExecute() {
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.setMessage("loading...");
dialog.show();
}
@Override
protected String doInBackground(String...parmans){
{
for(int i = 0; i < 100; i++){
publishProgress(1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String urlString = petrolPriceURL;
String result = "";
InputStream anInStream = null;
int response = -1;
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
return null;
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
// Check that the connection can be opened
if (!(conn instanceof HttpURLConnection))
try {
throw new IOException("Not an HTTP connection");
} catch (IOException e) {
// TODO Auto-generated catch block
return null;
}
try
{
// Open connection
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
// Check that connection is OK
if (response == HttpURLConnection.HTTP_OK)
{
// Connection is OK so open a reader
anInStream = httpConn.getInputStream();
InputStreamReader in= new InputStreamReader(anInStream);
BufferedReader bin= new BufferedReader(in);
// Read in the data from the RSS stream
String line = new String();
while (( (line = bin.readLine())) != null)
{
result = result + "\n" + line;
}
}
}
catch (IOException ex)
{
try {
throw new IOException("Error connecting");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
}
@Override
protected void onProgressUpdate(Integer...progress){
dialog.incrementProgressBy(progress[0]);
}
@Override
protected void onPostExecute(String result) {
// Get the data from the RSS stream as a string
errorText = (TextView)findViewById(R.id.error);
response = (TextView)findViewById(R.id.title);
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
catch(Exception ae)
{
// Handle error
errorText.setText("Error");
// Add error info to log for diagnostics
errorText.setText(ae.toString());
}
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
}
如果有人可以指出我的錯誤以及顯示代碼應該放在doInBackground中的示例,那將很棒。 謝謝
問題:
result = doInBackground(petrolPriceURL);
你是隱式調用doInbackground
的方法onPostExecute
這將在實際UI線程,而不是在不同的線程從而導致運行Android:NetworkOnMainThreadException
。
此外,它不需要調用doInBackground
它之前已經執行onPostExecute
當您執行Asynctask
。 只需直接使用result
的參數onPostExecute
。
樣品:
@Override
protected void onPostExecute(String result) {
// Get the data from the RSS stream as a string
errorText = (TextView)findViewById(R.id.error);
response = (TextView)findViewById(R.id.title);
response.setText(result);
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
我懷疑該錯誤與您的代碼的這一部分有關:
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
當您調用asynctask.execute時,會自動調用doInBackgound。 要正確啟動任務,您應該(1)創建任務的新實例; (2)在execute方法中的doInBackground中傳遞您需要使用的字符串參數; (3)使用它們; (4)將結果返回給onPostExecute。
例如:
//in your activity or fragment
MyTask postTask = new MyTask();
postTask.execute(value1, value2, value3);
//in your async task
@Override
protected String doInBackground(String... params){
//extract values
String value1 = params[0];
String value2 = params[1];
String value3 = params[2];
// do some work and return result
return value1 + value2;
}
@Override
protected void onPostExecute(String result){
//use the result you returned from you doInBackground method
}
您應該嘗試在doInBackground方法中完成所有“工作”。 返回要在主/ UI線程上使用的結果。 這將自動作為參數傳遞給onPostExecute方法(在主/ UI線程上運行)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.