Not solely a Firebase question, but I am using Firebase to make posts to a backend from Android and run it 10 times, once every second.
Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());
However this is an Asynchronous Call and when I put a while loop:
while (time_now < time_start + 10 seconds) {
Firebase ref = new Firebase(URL);
ref.child("Time").setValue(Currentime());
}
It seems to run the while loop first and then ~10 Firebase calls at the end. Is there a way to add a timeout so that it forces the Asynchronous (Firebase) calls to run for a second before calling the next Async call?
If you look at the Java example on the Firebase web site, you'll see that it has a doTransactions method and an onComplete method:
Firebase countRef = new Firebase(URL);
Transaction.Handler handler = new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData currentData) {
// set the new time
...
}
#Override
public void onComplete(FirebaseError error, boolean committed, DataSnapshot currentData) {
if (error != null) {
...
} else {
if (!committed) {
...
} else {
// transaction committed, do next iteration
...
}
...
}
}
});
countRef.runTransaction(handler);
So you'd set the new time in the doTransaction method:
// set the new time
currentData.setValue(time_now);
return Transaction.success(currentData);
And then start a next iteration in the onComplete method.
// transaction committed, do next iteration
if (time_now < time_start + 10 seconds) {
countRef.runTransaction(handler);
}
Related
I am making a chat app, checking if there are any new messages using a REST call. On a one second timer I am checking if the id of the last message in list is the same as the last id of newly downloaded list. If it isn't the same id (there are new messages) then update the recycerview. The problem is that it keeps on updating without any new messages and I am not sure why. Most likely it's a simple problem though i can't seem to find it.
Timer:
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
readMessages(myId, chatId);
}
}, 0, 1000);
REST call:
private void readMessages(String myId, String chatId) {
apiInterface = ApiClient.getClient().create(userApi.class);
Call<LinkedList<Messages>> call = apiInterface.getMessages(myId, chatId);
call.enqueue(new Callback<LinkedList<Messages>>() {
#Override
public void onResponse(Call<LinkedList<Messages>> call, Response<LinkedList<Messages>> response) {
mList.clear();
mList = response.body();
if (mList2.isEmpty() || mList2.getLast().getId().equals(mList.getLast().getId())) {
messageAdapter = new MessageAdapter(ChatActivity.this, mList, Integer.parseInt(myId));
recyclerView.setAdapter(messageAdapter);
mList2.clear();
mList2 = (LinkedList) mList.clone();
Toast.makeText(ChatActivity.this, mList2.getLast().getId(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<LinkedList<Messages>> call, Throwable t) {
}
});
}
The first part of your if statement is mList2.isEmpty() (I assume mList and mList2 are actually the same thing). A wild guess for a reason why each call to onResponse passes if the test would be that the list is actually empty. Try step-by-step debug and placing a breakpoint on the if line to check, and if so, take a look at your REST service in order to understand why it is responding with an empty list.
So in your code what exactly is supposed to happen if the condition is not met?
If see that there is an if statement. And let us assume we are not going into it because conditions are not met. So where is the else statement? What is the code supposed to do if the conditions don't match? As there is nothing else to be done in function, the control will return back from the function to the timer.
You can probably try putting timer inside the if statement, so it will only run when your conditions are met.
Do you think this was the problem?
I have an issue with android studio and the retrofit library and the way in which it processes the data.
I have a simple flow of operation I would like:
Request single item from database on server(fetch request)
Wait for callback to confirm it has been received by the app
Add another request(Loop)
Stop adding requests when all data is sent
The issue I have is my onResponse callback for my fetch result does not run until all my requests are sent. Then all the responses are errors. ( If I call a single item(1 from the database)) the call back runs fine.
How do I force it to send one request and wait until that response before sending another?
Loop code
private void Pull_data_loop(int total_entries){
//int current_data_point = 0;
boolean datum_processing = false;
for (int i = 1; i <= total_entries; i++) {
Add_single_datam(i);//Call until all entries are fetched from the server
}
}
Fetch code- Not running callback need to wait for this callback before sending next request
private void Add_single_datam(int id)
{
HashMap<String, String> map = new HashMap<>();
map.put("Id_request", Integer.toString(id));//The ID value
Call<Fetch_result> call = retrofitInterface.executeGet_data(map);//Run the post
call.enqueue(new Callback<Fetch_result>() {
#Override
public void onResponse(Call<Fetch_result> call, Response<Fetch_result> response) {
if (response.code() == 200)//Successful login
{
D1= response.body().getD1_String();
D2= response.body().getD2_String();
boolean result = BLE_DB.addData_Downloaded(D1, D2);//Add data
if (result == true) {
Log.d(TAG, "data_changes: Added data correctly");
}
if (result == false) {
Log.d(TAG, "data_changes: did not add data correctly");
}//false
} else if (response.code() == 404) {
Utils.toast(getApplicationContext(), "Get data fail");//Pass information to the display
}
}
#Override
public void onFailure(Call<Fetch_result> call, Throwable t) {
Utils.toast(getApplicationContext(), "Get data error");
}
});
}
Note:
I am using a node js server for my requests. I send the Id and it returns that Id in the database.
You could send a callBack instance to your Add_single_datam then in your retrofit response, send to that callback success.
Then in that callBack you would have iteravel i and you could see if you reached the end of total_entries added +1 in i and make request again, or just stop.
use some threading solutions like RxJava or Coroutines or AsyncTask. The reason it's not following the rule is because of there are two threads on which work is getting distributed so in order to get it make it work in sync, we have to use some threading solutions mentioned above and execute this for loop on the background thread and make it like a synchronous call and get all the results and finally switch back to main thread with the results.
If you are familiar with the AsynTask.
private class FetchDataTask extends AsyncTask<Int, Integer, List<Fetch_result>> {
protected Long doInBackground(Int... total_entries) {
List<Fetch_result> allResults = new ArrayList<Fetch_result>();
for (int i = 1; i <= total_entries[0]; i++) {
HashMap<String, String> map = new HashMap<>();
map.put("Id_request", Integer.toString(total_entries[0]));
Fetch_result response = retrofitInterface.executeGet_data(map).execute().body();
allResults.add(response);
}
return allResults;
}
protected void onProgressUpdate(Integer... progress) {
//show progress
}
protected void onPostExecute(List<Fetch_result> result) {
//do something on main thread, in loop on result
D1= result[0].getD1_String();
D2= result[0].getD2_String();
boolean result = BLE_DB.addData_Downloaded(D1, D2);//Add data
if (result == true) {
Log.d(TAG, "data_changes: Added data correctly");
}
if (result == false) {
Log.d(TAG, "data_changes: did not add data correctly");
}//false
}
}
now call like this.
new FetchDataTask().execute(total_entries);
I'm using an ajax call to spring controller to start a firebase query, save the result to local database and return items saved in the local database (including the results saved from the current and previous firebase queries too). The problem is that since the firebase query runs async, the results from the local database query are returned before the firebase query finishes.
How can I make the returned local database query wait until the firebase query finished?
#PostMapping("/firebase-download")
#ResponseBody
public List<FirebaseTransactionRecord> firebaseDownload() {
firebaseService.downloadAndSaveFirebaseTransactions();
// wait for the query to end
return firebaseTransactionRecordRepository.findBySentFalse();
}
#Override
#Transactional
public void downloadAndSaveFirebaseTransactions() {
final List<FirebaseTransactionRecord> firebaseTransactions = new ArrayList<>();
firebaseDb.child(StringValueConstant.DB_CHILD_TEMPORARY_TRANSACTIONS)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
userSnapshot.getChildren().forEach(transactionSnapshot -> {
FirebaseTransactionRecord record = firebaseTransactionMapper
.toFirebaseTransactionRecord(transactionSnapshot);
firebaseTransactions.add(record);
});
}
saveFirebaseTransactionRecords(firebaseTransactions);
}
#Override
public void onCancelled(DatabaseError error) {
log.error("Error reading Firebase data:", error);
}
});
}
#Override
#Transactional
public void saveFirebaseTransactionRecords(List<FirebaseTransactionRecord> firebaseTransactions) {
firebaseTransactions.forEach(firebaseTransaction -> {
if (!firebaseTransactionRecordRepository.existsByReferralNumber(firebaseTransaction.getReferralNumber())) {
firebaseTransactionRecordRepository.save(firebaseTransaction);
}
});
}
Something with a CountdownLatch should do the trick.
Set the initial latch counter to 1 (for the main listener), then set it to the number of child nodes in onDataChange. Next pass the latch to saveFirebaseTransactionRecords and decrease it when each transaction completes. Once the latch reaches 0, you can exit out of downloadAndSaveFirebaseTransactions
This question already has answers here:
Combining Firebase realtime data listener with RxJava
(5 answers)
Closed 2 years ago.
Does anyone knows how to connect Firebase with RxJava so when I load ALL my data from database then it runs arrayAdapter.notifyDataSetChanged() ??
I was thinking to write it in onComplete() method but it still runs before loading all data
Completable.fromCallable(new Callable<List<cards>>() {
#Override
public List<cards> call() throws Exception {
newUserDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(currentUID).child("sex").exists()) {
myInfo.put("sex", dataSnapshot.child(currentUID).child("sex").getValue().toString());
}
if (dataSnapshot.child(currentUID).child("dateOfBirth").exists()) {
int myAge = stringDateToAge(dataSnapshot.child(currentUID).child("dateOfBirth").getValue().toString());
myInfo.put("age", String.valueOf(myAge));
}
if (dataSnapshot.child(currentUID).child("connections").child("yes").exists()) {
for (DataSnapshot ds : dataSnapshot.child(currentUID).child("connections").child("yes").getChildren()) {
if (!dataSnapshot.child(currentUID).child("connections").child("matches").hasChild(ds.getKey())) {
Log.d("rxJava", "onDataChange: " + ds.getKey());
first.add(ds.getKey());
getTagsPreferencesUsers(dataSnapshot.child(ds.getKey()), true);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return rowItems;
}
}).subscribeOn(Schedulers.computation())
.subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
Log.d("rxJava", "Test RxJAVA, onSubscribe");
}
#Override
public void onComplete() {
Log.d("rxJava", "Test RxJAVA, onComplete");
}
#Override
public void onError(Throwable error) {
Log.d("rxJava", "Test RxJAVA, onError");
}
});
and the output is
2020-06-04 23:36:28.797 29515-29515/com.example.tinderapp D/rxJava: Test RxJAVA, onSubscribe
2020-06-04 23:36:28.800 29515-29612/com.example.tinderapp D/rxJava: Test RxJAVA, onComplete
2020-06-04 23:36:29.018 29515-29515/com.example.tinderapp D/rxJava: onDataChange: a4hqGgAJBRTVJOlPp3blNDt5v7q1
2020-06-04 23:36:29.022 29515-29515/com.example.tinderapp D/rxJava: onDataChange: aA9HAOtaB7ao6vzKqqBNp0iaBev2
I would say, this is expected behavior, which is described in the following:
Completable.fromCallable
fromCallable takes a Lambda, which returns a List on subscription. In your case, a database-connection is opened as-well, which is basically fall through, because the callback is registered via callback non-blocking.
subscribeOn
this makes sure, that the subscribeAcutal from fromCallable is called from given scheduler. Therefore the subscribing thread and and emitting thread are decoupled.
You get onComplete first, because the fromCallable will return rowItems immediately and the database connection will stay open, because you did not remove the listener. After a while you get data-base callback logs, because the database connection is still open and the listener is still registered.
You want to actually do something like this:
Single.create<List<Card>> { emitter ->
// register onChange callback to database
// callback will be called, when a value is available
// the Single will stay open, until emitter#onSuccess is called with a collected list.
newUserDb.addListenerForSingleValueEvent {
// do some stuff
emitter.onSuccess(listOf()) // return collected data from database here...
}
emitter.setCancellable {
// unregister addListenerForSingleValueEvent from newUserDb here
}
}.subscribeOn(Schedulers.computation())
.subscribe(
// stuff
)
If you want to have a constant stream of updates, exchange Single with Observable/ Flowable
I have a problem with the waiting requests functionality in the volley library. The debugging led me to the AbstractQueue class in java.util where an element is being added (according to some values in the method that indicate a successful addition to the queue) and simultaneously - not being added(according to the 0 elements in the queue - that don't change their value). The adding method is synchronized. Bellow you can find a detailed description of the situation and my research so far. I will be really thankful if you have a look at them and share if you have any idea what is happening.
I try to automatically retry requests upon any kind of error ( for example - when there is no connection, or the server name is not correct ).
The error handler of a request adds the request back to the static singleton RequestQueue of my app.
RetriableRequestWraper.java
m_request = new StringRequest(
method,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
handleResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
handleError(volleyError);
}
});
public void handleError(VolleyError volleyError)
{
Log.d("Request: ", m_request.toString());
Log.d("handleError: ", volleyError.toString());
if(retriesCount<3)
{
executeRequest();
++retriesCount;
}
else
{
retriesCount = 0;
}
}
public void executeRequest()
{
RequestsManager.getInstance().executeRequest(m_request);
}
public void executeRequest(Request request)
{
Log.d("executeRequest ","m_requestQueue.add(request)");
m_requestQueue.add(request);
}
RequestManager.java
public void executeRequest(Request request)
{
Log.d("executeRequest ","m_requestQueue.add(request)");
m_requestQueue.add(request);
}
This approach doesn't work and when debugging inside the volley library I come to the point where the request could not be added to the mCacheQueue of the RequestQueue class, because the cacheKey of the reuqest is present in the mWaitingRequests Map. So the request is added in the queue in mWaitingRequests map, corresponding to its key. When the previous request is finished - the new one is not added to the queue although these lines are being executed in the RequestQueue class:
synchronized(this.mWaitingRequests) {
String cacheKey1 = request.getCacheKey();
Queue waitingRequests1 = (Queue)this.mWaitingRequests.remove(cacheKey1);
if(waitingRequests1 != null) {
if(VolleyLog.DEBUG) {
VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.", new Object[]{Integer.valueOf(waitingRequests1.size()), cacheKey1});
}
this.mCacheQueue.addAll(waitingRequests1);
}
}
When debugging further this line
this.mCacheQueue.addAll(waitingRequests1);
In the AbstractQueue.java (class in java.util ) the element is being added to the queue, the "modified" value is true, but throughout the hole time the "this" parameter continues to contain 0 elements.
public boolean addAll(Collection<? extends E> c) {
if (c == null)
throw new NullPointerException("c == null");
if (c == this)
throw new IllegalArgumentException("c == this");
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
Inside the offer(E e) method of PriorityBlockingQueue.java the execution of the program stops at line 453.
l452 siftUpUsingComparator(n, e, array, cmp);
l453 size = n+1;
Obviously the returned value is true, but the element is not added. My debugger could not get into the method that adds the element - siftUpUsingComparator(n, e, array, cmp);
I am going to add a timer before retrying my request, and will construct a new one. So I am not really interested in a workaround, I want to understand what and how is happening in this situation. Do you have any idea as to what could be the reason behind this?
The issue is that you try to add the same Request instance once again to the queue it has been added to. This messes up with the queue and the Request itself as it has states. For example if you simply enable markers you'll have a crash. The solution is to either just use the default retry policy or clone the requests.