Android waits for an async task to complete a specific method

I was looking for an answer, but no one really answers, because there is no point in using the async task for it; in Android api 11 or higher, it will force the code to execute network requests on the main thread, so I need to perform an asynchronous task ... So, the question is, can I wait for the asynchronization to complete before continuing, I need data for the next method and so on .d.

Here is my code:

public JSONObject getJSONFromUrl(String url) { this.url = url; new loadURL().execute(); // Do this when ASYNC HAS FINISHED return jObj; } class loadURL extends AsyncTask <Void, Void, Void> { protected void onPreExecute() { } protected Void doInBackground(Void... unused) { //do stuff in background return (null); } } 

}

Any questions for awnser just leave a comment. Thanks for the help.

+4
source share
3 answers

yes, you use the onPostExecute method for AsyncTask to do what you want to do. This method is called after doInBackground completes doInBackground

+7
source

If the operation does not take much time (less than a few seconds), you can use the progress bar so that it does not allow the user to do anything. Install something like this in AsyncTask

 ProgressDialog progress = ProgressDialog.show(LoginScreen.this, "Downloading Users", "Please wait while users are downloaded"); @Override protected void onPreExecute() { progress.setCancelable(false); progress.isIndeterminate(); progress.show(); } 

You still want to call your method from onPostExecute() , as this will just cause the user to do nothing, but he will not run any code from the method that you are calling AsyncTask from

+1
source

You can perform a network-related operation inside the doInBackground () method, because the onPostExecute () method is only used to update the user interface in android only

0
source

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


All Articles