Firebase StorageReference getActiveUploadTasks return 0 results - android

I am uploading files in the background in Android. And and to cancel it I store the reference. Now when cancel is clicked and I try to get that upload task from the reference it gives 0 results.
Heres my code:
// Storing the reference
StorageReference storeRef = FirebaseStorage.getInstance().getReference().child("Folder1").child("Folder2").child("Filename")
UploadTask task = storeRef.putFile(file);
intent.putExtra("reference", storeRef.toString());
// Retrieving the UploadTask
final String ref = intent.getStringExtra("reference");
if (ref == null) {
return;
}
StorageReference sRef = FirebaseStorage.getInstance().getReferenceFromUrl(ref);
List<UploadTask> taskList = sRef.getActiveUploadTasks(); // taskList.size() ---> 0

You may want to start verifying your database connection and see if the reference is done correctly.
If you can discard that, moving to the next step would be to check the upload method is working, maybe a screenshot or simply checking your database in the console inside Firestore is enough if your files are in the cloud.
As you described, you are uploading files in the background. Following the Handle Activity Lifecycle Changes and using your own implementation would be the best option to correct this behaviour.
If you want to check the full example, it is at the end of the same page. Please be aware this example is for uploading from a stream or data in memory apparently, so you need to add the appropriate “uploading from a file” methods.
Continuing with the downloading of the reference, I would redirect to this page for downloads that continue in the background. In both pages, for uploading and downloading the files, you should add the missing code; this is only compared with the code that you already provided, as many parts are still missing. You should read the guide very carefully to avoid skipping any step. And also check the methods are for the correct data type you are using.
Finally, adding a method for handling errors would be great. As in this case you haven’t found the origin of the issue or got any logs to help us debug your code, this could help you save a lot of time and effort in case you encountered yourself with an issue like this one.

Related

Firestore still take the same time in offline mode as compere to online

I have a fragment in android where I read some data from firestore and than present it in the recycler view. the thing is it still working slow the same when device is go offline. I see in documentation that data persistence is on by default in firestore. here is the code:
firestore.collection(Constants.FireCollections.USERS)
.document(FirebaseAuthRepository().getCurrentUserId())
.collection("categories")
.get().addOnSuccessListener {
for (c in it) {
defaultCategories.add(c.toObject(Category::class.java))
}
Log.i(TAG, "Category: $defaultCategories")
binding.recyclerViewIcons.adapter = CategoryIconAdapter(defaultCategories, this#OutflowTransactionFragment)
}
I need this to work fast at least fast than reading from firestore online mode. and I want the online mode also to fetch the data locally from cached data instead of online for speed so when the device comes online it just update the catched data.
overall the desired result I want the speed.
Thanks for reading this.
The answer is very simple just by redirecting the call from the server to cache will do the magic.
If you are using Firestore in your app then you may notice a tiny delay in when you are getting data from Firestore in offline mode. and this because due to Firebase Firestore checks first in the server the data when it fails to load then again it takes the data from cache.
The problem and the tiny delay is because of two calls. so to overcome the delay we need get data from cache and this very simple by passing Source.CACHE to get() method. The default call is always from server so we need to add cache:
val source = Source.CACHE
firestore.collection(Constants.FireCollections.USERS)
.document(FirebaseAuthRepository().getCurrentUserId())
.collection("categories")
.get(source).addOnSuccessListener {
for (c in it) {
defaultCategories.add(c.toObject(Category::class.java))
}
Log.i(TAG, "Category: $defaultCategories")
binding.recyclerViewIcons.adapter = CategoryIconAdapter(defaultCategories, this#OutflowTransactionFragment)
}
Hope this help, let me know in the comment section if need for more clearification.

How can I show a Downloads List using RecyclerView?

I need to track and update download status(start,pause,play,done) of multiple files in a list that I get from some Api (can't share), onto a RecyclerView.
I am also getting a fileId so each file can be distinguished.
I need download tracking based on the fileId because the Download list is also searchable, it means that the position of items will change and so we can't rely on position based ViewHolder refreshing.
Also if for some reason you close the app, and then go back to the list, search the file, it should show the file download status.
Now there are three options :
a) WorkManager based implementation (how this option can be implemented?)
b) PRDownloader (how this option can be implemented?)
c) Or Android's download manager? (Need to be sure that we need to show progress of multiple files at
same time in a list.)
Which one is better and more reliable?
Which one is the shortest method?
Also can someone share if you have code based on work manager?(how
will you manage to relate fileId to workManger's work id. Do I
need to make a DB table for keeping track of downloads by the Worker?
How to use LiveData from workManager, iff we can in the ViewHolder )
[Reference to Blog/Code/Repos will be most helpful]
Answering my own question(strange!).
I used Fetch Downloader Library
Initialized and used the "Fetch Instance" as a Singleton
Added the download using tag (Maybe I wrongly used the tag. It was supposed to be used for group of downloads. But I used one tag for each download. But it worked.)
Now I did following in the ViewHolder's bind() method :
Took the file Id as a "tag" and removed the FetchObserver linked to
the "tag" i.e. Id using the method of "Fetch Instance" (//will update
the method)
Then again find the download in the "Fetch
Instance" using the Id as "tag".(getDownloadsByTag() method)
If there is a download, you will receive a downloadList whose 0th
element will be your download because I am using one tag per download
and not for group.
Now add the FetchObserver again for that
"tag".
Inside the FetchObserver's lambda, update the progress and other values.
Note : The code can not be shared for non-disclosure purposes. Can share small snippets if you find this confusing.

