Object List on RecyclerView - android

I'm having a little big problem on Android Studio. A have an object "Sport" that can have multiple lessons. So inside this object there is a list.
public class Sport implements Serializable {
private String cid;
private String cname;
String csportpic;
long ccreatedat;
List<Lesson> lessons;
public Sport() {
}
The object has gets and sets for each element. So the data coming from Firebase in well placed.
In a recycleview I want to display the lessons data and also some variable of the object sport(cname, cid), so I'm passing to the recycleview constructor the object Sport.
Do you have any ideia how to perform a loop through lesson List in a recyclerview? Can it be done inside onBindViewHolder?

Sorry, got it working.
For some reason the first loop was not working correctly. Perhaps the Object was not well written, or the query to the database.
public void onBindViewHolder(#NonNull final CoachVH holder, final int position)
{
for (Lesson lesson:sportlesson.get(position).getLessons())
{
holder.classid.setText(String.valueOf(new SimpleDateFormat("dd-MM-yyyy HH:mm").format(lesson.getLessonTime())));
holder.classname.setText(sportlesson.get(position).getCname());
holder.classaddress.setText(String.valueOf(lesson.getLessonAddress()));
holder.classprice.setText(String.valueOf(lesson.getLessonPrice()));
}
}

Related

Sorting Data in Firebase

I'm using Firebase listview at its shown below and its working like a charm but the problem is it displays the last pushed key in the child("Posts") at the end of my listview(lv) I want the last pushed key to be displayed above all or if i can sort it by date.
query = ref.child("Posts").orderByKey();
FirebaseListAdapter<ChatRoomJ> adapter = new FirebaseListAdapter<ChatRoomJ>(
ChatRoom.this,
ChatRoomJ.class,
R.layout.lvchatroom,query
) {
#Override
protected void populateView(View v, ChatRoomJ model, final int position) {
final String date = model.getDate();
final String displayName = model.getDisplayName();
((TextView) v.findViewById(R.id.displayname)).setText(displayName);
((TextView) v.findViewById(R.id.datel)).setText(date);
});
}
};
lv.setAdapter(adapter);
Method 1:
There is no way to reorder the data with your current code, unless you make your own class that extends FirebaseListAdapter and override the getItem() method. This is a great and easy way to do it (courtesy of Monet_z_Polski). I used the same trick with perfect results so far.
public abstract class ReverseFirebaseListAdapter<T> extends FirebaseListAdapter<T> {
public ReverseFirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, Query ref) {
super(activity, modelClass, modelLayout, ref);
}
public ReverseFirebaseListAdapter(Activity activity, Class<T> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
}
#Override
public T getItem(int position) {
return super.getItem(getCount() - (position + 1));
}
Then when you make the adapter, you use your new custom class that modifies the starting position for each item that is sent to the list.
Method 2:
The other way would be to read the data in to your app (probably into an ArrayList or something like that) and reorder the data on the client before populating the list with the properly ordered data. This can be as easy as reading the data into the ArrayList with a start index of 0 for each item. Something like chatRoomList.add(0, nextChatRoom); for example. That way when you populate the list on the screen it will be in the order you want.
There are other methods involving making a custom adapter, but I personally think that would be more complicated than these two methods. The first is my favorite.

Android: Using spinner to update an RealmObject

I have two RealmObjects, something like,
public class Dog extends RealmObject {
#Required
private String name;
private int age;
}
public class Person extends RealmObject {
#Required
private String name;
private Dog dog; // A person has only one dog (a relationship)
}
In one of the activities, I want to let the user select the dog for the given person.
I thought I will use a spinner.
I also got a sample code from Realm-Examples, that did similar stuff for the ListView.
public class DogListAdapter extends RealmBaseAdapter<Dog> implements SpinnerAdapter
So far everything works fine. The spinner list automatically updates to reflect changes in the realm.
But, when I have to first display the GUI, I want to set the selected item to the current Person.dog.name.
What is the best way to do this?
I am doing something like this in onResume():
dogNameSpinner.setSelection(RealmUtils.resultIndexOf(dogsResult, person.getDog()));
where, the RealmUtils.resultIndexOf is a small utility function:
public static int resultIndexOf(RealmResults results, RealmObject obj) {
for(int i=0; i < results.size(); i++ ) {
if(results.get(i) == obj) {
return i;
}
}
return 0;
}
This does not work. I suspect may be because the realm.changeListeners get called and the spinner resets to the first item whenever items are updated.. ??
I suppose there could be a better way to do this as it should be a common model-view use case.

