How to solve Async Task task on Android

I am working on an application that retrieves data from the network, saves it on the device, and then reads it. The problem is that I get my data in an Async task. And my application does not allow to complete the task before trying to show the data to the user. I tried task.get () but with no result (it just stops there).

Here is my task:

public GetOptionsTask(XMLPortalGetOptions request) { super(request); } protected void onCancelled(){ // TODO afficher message pas d'options sur le disque } @Override public void handleError(Transaction transaction) { // TODO afficher message pas d'options sur le disque } @Override public void handleSuccess(Transaction transaction) { saveOptions(transaction.getResponse()); request = null; Log.d(OptionsManager.class.getName(), this.getStatus().toString()); } 

This task is an instance of my Async custom task:

 protected BaseXMLTransaction request; public abstract void handleError(Transaction transaction); public abstract void handleSuccess(Transaction transaction); public TransactionTask(BaseXMLTransaction request){ this.request = request; } @Override protected Void doInBackground(Void... params) { try { Log.i(TransactionTask.class.getName(), "Doing in background"); SocketHandler.sendTransaction(this, request.getRequest()); } catch (SocketHandlerNotConfiguredException e) { Log.e(TransactionTask.class.getName(), "SocketHandler parameters were not set."); } return null; } @Override public void transactionResult(Transaction transaction) { switch (transaction.getCode()) { case ERROR: Log.e(TransactionTask.class.getName(), "ERROR !!!"); handleError(transaction); break; case NO_CLIENT: Log.e(TransactionTask.class.getName(), "No Client Error"); handleError(transaction); break; case NO_SERVER: Log.e(TransactionTask.class.getName(), "No Server Error"); handleError(transaction); break; case OLD_VERSION: Log.e(TransactionTask.class.getName(), "Old Version"); handleError(transaction); break; case TIMEOUT: Log.e(TransactionTask.class.getName(), "Transaction Timeout"); handleError(transaction); break; case SUCCESS: Log.i(TransactionTask.class.getName(), "Transaction Success"); handleSuccess(transaction); } } 

I seriously don’t know what to do ... Execute is fast and gets nothing, since I do not return anything that I think.

+5
source share
4 answers

onPostExecute (Result), called in the user interface thread after the background calculation is complete. The result of calculating the background is passed to this step as a parameter.

 @Override protected void onPostExecute(String result) { } 
+1
source
 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } } 

and name it as follows:

 new DownloadFilesTask().execute(url1, url2, url3); 
0
source

I use the interface as a delegate for this. Here is an example:

In my main activity, I have an onClick listener to start my asynchronous call and a listener to handle after the call ends.

 private void enableLocationButton(){ locationButton = (Button) findViewById(R.id.locationButton); locationButton.setEnabled(true); locationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, selectLocationActivity.class); intent.putExtra("serverURL",server.getWebServerAddressField()); startActivityForResult(intent, 200); } }); } @Override protected void onActivityResult(int requestCode,int resultCode, Intent data){ if(resultCode == RESULT_OK) { switch (requestCode){ case 100: processServerResponse((PmsWebServer) data.getBundleExtra("server").get("server")); break; case 200: processLocationResponse((PmsDataSource)data.getBundleExtra("location").get("location")); default:processError(); } }else{ processError(); } } 

Somewhere in selectLocationActivity I have an Async call invocation and something to handle the response, note that this class implements the interface that is used in the Async invocation.

 public class selectLocationActivity extends ListActivity implements SoapServiceInterface{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location_select); chosenServer = this.removeURLHeader(getIntent().getStringExtra("serverURL")); this.retrieveLocationOptionsByServer(chosenServer); } private void retrieveLocationOptionsByServer(String server) { Map<String,Object> parms = new HashMap<String,Object>(); parms.put(WEB_SERVER_NAME,server); SoapServiceObject service = new SoapServiceObject(Services.SERVICE_DETAILS,parms); callTheService(service); } private void callTheService(SoapServiceObject service){ SoapServiceHelper helper = new SoapServiceHelper(); helper.delegate = thisActivity; helper.execute(service); } @Override public void serviceCallComplete(SoapObject response){ this.createClickableListOnScreen(response); } //...more code...// } 

serviceCallComplete is started by asyncTask. Below is the code for this task.

 public class SoapServiceHelper extends AsyncTask<SoapServiceObject, Void, SoapObject>{ public SoapServiceInterface delegate = null; private Integer RETRY_COUNT = 0; private final Integer MAX_RETRY_COUNT = 2; protected SoapObject doInBackground(SoapServiceObject... args){ SoapServiceObject service = args[0]; try{ service.callTheService(); }catch(Exception e){ System.out.println("An error occurred calling the service\n" + e.getMessage()); } return service.getResponse(); //return callDateTimeService(); } protected void onPostExecute(SoapObject result){ delegate.serviceCallComplete((SoapObject)(result.getProperty(0))); } } 

And finally, here is the interface

 public interface SoapServiceInterface { public void serviceCallComplete(SoapObject response); } 

I know that I show something on the screen directly from my result, I simply substitute this part with saving and reading;)

0
source

One thing with this task was that it saved things in a singleton. I managed to call methods using information from a network stored in singleton in onResume (). When threads end, it goes into onResume, and everything works fine!

0
source

Source: https://habr.com/ru/post/1241628/


All Articles