onPostExect on Android AsyncTask doesn't get called - java

I've trying to create an Android client to cal via AsyncTask. Server has a primary and a secondary job to do for the same connection. If the primary returns some result then I don't need to do the secondary part but if server returns null I want to ask User using an AlertDialog if he wants to continue and if he says yes then I continue the communication with the server.
To do that I've seperated the call on doInBackground() and onPostExecute() method. Here is my logic:
#Override
protected Object doInBackground(Object... params) {
//Do primary part of the call
return obj;
}
#Override
protected void onPostExecute(Object obj) {
if(obj == null) {
super.onPostExecute(obj);
//Throw alert window to ask user if he wants to continue
//If user says yes call server to do the the secondary part
}
}
from the mainActivity when I call this AyncTask I use the get() method so that I can wait until it's inished to take the result.
My problem is that onPostExecute() never gets called...Any ideas?Does it play any role the fact that I contue calling the server on onPostExecute()?

EXAMPLE USES OF ASYNCTASK
Want to give AsyncTask a try? Here’s an example of how to use this function.
class DoSomeTask extends AsyncTask{
#Override
protected void onPreExecute() {
//Setup precondition to execute some task
}
#Override
protected String doInBackground(String... params) {
//Do some task
publishProgress (1);
return "";
}
#Override
protected void onProgressUpdate(Integer... values) {
//Update the progress of current task
}
#Override
protected void onPostExecute(String s) {
//Show the result obtained from doInBackground
}
}
more details : https://www.upwork.com/hiring/mobile/why-you-should-use-asynctask-in-android-development/
and
http://www.journaldev.com/9708/android-asynctask-example-tutorial

Related

Replicating Swift completion handler on Android & Java

After years, I'm trying to develop an Android app, using Firebase Firestore. I'm basically trying to replicate this Swift function:
func getCategories(onCompletion completionBlock: #escaping (_ categories: [Category]?, _ error: Error?) -> Void) {
firestore.collection("cats").getDocuments { (snap, error) in
guard let snap = snap else {
completionBlock(nil, error ?? anUnknownError)
return
}
var categories: [Category] = []
for document in snap.documents {
let cat = Category.init(data: document.data())
categories.append(cat)
}
completionBlock(categories, nil)
}
}
But I have no idea what is the equivalent of swift's blocks, even don't know if it exists.
I checked Firebase source codes. Query.get() returns Task<QuerySnapshot> so I tried to return a Task<List<Category>> without luck.
Any Help? Thank you.
EDIT: Android code added to clarify what I'm trying to do.
public class FirestoreService {
private static volatile FirestoreService singleton = new FirestoreService();
public static FirestoreService getInstance() {
return singleton;
}
private FirebaseFirestore firestore() {
// default firestore instance
FirebaseFirestore db = FirebaseFirestore.getInstance();
// default firestore settings
FirebaseFirestoreSettings settings = db.getFirestoreSettings();
// firestore settings builder
FirebaseFirestoreSettings.Builder builder = new FirebaseFirestoreSettings.Builder(settings);
// enable timstamps
builder.setTimestampsInSnapshotsEnabled(true);
// set new settings to db instance
db.setFirestoreSettings(builder.build());
// return db with new settings.
return db;
}
public void getProductCategories(Handler? handler) {
Task<QuerySnapshot> task = firestore().collection("coll").get();
task.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
try {
if (task.isSuccessful()) {
List<Category> cats = new ArrayList<>();
for (QueryDocumentSnapshot doc : task.getResult()) {
String id = doc.getId();
Map<String, Object> data = doc.getData();
Category cat = new Category(id, data);
cats.add(cat);
}
// now I need completion handler
} else {
Log.w("ERROR", "Error getting categories", task.getException());
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
});
}
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirestoreService.getInstance().getCategories().addCompletionListener(
// handle List<Category> and respresent in UI
);
}
}
Thank you very much four your help and lead #Daniel-b.
I've solved my issue now.
First I created an Interface for handling results; as you suggested.
public interface ResultHandler<T> {
void onSuccess(T data);
void onFailure(Exception e);
}
Then in the service class, I added ResultHandler to the function's input parameters :
public void getUserInfo(String id, ResultHandler<UserInfo> handler) {
firestore().collection("userInfo").document(id).get().addOnCompleteListener(snap -> {
if (snap.isSuccessful()) {
try {
// failable constructor. use try-catch
UserInfo info = new UserInfo(snap.getResult().getId(), snap.getResult().getData());
handler.onSuccess(info);
} catch (Exception e) {
handler.onFailure(e);
}
} else {
handler.onFailure(snap.getException())
}
});
}
And called service in Activity
FirestoreService.getInstance().getUserInfo("ZsrAdsG5HVYLTZDBeZtkGDlIBW42", new ResultHandler<UserInfo>() {
#Override
public void onSuccess(UserInfo data) {
Log.i("UserInfo", data.id);
}
#Override
public void onFailure(Exception e) {
// getting data failed for some reason
}
});
Using AsyncTask
You can use an AsyncTask. It has 3 steps to it.
1. onPreExecute() - things you want to do before running doInBackground(). This happens in the UI main thread.
2. doInBackground()- the AsyncTask, will do operations in a background thread (the background thread is created by Android so you don't need to worry about it).
3.onPostExecute() - here you can receive any data from the doInBackground method. The postExecute method is executed again, in the UI main thread.
So you can do any I/O operations in doInBackground(), and return the value you received from the server or any other data source, and onPostExecute(), is the equivalent of a completion block in swift.
How to Declare
To use AsyncTask, you need to extend the Android AsyncTask.
So your own AsyncTask declaration will look like this:
private class MyAsyncTask extends AsyncTask<Void, Void, Void> { ... }
What are the 3 generic arguments you ask?
1. Params - the type of the parameters sent to the task upon execution.
2. Progress - the type of the progress units published during the background computation. (Almost always will be Void, unless you care about the actual progress of the operation. Notice this is Void with a capital letter, and not void as the return type).
3. Result - the type of the result of the background computation.
Full Example
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
TextView txt = findViewById(R.id.output);
txt.setText(result);
}
}
In the example, I create a fake, long operation, that you can not run on the UI main thread (because it is a blocking operation).
When the operation is finished, it returns a String, and that same String is received in the onPostExecute() method (and remember, onPostExecute() runs on the UI main thread again). So you can change your UI with the String value you received from the long,blocking operation.
If you want the documentation, here it is:
https://developer.android.com/reference/android/os/AsyncTask
Using Observer Pattern
You can also use the observer pattern in your situation.
Create an interface, that has a method onSuccess(). Have an object implement that interface, and whenever you need it, you can call the onSuccess() method.
Example:
public Interface SuccessInterface{
void onSuccess()
}
public class SuccessHandler implements SuccessInterface{
public void onSuccess(){
//success code goes here
}
}
then in your code, have a SucessHandler instantiated, and call onSuccess() when you need to.
For API 26,
CompletionHandler is available.
Check https://developer.android.com/reference/java/nio/channels/CompletionHandler