Android view not updating on main thread

I have an array of data model items in the application class. My first activity has a broadcast receiver that alters the values of items in the list (via push if you are curious).
I have two kinds of visual representation for a model item and I want to be able to update the view whenever I get a push, regardless of where I am in the application.
My solution was that every model item has an interface reference to their view classes, so when I update the model, the model tells the interfaces to update the views.
My problem is that the views do not update, and I have verified, the code is running on the main thread.
public interface IWidget {
void setValue(int value);
}
public class MyView implements IWidget {
#Override
void setValue(int value){
}
}
public class Model{
int value;
IWidget iWidget;
public void setWidget(IWidget iWidget){
this.iWidget = iWidget;
}
public void setValue(int value){
this.value = value;
iWidget.setValue(value);
}
}
I was generating a view twice on 2 fragments of view pager, so I was not looking at the right one. The instance that was updating was the last one (not on the fragment I was initially looking on).

Detailed view of list row

In my project have to populate the list view from local database.I have implemented it.When I click the row in list item I need to show all the details in list row in next activity.I implemented custom list adapter.I not yet started to code for detailed list row.How can I pass all details in single row to another activity.Can anyone help me?
You can set the information in tags of textviews of your custom list and pass them through intents.
one thing that you can do is just pass the id (PK) of the item . Then on next activity you can fetch it again from database.
another options is that you can create a class with all the data you want to forward as class'members and serialize the object and send it along with the intent.
here is a example
public class ActivityExtra implements Parcelable {
public Integer a=0;
public String b="";
private GameActivityExtra(Parcel in) {
this.a = in.readInt();
this.b = in.readString();
}
public GameActivityExtra() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(a);
dest.writeString(b);
}
public static final Parcelable.Creator<GameActivityExtra> CREATOR = new Parcelable.Creator<GameActivityExtra>() {
public GameActivityExtra createFromParcel(Parcel in) {
return new GameActivityExtra(in);
}
public GameActivityExtra[] newArray(int size) {
return new GameActivityExtra[size];
}
};
}
now create instance of this class in your activity . and use intent.putextra(...) to put it . and get the same object while receiving it.
Use #nitesh goel answer to make your object class parcelabe.
Then onitemclick use
intent.putExtra("object", object);
to send your object to other activity.
And in corresponding activity use
intent.getParcelableExtra("object");
to get your object. then you can get everything of that object.

sorting custom object array on two fields

I'm sorting an array of custom objects (ListData[]) on two fields. I want it to be sorted by theme, and them by name. I thought i made a nice comparator in the custom object class and that i could use Arrays.sort(ld) to make my code working and sorting my array. But apparently im doing something wrong...
my custom object:
public class ListData implements Comparable<ListData>{
public int venueID;
public String name;
public String photoUrl;
public String tip;
public String theme;
#Override
public int compareTo(ListData ld0) {
return this.venueID- ld0.venueID;
}
public static Comparator<ListData> ListDataThemeAndNameComparator = new Comparator<ListData>() {
#Override
public int compare(ListData ld1, ListData ld2) {
String compareTheme1 = ld1.theme.toUpperCase();
String compareTheme2= ld2.theme.toUpperCase();
String compareName1 = ld1.name.toUpperCase();
String compareName2= ld2.name.toUpperCase();
//ascending
int comp = compareTheme1.compareTo(compareTheme2); // comp themes
if(comp==0){ // same theme
comp= compareName1.compareTo(compareName2); // compare names
}
return comp;
}
};
}
And in my main activity i have:
ListData ld[]= new ListData[jsonResponse.size()];
(some code filling my ListData array)
Arrays.sort(ld, ListData.ListDataThemeAndNameComparator); // compare by theme and then by name
Does anyone know what i'm doing wrong?
I edited my code But still it fails, now on a nullpointerexception on the compareTheme1 = ld1.theme.toUpperCase();. But i am sure my array is not empty, i logged it the line before sorting it and its filled with about 500 items.
Your ListData object should implements Comparable not Comparator interface.
EDIT:
To make things clear, you can sort an array by Array.sort(). To make custom sort, you can specify your comparator in Array.sort(), if you don't do that, array will be sorted in natural order which you can define by implementing Comparable interface. So you have two options how to custom sort:
by using custom comparator and specifying it in Array.sort()
by implementing Comparable interface to your items
I would suggest you to go with implementing Comparable. You save memory by not creating new comparator objects and Comparator is useful if you are comparing objects of different types which is not your case.

Categories

Resources