MediaBrowser(Compat) subscribe/query items with pagination [closed] - android

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
In my Service-side, it has huge data and I want to provide items with pagination way.
Is there any recommended flow to traverse with pagination between MediaBrowser/MediaBrowserService(Compat)?
I want to provide partial data in Result<List<MediaItem>> instead of all data (e.g. all YouTube songs), while browser-side using pagination to pull partial data once a time.

In your
MediaService extends MediaBrowserServiceCompat
#Override
public void onLoadChildren(#NonNull final String parentMediaId, #NonNull final Result<List<MediaItem>> result) {
result.detach();
for (int page = 0; i<pages.size(); i++){
result.sendResult(getList(page));
}
}
public List<MediaItem> getList(int page){
//here create List for page-number == page
}
OR
You can make request in your Fragment or Activity with page
MediaBrowserCompat mediaBrowser = ...;
mediaBrowser.subscribe("1"/*it's page*/, mSubscriptionCallback);
then in your Service make this:
#Override
public void onLoadChildren(#NonNull final String page, #NonNull final Result<List<MediaItem>> result) {
result.detach();
result.sendResult(getList(page));
}

I wanted to do a similar thing in my app - I wanted to return the existing songs on the device but in paginated way. Like you say, a partial result in the onLoadChildren() method. I ended up using Android's new Paging library to do just that. Using the library, I could make the client/UI side asks the service for only the pages the user is interested to see, and then serve only those in the onLoadChildren() method, calling the client's subscribe() method to retrieve it.
I go over it in details in a post I wrote, where I also give code samples to better demonstrate the concept.

Related