How to pass function as paramater to AsynTask

since im new in android development, and i need to provide an asynctask class for my http request. i have a lot of http request function type in one activity, and i want to make it dynamic. so i wanted to create only one AsyncTask function that can run all my function.
so this is the example
private class WebServiceCall extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setVisibility(View.VISIBLE);
pBar.setIndeterminate(false);
pBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
// a function that i passed
Function01();
return null;
}
#Override
protected void onPostExecute(Void result) {
try{
some code
}
}
catch(Exception e)
{
e.printStackTrace();
}
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setClickable(true);
pBar.setVisibility(View.GONE);
}
}
and i just call like this
Oncreate(
new WebServiceCall().execute(function01());
)
any help and code sample would be appreciate,
thanks
I don't know what you mean by a function as a parameter to another function!
but you can use Interfaces for this purpose.
for example:
create an Call Back interface that can be called in onPostExecute()
public interface ResponseCallback {
void onRespond();
}
and before calling asynckTask define it like this:
ResponseCallback callback = new ResponseCallback() {
#Override
public void onRespond() {
//code to be done after calling it from onPostExecute
}
};
and pass callback to the constructor of of the asynckTask and call it in onPostExecute
of course you can modify the signature of the interface to what ever you want.
Send class object with your function and call function from object in AsyncTask.
public class A
{
//your function
int function()
{
return...;
}
}
private class WebServiceCall extends AsyncTask<Void, Void, Void> {
A myobj;
WebServiceCall(A mycustomslass)
{
myobj = mycustomclass;
}
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setVisibility(View.VISIBLE);
pBar.setIndeterminate(false);
pBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
// a function that i passed
int cur = myobj.function();//this your function
return null;
}
#Override
protected void onPostExecute(Void result) {
try{
some code
}
}
catch(Exception e)
{
e.printStackTrace();
}
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setClickable(true);
pBar.setVisibility(View.GONE);
}
}
and you can call like
Oncreate(
new WebServiceCall(new A()).execute();
)
This doesn't address your question directly, but I urge you to investigate both the fairly-well advertised problems with using AsyncTask for anything that's likely to take more than a few milliseconds, and the several really good HTTP / REST frameworks for Android, e.g. Retrofit.

