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
Related
How can I change the value of a variable inside the method from anonymous inner class, to access this variable it must be a final, but if the variable final can't change its value, how solve this problem using java?
This is My Code, I want to change the value of addFlag.
public static boolean addUser(UserModle user){
Boolean addFlag ;
dbUser = FirebaseDatabase.getInstance().getReference("user");
Task task = dbUser.child(user.getId()).setValue(user);
task.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
addFlag = true;
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
return addFlag;
}
IMHO, the current implementation of the addUser function is flawed. As per my understanding, you want to know if the user was added successfully to your firebase database based on the addFlag value that is returned from this function.
The addFlag will be updated once the Firebase database call will get back the data from the firebase realtime database. However, you are returning the flag immediately and hence you are not waiting for the result from your background network thread.
In order to achieve that, I would like to suggest an interface based implementation. You might have an interface as follows.
public interface FirebaseListener {
void onSuccess(boolean flag);
}
Then add an extra parameter in your addUser function to pass that interface from your Activity or Fragment where you are calling this function. Hence the function might look as follows.
// Change the return type to void, as we are not expecting anything from this function.
// Instead, we will wait for the success callback using the interface
public static void addUser(UserModle user, FirebaseListener listener) {
dbUser = FirebaseDatabase.getInstance().getReference("user");
Task task = dbUser.child(user.getId()).setValue(user);
task.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
listener.onSuccess(true);
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onSuccess(false);
}
});
}
Now implement the listener in your activity or fragment as follows.
public MyActivity extends AppCompatActivity implements FirebaseListener {
// ... Other functions of your activity
#Override
public void onSuccess(boolean flag) {
if (flag) {
// User add successful. Do something here
} else {
// User add not successful. Do something here
}
}
}
Now while calling the addUser function, you should pass the callback listener along with it as follows.
addUser(user, this);
I hope that helps.
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.
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);
}
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.
I am trying to understand mechanism of callback handler. How is the handle() method invoked? Can anybody give an example of usage of custom callback handler (other than those used in Login Modules of JASS or so) in non Swing application?
Define an interface to handle the callback.
public interface ServiceListener<T> {
void callback(T result);
}
Define a method that takes ServiceListener as parameter and returns void.
Public void runInBackground(ServiceListener listener) {
...code that runs in the background...
listener.callback(...data to return to caller...);
}
And you can now do this from your main code:
runInBackground(new ServiceListener() {
#Override
public void callback(..returned data...) {
...Do stuff with returned data...
}
});
This is a basic example for requesting data from a webserver using the AsyncTask from an Android application.
First define the async class. Note that the constructor takes a listener which we use to publish the result once ready.
public class Webservice extends AsyncTask<String, Void, String> {
private DialogListener dialogListener;
public Webservice(final DialogListener dialogListener) {
this.dialogListener = dialogListener;
}
#Override
protected String doInBackground(final String... strings) {
// We cant trigger onComplete here as we are not on the GUI thread!
return "";
}
protected void onPostExecute(final String result) {
dialogListener.onComplete(result);
}
}
Basic server class for handling various network communications:
public class Server {
public void queryServer(final String url, final DialogListener service) {
// Simulate slow network...
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Webservice(service).execute(url);
}
}
We can now use this code inside our activity without having to worry how long the call takes as it is not going to halt the GUI as it is executed async.
Server s = new Server();
// Async server call.
s.queryServer("http://onto.dk/actions/searchEvents.jsp?minLatE6=55640596&minLngE6=12078516&maxLatE6=55642654&maxLngE6=12081948", new DialogListener() {
#Override
public void onComplete(final String result) {
toast("complete");
}
#Override
public void onError() {
toast("error");
}
});