Kotlin - Best way to update Android Views using retrieved Firebase data [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to update my Android views using some data that I've got on a Firebase Realtime DB. Since I'm using Kotlin, I've encountered some problems doing this simple thing. I'm not an expert on Realtime DB, I've just discovered that the calls to the DB are made asynchronously, and this means I've got to use the data inside the onDataChange function.
I also discovered that Kotlin doesn't let me change the value of a View that I passed as a parameter to some function (like the one I created to update that View using the data retrieved from the DB). So I'm counting on you for this.
What's the best way to retrieve data from Firebase and use that data to update my Views? I would like to have some clean code, like different functions that do the right thing, without having a pile of code in the onCreate method of my MainActivity.
Maybe something along these lines:
fun fetchFeed(): LiveData<List<Feed>> {
val result: MutableLiveData<List<Feed>> = MutableLiveData()
firestore.collection("feeds")
.addSnapshotListener { collectionSnapshot, exception ->
if (exception != null) {
//...handle error
return#addSnapshotListener
}
if (collectionSnapshot == null || collectionSnapshot.isEmpty) {
//...no data or no collection
return#addSnapshotListener
}
val value: MutableList<Feed> = arrayListOf()
collectionSnapshot.documents.map {
value.add(it.toObject(Feed::class.java))
}
data.postValue(value)
}
return result
}
class FeedFragmentViewModel: ViewModel() {
//ApiService is a singleton or an DAO eg... where your fetchFeed is declared or have access to it
val result: LiveData<List<Feed>> = ApiService.fetchFeed()
}
class FeedFragment: Fragment() {
override onActivityCreated() {
//initialize view model -> in docs
viewModel.result.observe(this, Observer {
myListAdapter.updateList(it)
})
}
}
It is not a complete solution but along these lines I think you should be able to incorporate realtimedb in it. Long story short you want to observe live data which represents the data from realtime db. When ever those c hange your callback in observer gets called where you can update the UI accordingly

Future String in flutter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So I have a function that returns a value that is of future. When this function executes I want to extract the string from the future. How should I do this?
Future<String> coverImage(id, space) {
String link = 'https://cdn.contentful.com/spaces/$space/assets/$id?access_token=1d4932ce2b24458e85ded26532bb81184e0d79c1a16c5713ec3ad391c2e8f5b3';
return http.get(link).then((response) => decodeToImage(decodeJson(response.body)));
}
this function return Future<String>, i want to extract to string when i am using with image widget
Future someMethod() async {
String s = await someFuncThatReturnsFuture();
}
or
someMethod() {
someFuncTahtReturnsFuture().then((s) {
print(s);
});
}
There is no way to go from async (Future) to sync execution.
async/await is only syntactic sugar to make the code look more like sync code, but as you see in my first example, someMethod will return a Future and if you want to use the string s on the call site, you have to use async/await or then() there.

MVC pattern with Firebase [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a simple question. I am developing an Android application that uses as backend Firebase realtime database. I was wondering if can it be said that my app is built following the MVC pattern, although I do not have my own logic, my own server, I am using the API from Firebase. Thanks!
Yes, you can use MVC pattern with Firebase. With Firebae it's even simpler. You can create a model class in which you can declare all the variables you need. This can include also other classes. Create all the constructors that you need. Add public setters and public getters and you'll have your complete model class or your POJO. Don't forget to add the no argument constructor needed for Firebase.
Here is an example of an user model class with only two fields.
public class UserModel implements Serializable {
private String userEmail;
private String userName;
public UserModel() {}
public void setUserEmail(String userEmail) {this.userEmail = userEmail;}
public String getUserEmail() {return userEmail;}
public void setUserName(String userName) {this.userName = userName;}
public String getUserName() {return userName;}
}
Every change that is made in your Firebase database is triggerd in real time in your user interface.
I recomand you reading the official documentation for Firebase. Here is how to add Firebase to your Android Project and here is how you can set up Firebase Realtime Database for Android. And here is how you can use FirebaseUI for Android.
Hope it helps.

How to insert/remove items from RecyclerView using MVP [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
While using recycler view in MVP, where do you guys keep a reference to the list? I have a ChatManager which can talk to different presenters. I keep two copies of the list of messages , one in the ChatManager and the other in the Presenter. The adapter, view, and the presenter share the same list.
The reason I have a reference to the list of messages in the Presenter is because I have some business logic for removal and scrolling which I want to handle from the presenter.
So now when I have to remove a message, the presenter decides what item to remove and removes it from the list. Now it needs to let the view know that a message has been removed. So in that case, should it say view.remove(message) or view.remove(index)? The view should not try and remove the message again since the presenter has already done that.
Same thing for other operations like scrolling or adding. If new messages are received, the presenter adds the newMessages to allMessages and then has to update the view. Ideally, the presenter should be calling view.onMessagesReceived(List<Message> messages) instead of view.onMessageReceived(int newMessagesCount, int indexAddedAt). The second method is really weird and not verbose at all. But since the list is being shared, the view only needs to call notifyItemInserted and hence only needs to know about the count and the index.
What is the best way to handle this?
So as Amir suggested, one way to go about it is expose a method from the adapter to update the data, and call notifyDataSetChanged. I really didn't want to use this method as it unnecessarily refreshes the entire data set when I only wanted to add/update messages in the adapter.
Another way was to expose a method addNewMessages(int count, int index) in the view, so that the adapter knows which indices to notify insert/update for, which I again didn't want to use because then the API seems weird as addNewMessages should actually be passed the list of new messages instead of the index and count.
The solution I went with was to actually pass the entire updated list from the Presenter to the View, which eventually passes it to the Adapter. The Adapter then uses DiffUtil to figure out the diff between the old list and the new list and calls only the notifyItemInserted/notifyItemChanged methods instead of notifyDataSetChanged every time.
This helps because now the API looks like this:
ChatPresenter {
interface View {
...
void updateMessages(List<Message> messages);
}
Activity implements ChatPresenter.View {
...
#Override
void updateMessages(List<Message> messages) {
chatsAdapter.update(messages);
}
}
ChatsAdapter {
...
public update(List<Message> messages) {
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ChatMessageDiffCallback(this.messages, updatedMessages));
this.messages = updatedMessages;
diffResult.dispatchUpdatesTo(this);
}
}
the best practice is to update adapter list from the view implementation but the function for this task should be on view interface and implemented in view implementation (e.g. fragment or activity)
firstly add a method to your adapter like below
public void updateItemsList(ItemsList itemsList)
{
//update the list of your items assume your items list is named "mItemsList"
this.mItemsList = itemsList;
notifyDataSetChanged();
}
then in your view interface add a method to update the adapter list like below
public void updateAdapterList(ItemsList itemsList);
then in your view implementation (fragment or activity) add this:
#Override
public void updateAdapterList(ItemsList itemsList);
{
//update the adapter list -- assume your adapter is named "mAdapter"
mAdapter.updateItemsList(itemsList);
}
now you can access this method (updateAdapterList()) wherever you have an object of type view interface.

Android Event Bus Alternative [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Context: In a previous Android application I have developed, I used an event bus (otto by Square) to handle async task results (for example: the result of a server request is posted on the bus and somewhere in the application I intercept that response). Although it did the job, in some article I've read it was mentioned that using such a bus is rather a bad idea as it's considered an antipattern.
Why is that so? What are some alternatives to using an event bus when dealing with results of async operations? I know that, most of the time, there is no standard way to handle things, but is there "a more canonical" method?
Use RxJava and Retrofit for asynchronous network calls. RxJava provide out of the box support for Retrofit.
Return Observable from retrofit interface.
#GET("/posts/{id}")
public Observable<Post> getData(#Path("id") int postId);
Use it in your activity class -
retrofitBuilderClass.getApi()
.getData()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer < List < Data >> () {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(List < Data > data) {
// Display data
}
});

Categories

Resources