Firestore/Firebase not able to get images from folder

I have a folder on firebase. which named 'Item'. 'Item' contains 100 images. I just want to fetch just all images Url in the list.
I have tried google documents. Google showing only for a single image. But I just need complete images URLs.
FirebaseStorage firestore = FirebaseStorage.getInstance()
val ref: StorageReference? = firestore.getReference("Item")
I am facing this error =
StorageException has occurred. The object​ does not exist at the location
As i found in documentation this method could help public Task<ListResult> listAll ()
First you need to get needed reference of the folder in your case it is item/
StorageReference mImageStorage = FirebaseStorage.getInstance().getReference().child("items/");
And then with help of listAll() inflate the list of files in it
Here is the description
https://firebase.google.com/docs/reference/android/com/google/firebase/storage/StorageReference.html#listAll()
You're calling firestore.getReference("Item"), which gives you a StorageReference to that folder. The Android, iOS and JavaScript SDKs of Firebase recently added a method to list the files in a folder to StorageReference.
So you need to loop over the ListResult and call getDownloadUrl to get the download URL for each file. Keep min mind that getDownloadUrl is asynchronous, so it returns a task. Get the actual download URL as shown here: How to get the download url from Firebase Storage?

Android Firebase Remote Config initial fetch does not return value

I'm using Firebase Remote Config to fetch data when app first open for the first time. But problem is I cannot fetch data on first start of the app. onComplete() method triggers but returns no value. If I close app and run again it returns value from Remote Config.
Tried to call fetch() in onCreate(), onStart(), onResume(), gave it a second delay with postDelay() still the same, initial fetch is always empty. I know, Remote Config has setDefaults() method to store defaults before it is getting fetched, but setting defaults inside app is not what I want.
It is the way how Remote Config works or am I doing something wrong? The only workaround I found is to add fetch() inside onResume() and call onResume() again inside onCreate(). It results calling onResume() twice. First time by Android system and second time by code.
It there any other way to force Remote Config fetch data on first time run?
UPDATE
Inside onComplete() first I must call firebaseRemoteConfig.activateFetched(); before getting new values from it.
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder().build();
mFirebaseRemoteConfig.setConfigSettingsAsync(configSettings)
.addOnCompleteListener(task -> mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(activity, task1 {
// now cache is updated you can fetch values
String value = mFirebaseRemoteConfig.getString("key");
}));
Start getting the values after config settings are completed
just do that at the app launch, and get values directly anywhere else (eg:
mFirebaseRemoteConfig.getString("key");)
check few points:
Once new variable is created in firebase dashboard, publish it
fetch with cache time set to 0
FirebaseRemoteConfig.getInstance().fetch(0).
I understand that this is an old question - but I ran into exactly the same issue as the asker. After investigating this for a few days I was able to find an answer so I will post it here to help anyone else who is having difficulties.
The first thing to check is that your config settings are published in Firebase. After making a change there is a Publish button on the top right of the console.
I had followed numerous tutorials and guides onto how configure FireBases Remote Config in Unity but despite calling ActivateFetched I got no results.
After investing a great deal of effort trying to figure out why no data was being returned I stumbled across this thread: https://github.com/firebase/quickstart-unity/issues/9
It turns out RemoteConfig doesn't work in Unity and will only use the defaults. To actually using your remote config you must do a build and deploy it onto your target device.
On my Android device all of my remote config is retrieved successfully
Thanks to Pankaj kumar answer, I set firebase.remoteConfig().settings.minimumFetchIntervalMillis = 0 and worked
Simply just try to reset your config locally before getting it to prevent wrong values from getting back.
val firebaseRemoteConfig = Firebase.remoteConfig
firebaseRemoteConfig.reset()
firebaseRemoteConfig.fetch(0)
.addOnCompleteListener { taskFetch ->
if (taskFetch.isSuccessful) {
firebaseRemoteConfig.activate().addOnCompleteListener { task ->
if (task.isSuccessful) {
//do what you want..
}
}
}
}
Just the point is firebaseRemoteConfig.reset() before the activation is called.