Synchronized doesn't synchronize

I have a custom adapter that it's associated with a ListView in my MainActivity class and when I press on one of the items of the List (setOnItemClickListener method) I execute an AsyncTask to retrieve the info from the database and send it into a bundle.
Therefore, I have to wait until the AsyncTask finishes to send the info retrieved in the bundle.
For this purpose, I created an interface:
public interface OnCarListener {
void onCarCompleted(String c);
void onCarError(String error);
}
And I have my AsyncTask in another class:
class findCar extends AsyncTask<Integer, Integer, String> {
private final OnCarListener mListener;
public findCar(OnCarListener listener)
{
mListener = listener;
}
protected void onPreExecute() {
}
protected String doInBackground(Integer... idCar) {
String nameCar = "";
//Here the code to retrive the info
nameCar = obj.getString("name");
//Now nameCar = "Car1"
} catch (Exception ex) {
}
return nameCar;
}
protected void onProgressUpdate() {
}
protected void onPostExecute(String c) {
if (mListener != null) {
mListener.onCarCompleted(c);
}
}
}
And I execute my AsyncTask (in my MainActivity) as follows:
new findCar(new OnCarListener()
{
#Override
public void onCarCompleted(String c) {
synchronized (c)
{
name = c;
}
}
#Override
public void onCarError(String error) {
}
}).execute(idCar);
And after executing the AsyncTask I throw the bundle:
bundle.putString("name", name);
Note: I send more info with the bundle but I omitted it to simplify the question.
It should work in my opinion but in the first click in one element of the List the name isn't being passed by the bundle, just in the second and the rest of the clicks I made at the same or in the rest elements of the List, it works.
Expected result: AsyncTask will be executed and until it finishes the rest of the code shouldn't work. It is clear that it's not what it's doing right now.
What I want to know: Why the synchronized doesn't work in the first iteration? I mean, when I have the List and I click on one of the elements of the List the information of the element it's show (in another Activity) but the value name it's not shown.
If I go back and I do one or more clicks on the same element (or a different one) from the List, in all of them appears the value name correctly.
Why in the first iteration it doesn't work?
And I have another question: Why if I quit the synchronized as adelphus said in his answer, any of the times that I click on the elements of the List the value name appears?
I tried the solution in this question: synchronized not synchronizing but still doesn't work.
What could I do? (Without changing the logic of the program)
Thanks in advance!
I'm not sure you understand what synchronized does - it creates an exclusive lock on a given object to create ordered access to a section of code. When multiple threads attempt to enter a synchronized block (with the same lock object), only one thread will be allowed to continue into the block at a time.
In your code, you're synchronizing on the String parameter c. Since no other threads will be accessing this parameter, synchronized has no effect here.
Since your interface callback is being called on the UI thread (via onPostExecute()), you can just set the bundle value in the callback:
void amethod() {
final Bundle bundle = new Bundle();
new findCar(new OnCarListener()
{
#Override
public void onCarCompleted(String c) {
bundle.putString("name", c);
}
#Override
public void onCarError(String error) {
}
}).execute(idCar);
}

kills an Android AsyncTask with a timeout

