Java aSync 任务不能执行两次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19345118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
aSync Task can't be executed twice
提问by Stian Instebo
I'm working on app which needs to upload a file to server. But to upload the files it needs to login (working) then get the url (working) then uploading (Force Close)
我正在开发需要将文件上传到服务器的应用程序。但是要上传它需要登录(工作)然后获取网址(工作)然后上传(强制关闭)的文件
The logcat:
日志猫:
10-13 14:10:27.494: E/AndroidRuntime(26578): FATAL EXCEPTION: main
10-13 14:10:27.494: E/AndroidRuntime(26578): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:578)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.os.AsyncTask.execute(AsyncTask.java:534)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.spxc.bayfiles.FilesActivity.onOptionsItemSelected(FilesActivity.java:294)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.actionbarsherlock.app.SherlockActivity.onMenuItemSelected(SherlockActivity.java:208)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchOptionsItemSelected(ActionBarSherlockNative.java:93)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.actionbarsherlock.app.SherlockActivity.onOptionsItemSelected(SherlockActivity.java:159)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.app.Activity.onMenuItemSelected(Activity.java:2566)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:986)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:547)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:115)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.view.View.performClick(View.java:4240)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.view.View$PerformClick.run(View.java:17721)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.os.Handler.handleCallback(Handler.java:730)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.os.Handler.dispatchMessage(Handler.java:92)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.os.Looper.loop(Looper.java:137)
10-13 14:10:27.494: E/AndroidRuntime(26578): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-13 14:10:27.494: E/AndroidRuntime(26578): at java.lang.reflect.Method.invokeNative(Native Method)
10-13 14:10:27.494: E/AndroidRuntime(26578): at java.lang.reflect.Method.invoke(Method.java:525)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-13 14:10:27.494: E/AndroidRuntime(26578): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-13 14:10:27.494: E/AndroidRuntime(26578): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:112)
10-13 14:10:27.494: E/AndroidRuntime(26578): at dalvik.system.NativeStart.main(Native Method)
My code: (handleJsonObject):
我的代码:(handleJsonObject):
private void handleJsonObject(JSONObject object) {
try {
sUpload = object.getString("uploadUrl");
HttpClient httpclient = new DefaultHttpClient();
//post request to send the video
File sdCardRoot = Environment.getExternalStorageDirectory();
File myDir = new File(sdCardRoot, "Download");
HttpPost httppost = new HttpPost(sUpload);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy( policy);
FileBody video_file1 = new FileBody(new File(myDir + "/test.txt"));
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file=", video_file1);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = null;
try {
response = httpclient.execute( httppost );
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
try {
System.out.println( EntityUtils.toString( resEntity ) );
} catch (org.apache.http.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end if
if (resEntity != null) {
try {
resEntity.consumeContent( );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end if
httpclient.getConnectionManager( ).shutdown( );
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data: " + e.toString());
Crouton.makeText(this, "Something went wrong!", Style.ALERT).show();
}
}
The code (aSync) Which calls the post code (handleJsonObject):
调用post代码(handleJsonObject)的代码(aSync):
asyncTask.setJsonListener(new JsonListener() {
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
asyncTask.execute("http://api.bayfiles.net/v1/file/uploadUrl?session=" + sessionId);
I can't figure out why the code won't work? Any help is much appreciated!
我不明白为什么代码不起作用?任何帮助深表感谢!
采纳答案by waqaslam
As the exception itself explains, you cannot execute an AsyncTask
more than once, unless you create a new
instance of it and call .execute
.
正如异常本身所解释的那样,您不能AsyncTask
多次执行一个,除非您创建new
它的一个实例并调用.execute
.
For example:
例如:
async = new AsyncTask();
async.execute();
*in order to execute more than once, you need to re-create the instance (using new
) the number of times you want to executeit.
*为了多次执行,您需要重新创建实例(使用new
)您想要执行它的次数。
回答by boakye_wozniac
You cannot execute AsyncTask more than once,therefore to fix this error, simply wrap it in a condition like this : async = new AsyncTask();
您不能多次执行 AsyncTask,因此要修复此错误,只需将其包装在这样的条件中: async = new AsyncTask();
if (async==null){
async.execute();
}
This error usually occurs when you are trying to run Asynctask in a viewpager. When you run asynctask in a fragment and swipe to the next fragment, returning to the previous fragment triggers a re- execution of the asynctask in that fragment causing the app to crash. Therefore you have to check if the asynctask has already been executed by wrapping it in a condition.
当您尝试在 viewpager 中运行 Asynctask 时,通常会发生此错误。当您在片段中运行 asynctask 并滑动到下一个片段时,返回到前一个片段会触发该片段中异步任务的重新执行,从而导致应用程序崩溃。因此,您必须通过将其包装在条件中来检查异步任务是否已被执行。
回答by yader_centeno
I use this code and it works for me:
我使用此代码,它对我有用:
if ((eliminar_op_async != null) && eliminar_op_async.getStatus() == AsyncTask.Status.RUNNING) {
if (eliminar_op_async.isCancelled()) {
eliminar_op_async = new EliminarOperacion();
eliminar_op_async.execute(id_operacion,posicion_operacion);
}
else {
// Nada
}
}
if ((eliminar_op_async != null) && eliminar_op_async.getStatus() == AsyncTask.Status.PENDING) {
eliminar_op_async.execute(id_operacion,posicion_operacion);
}
if ((eliminar_op_async != null) && eliminar_op_async.getStatus() == AsyncTask.Status.FINISHED) {
eliminar_op_async = new EliminarOperacion();
eliminar_op_async.execute(id_operacion,posicion_operacion);
}
if (eliminar_op_async == null) {
eliminar_op_async = new EliminarOperacion();
eliminar_op_async.execute(id_operacion,posicion_operacion);
}
回答by He Termis
You can cancel by calling async instance with async.cancel(true) so that you can ensure there is only one instance of async
您可以通过使用 async.cancel(true) 调用 async 实例来取消,这样您就可以确保只有一个 async 实例