Can't set user objectId to parse pointer field

For a new project I was running some tests. For now I have a function in which I am trying to save an object to the parse.com framework and all went well untill I added a user pointer object. The pointer line seems to block my code when I use the current user's objectId as a value for it. Using a random word of the user's email adres however does work. I added my code below.
// Create a data object and store it online.
public void createDataObject(){
ParseObject object = new ParseObject("TestData");
object.put("action", "trial");
object.put("value", "succes?");
object.put("name", ParseUser.getCurrentUser().getUsername());
String pointer = ParseUser.getCurrentUser().getObjectId();
Log.i(TAG, pointer);
object.put("pointer", ParseObject.createWithoutData("_User", pointer));
object.saveEventually();
}
I hope anyone can help me figure it out, help is greatly appreciated!
Update: The problem is not my pointer command but it's the fact I use saveEventually(); If I use saveInBackground it just works but I want to use saveEventually because of possible lost network connection. Does anyone have a clue what could be the problem?
Update 2: Finally decided to delete the app and the installationId of the Parse data browser. Upon reinstalling the app everything started working like it should. I probably had a bad piece of code that got stuck with my installation Id. I hope others with the same problem reach this post fast and don't spend several days searching for an answer!
Update 3: There was a certain function that tried to find a user based on a pointer with the app user's object ID which made the app crash once and than totally unusable. I marked the first answer as the correct answer since it solved my original question but just fyi.. there was more going on than I expected at first.
Just try this:
public void createDataObject(){
ParseObject object = new ParseObject("TestData");
object.put("action", "trial");
object.put("value", "succes?");
object.put("name", ParseUser.getCurrentUser().getUsername());
object.put("pointer", ParseUser.getCurrentUser());
object.saveEventually();
}
No need to get the object ID to set the current User.
Edit:
You can also refer https://stackoverflow.com/a/28403968/2571060 to set pointer
I had a similar issue with the iOS SDK. Are you using 'automatic user creation' ? Cause in that case, ParseUser.getCurrentUser() returns a User object whose objectId is null. According the documentation, it is null until the user or any object related to it is saved. But in my experience, it is not the case, I had to save the user first or I would get an error like 'User can only be created during signUp' or something like this.

Categories

Resources