So my problem is that i have a AsyncTask that scraps html from a page on a server so i used Jsoup as a library .
so the problem is that i want to set a timeout to cancel the Task if i don't receive any data from the page and display that there is a "communication error " on a toast
is there anyway to kill or stop the asynctask within it self and return a result on onPostExecute
{
private class getPageTitle extends AsyncTask<Void, Void, String> {
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
connectServerProgressDialog = new ProgressDialog(LoginScreen.this);
connectServerProgressDialog.setTitle("CheckingServer");
connectServerProgressDialog.setMessage("Loading...");
connectServerProgressDialog.setIndeterminate(true);
connectServerProgressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(CONNECT_URL).get();
title = document.title();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
#Override
protected void onPostExecute(String result) {
if(result!=null){
switch (title) {
case "0":
Toast.makeText(LoginScreen.this,"offline",Toast.LENGTH_SHORT).show();
connectServerProgressDialog.dismiss();
break;
case "1":
connectServerProgressDialog.dismiss();
Toast.makeText(LoginScreen.this,"Connected",Toast.LENGTH_SHORT).show();
break;
}}else{
Toast.makeText(LoginScreen.this,"Communication error",Toast.LENGTH_SHORT).show();
}
}
}}
I have a convention that I use for AsyncTask subclasses.
Define an inner interface for the client to use. This decouples the client class so that the AsyncTask can be re-used. The interface is named in the form blahblahListener.
The interface has two methods of the form blahblahCompleted() and blahblahException().
Accept a callback object (listener) that is an implementation of that interface. This is either passed in the AsyncTask constructor or set with a setListener() method.
Hold that listener reference in a WeakReference field so that if the listener goes away before the task completes, the listener can still be garbage-collected.
Define a field to hold an Exception. If an exception occurs in the background method, this field remembers the exception in order to report it to the client.
In the onPostExecute() method, check if the Exception field is null. If it is, call blahblahCompleted() with the result. If it isn't, call blahblahException() with the exception. Also check if the WeakReference is still valid.
For killing the task, you can have a timeout set on your connection. Then when your connection times out, you will get an exception, which is remembered and reported.
So using that convention, your code would look like this:
public class WebPageTitleRemoteTask extends AsyncTask<URL, Void, String> {
private WeakReference<WebPageTitleRetrievalListener> mListener;
private Exception mException;
public WebPageTitleRemoteTask(WebPageTitleRetrievalListener listener) {
super();
mListener = new WeakReference<WebPageTitleRetrievalListener>(listener);
}
#Override
protected String doInBackground(URL... params) {
String title = null;
try {
// Connect to the web site
Document document = Jsoup.connect(params[0]).get();
title = document.title();
} catch (IOException e) {
mException = e;
}
return title;
}
#Override
protected void onPostExecute(String result) {
WebPageTitleRetrievalListener listener = mListener.get();
if (listener != null) {
if (mException == null) {
listener.webPageTitleRetrieved(result);
} else {
listener.webPageTitleRetrievalException(mException);
}
}
}
public static interface WebPageTitleRetrievalListener {
public void webPageTitleRetrieved(String title);
public void webPageTitleRetrievalException(Exception e);
}
}
And your client code would look something like this, with your Activity implementing that inner interface:
.
.
.
connectServerProgressDialog = new ProgressDialog(LoginScreen.this);
connectServerProgressDialog.setTitle("CheckingServer");
connectServerProgressDialog.setMessage("Loading...");
connectServerProgressDialog.setIndeterminate(true);
connectServerProgressDialog.show();
new WebPageTitleRemoteTask(this).execute(url);
.
.
.
#Override
public void webPageTitleRetrieved(String title) {
if (isFinishing()) return;
connectServerProgressDialog.dismiss();
Toast.makeText(this, "title = " + title, Toast.LENGTH_SHORT).show();
}
#Override
public void webPageTitleRetrievalException(Exception e) {
if (isFinishing()) return;
connectServerProgressDialog.dismiss();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
NOTE: Because the listener is held in a WeakReference, you can't use an anonymous inner class for the listener, because the reference will go away almost immediately and be eligible for garbage collection.
I use this convention consistently, and the extra boilerplate code in the AsyncTask subclass makes it a lot cleaner to use in the client class.

calling AsyncTask in main thread inside a for loop

I have someclass which do large network operations and it do take some time to complete,and hence i put it in AsyncTask .I have to do this process 'n' times so in the main thread using a for loop i called this asynctask n times.will it throw any error since there is an interrupt in completing the for loop.?
// inside main thread
for(i=0;i<n;i++)
{
new asynctask().execute(new someclass());
}
Running mutliple AsyncTask is not recommended, but if it is few times, then it will work but all async task will run serially not in parallel. But if you want async tasks to run parallelly then you can call it's executeOnExecutor(..) method where you have to pass THREAD_POOL_EXECUTOR as parameter. You can search on google you can find many links. Here is an example for your help.
don't call AsyncTask n times just put your for loop in onPostExecute() and do any task up to n times
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
} catch (Exception e) {
e.printStackTrace();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
for(i=0;i<n;i++)
{
//do your operation here
}
}
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
}
#Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
}

Categories