Java Android:NetworkOnMainThreadException异步任务内出现异常错误
好的,我创建了一个内部类,它扩展了AsycTask,以便我的代码能够与UI线程一起运行。然而,我得到了这个错误,所以我假设这意味着我的onPostExecute的某些部分需要在doInBackground中完成,但是我不能确切地知道这是什么Java Android:NetworkOnMainThreadException异步任务内出现异常错误,java,android,exception,android-asynctask,networkonmainthread,Java,Android,Exception,Android Asynctask,Networkonmainthread,好的,我创建了一个内部类,它扩展了AsycTask,以便我的代码能够与UI线程一起运行。然而,我得到了这个错误,所以我假设这意味着我的onPostExecute的某些部分需要在doInBackground中完成,但是我不能确切地知道这是什么 public class asyncTask extends AsyncTask<String, Integer, String> { ProgressDialog dialog = new ProgressDialog(Pet
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中展示代码应该放在哪里的示例,那就太好了。谢谢,问题:
您正在onPostExecute中隐式调用doInbackground方法,该方法实际上将在您的UI线程中运行,而不是在另一个线程上运行,从而导致Android:NetworkOnMainThreadException
另外,当您执行异步任务时,在onPostExecute之前已经执行了doInBackground,不必调用它。只需直接使用onPostExecute的结果参数
样本:
我怀疑错误与代码的这一部分有关:
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方法完成所有工作。Reutrn要在主/UI线程上使用的结果。这将自动作为参数传递给在主/UI线程上运行的onPostExecute方法。非常感谢我是AsycTask新手,但我应该意识到这个错误。这已经奏效了,非常感谢您提供的代码示例非常好的答案,但是我实际上返回了值。这是一个愚蠢的错误,我在onPostExecute中再次访问doInBackground方法,这完全没有用,因为在执行asyncTask时调用了该方法。我明白我的错误,但非常感谢你的回答
try
{
// Get the data from the RSS stream as a string
result = doInBackground(petrolPriceURL);
response.setText(result);
Log.v(TAG, "index=" + result);
}
//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
}