I have just jumped to android with a very limited knowledge about recyclerview. I have used a a bit, but faced a situation where setting a text inside onBindViewHolder.Please bear with me.Check the following codes:
1.This is the json, here:
[
{
"restaurantSubscriptionType_Id": 1,
"noOfDaysPlan": "1 Day Trial Meal",
"restaurantSubscriptionEntity": [
{
"restaurantSubscriptionId": 39,
"subscriptionPlan": "Breakfast & Lunch",
"subscriptionImagePath": null,
"subscriptionDays": 1,
"subscriptionAmount": 150,
"restaurant_Subscription_Type_Id": 1
}
],
"restaurantId": 224
},
{
"restaurantSubscriptionType_Id": 2,
"noOfDaysPlan": "5 Days Weekly Plan",
"restaurantSubscriptionEntity": [
{
"restaurantSubscriptionId": 40,
"subscriptionPlan": "Breakfast & Lunch",
"subscriptionImagePath": null,
"subscriptionDays": 5,
"subscriptionAmount": 650,
"restaurant_Subscription_Type_Id": 2
},
{
"restaurantSubscriptionId": 41,
"subscriptionPlan": "Only Lunch",
"subscriptionImagePath": null,
"subscriptionDays": 5,
"subscriptionAmount": 500,
"restaurant_Subscription_Type_Id": 2
}
],
"restaurantId": 224
}
]
I have pojo2schema site
2.RestaurantSubscriptionEntity
public class RestaurantSubscriptionEntity {
private Integer restaurantSubscriptionId;
private String subscriptionPlan;
private String subscriptionImagePath;
private Integer subscriptionDays;
private Long subscriptionAmount;
private Integer restaurantSubscriptionTypeId;
public RestaurantSubscriptionEntity(){
}
public Integer getRestaurantSubscriptionId() {
return restaurantSubscriptionId;
}
public void setRestaurantSubscriptionId(Integer restaurantSubscriptionId) {
this.restaurantSubscriptionId = restaurantSubscriptionId;
}
public String getSubscriptionPlan() {
return subscriptionPlan;
}
public void setSubscriptionPlan(String subscriptionPlan) {
this.subscriptionPlan = subscriptionPlan;
}
public String getSubscriptionImagePath() {
return subscriptionImagePath;
}
public void setSubscriptionImagePath(String subscriptionImagePath) {
this.subscriptionImagePath = subscriptionImagePath;
}
public Integer getSubscriptionDays() {
return subscriptionDays;
}
public void setSubscriptionDays(Integer subscriptionDays) {
this.subscriptionDays = subscriptionDays;
}
public Long getSubscriptionAmount() {
return subscriptionAmount;
}
public void setSubscriptionAmount(Long subscriptionAmount) {
this.subscriptionAmount = subscriptionAmount;
}
public Integer getRestaurantSubscriptionTypeId() {
return restaurantSubscriptionTypeId;
}
public void setRestaurantSubscriptionTypeId(Integer restaurantSubscriptionTypeId) {
this.restaurantSubscriptionTypeId = restaurantSubscriptionTypeId;
}
3.DemoItemAll:
public class DemoItemAll {
private Integer restaurantSubscriptionTypeId;
private String noOfDaysPlan;
private List<RestaurantSubscriptionEntity> restaurantSubscriptionEntity = new ArrayList<RestaurantSubscriptionEntity>();
private Long restaurantId;
public DemoItemAll(){
}
public Integer getRestaurantSubscriptionTypeId() {
return restaurantSubscriptionTypeId;
}
public void setRestaurantSubscriptionTypeId(Integer restaurantSubscriptionTypeId) {
this.restaurantSubscriptionTypeId = restaurantSubscriptionTypeId;
}
public String getNoOfDaysPlan() {
return noOfDaysPlan;
}
public void setNoOfDaysPlan(String noOfDaysPlan) {
this.noOfDaysPlan = noOfDaysPlan;
}
public List<RestaurantSubscriptionEntity> getRestaurantSubscriptionEntity() {
return restaurantSubscriptionEntity;
}
public void setRestaurantSubscriptionEntity(List<RestaurantSubscriptionEntity> restaurantSubscriptionEntity) {
this.restaurantSubscriptionEntity = restaurantSubscriptionEntity;
}
public Long getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Long restaurantId) {
this.restaurantId = restaurantId;
}
4.Here my class which extends RecyclerView
public class DemoAdapter extends RecyclerView.Adapter<DemoAdapter.MyViewHolder> {
private List<DemoItemAll> demoItemAllArrayList = new ArrayList<>();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title_tv,price_tv;
private Button drop_down_button;
public MyViewHolder(View itemView) {
super(itemView);
title_tv = (TextView) itemView.findViewById(R.id.day_plan_demo_tv_id);
price_tv = (TextView) itemView.findViewById(R.id.price_demo_tv_id);
drop_down_button = (Button) itemView.findViewById(R.id.demo_drop_down_btn_id);
}
}
public DemoAdapter(List<DemoItemAll> demoItemAllArrayList) {
this.demoItemAllArrayList = demoItemAllArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.demo_adapter, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
DemoItemAll demoItemAll=new DemoItemAll();
//noOfDays
holder.title_tv.setText(demoItemAll.getNoOfDaysPlan());
}
#Override
public int getItemCount() {
return demoItemAllArrayList.size();
}
}
now here inside onBindView,I need to set this but "subscriptionAmount"
belongs to RestaurantSubscriptionEntity class.How do I access it
holder.price_tv.setText //subscriptionAmount.
You just create new empty DemoItemAll object.
You need to use
DemoItemAll demoItemAll = demoItemAllArrayList.get(position);
instead of
DemoItemAll demoItemAll = new DemoItemAll();
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
DemoItemAll demoItemAll = demoItemAllArrayList.get(position);
List<RestaurantSubscriptionEntity> entity = demoItemAll.getRestaurantSubscriptionEntity();
holder.title_tv.setText(demoItemAll.getNoOfDaysPlan());
holder.price_tv.setText(String.valueOf(entity.getSubscriptionAmount()))
}
Related
I am a newbie in recyclerview. I have created my generic adapter for different properties by following the #SebastienRieu's answer, i.e. This link. The problem is that I want to instantiate the adapter and set it to my recyclerview. How Do I do that?
Here, 2nd parameter is context. What should replace the 1st paramenter with?
GenericModelAdapter adapter= new GenericModelAdapter(??, this)
recyclerView.setAdapter(adapter);
Any help is appreciated.
My PostModelClass:
public class PostsModelClass {
int userId;
int id;
String title;
#SerializedName("body")
String textBody;
public int getUserId() {
return userId;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String getTextBody() {
return textBody;
}
}
Similarly, here's my CommentsModelclass:
public class CommentsModelClass {
String postId;
String id;
String name;
String email;
#SerializedName("body")
String textBody;
public String getPostId() {
return postId;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getTextBody() {
return textBody;
}
And here's my adapter:
public class GenericModelAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_POSTS = 10;
private static final int TYPE_COMMENTS = 11;
private static final int TYPE_PHOTOS = 12;
private static final int TYPE_USERS = 13;
private List<GenericViewModel> mItems;
public GenericModelAdapter(List<GenericViewModel> items, Context context) {
this.mItems = items;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
GenericViewModel genericItems = mItems.get(position);
if (genericItems.isPostsModel()) {
return TYPE_POSTS;
} else if (genericItems.isCommentsModel()) {
return TYPE_COMMENTS;
} else if (genericItems.isPhotosModel()) {
return TYPE_PHOTOS;
} else {
return TYPE_USERS;
}
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
PostViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
public static class CommentsViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
CommentsViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
public static class PhotosViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
PhotosViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
public static class UsersViewHolder extends RecyclerView.ViewHolder {
TextView textViewResult;
UsersViewHolder(#NonNull View itemView) {
super(itemView);
textViewResult = itemView.findViewById(R.id.textViewResult);
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
if (viewType == TYPE_POSTS) {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new PostViewHolder(rootView);
} else if (viewType == TYPE_COMMENTS) {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new CommentsViewHolder(rootView);
} else if (viewType == TYPE_PHOTOS) {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new PhotosViewHolder(rootView);
} else {
View rootView = inflater.inflate(R.layout.single_item, parent, false);
return new UsersViewHolder(rootView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
GenericViewModel genericViewModel = mItems.get(position);
if (genericViewModel.isPostsModel()) {
onBindPost(holder, genericViewModel.getPostsModelClass());
} else if (genericViewModel.isCommentsModel()) {
//onBindComments(holder, genericViewModel.getCommentsModelClass());
} else if (genericViewModel.isPhotosModel()) {
//onBindPhotos(holder, genericViewModel.getPhotosModelClass());
} else if (genericViewModel.isUsersModel()) {
//onBindUsers(holder, genericViewModel.getUsersModelClass());
}
}
private void onBindPost(RecyclerView.ViewHolder holder, PostsModelClass postsModelClass) {
String content = "User ID: " + postsModelClass.getUserId() +
"\nID: " + postsModelClass.getId() +
"\nTitle: " + postsModelClass.getTitle() +
"\nBody: " + postsModelClass.getTextBody();
((PostViewHolder) holder).textViewResult.setText(content);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
And lastly, My GenericViewModel:
public class GenericViewModel {
private PostsModelClass mPostsModelClass;
private CommentsModelClass mCommentsModelClass;
private PhotosModelClass mPhotosModelClass;
private UsersModelClass mUsersModelClass;
private GenericViewModel(PostsModelClass postsModelClass, CommentsModelClass commentsModelClass, PhotosModelClass photosModelClass, UsersModelClass usersModelClass) {
this.mPostsModelClass = postsModelClass;
this.mCommentsModelClass = commentsModelClass;
this.mPhotosModelClass = photosModelClass;
this.mUsersModelClass = usersModelClass;
}
public boolean isPostsModel() {
return mPostsModelClass != null;
}
public boolean isCommentsModel() {
return mCommentsModelClass != null;
}
public boolean isPhotosModel() {
return mPhotosModelClass != null;
}
public boolean isUsersModel() {
return mUsersModelClass != null;
}
public static GenericViewModel getPostsInstance(PostsModelClass modelClass) {
return new GenericViewModel(modelClass, null, null, null);
}
public static GenericViewModel getCommentsInstance(CommentsModelClass modelClass) {
return new GenericViewModel(null, modelClass, null, null);
}
public static GenericViewModel getPhotosInstance(PhotosModelClass modelClass) {
return new GenericViewModel(null, null, modelClass, null);
}
public static GenericViewModel getUsersInstance(UsersModelClass modelClass) {
return new GenericViewModel(null, null, null, modelClass);
}
public PostsModelClass getPostsModelClass() {
return mPostsModelClass;
}
public CommentsModelClass getCommentsModelClass() {
return mCommentsModelClass;
}
public PhotosModelClass getPhotosModelClass() {
return mPhotosModelClass;
}
public UsersModelClass getUsersModelClass() {
return mUsersModelClass;
}
}
Yes, I haven't shared the model classes for Posts and Users. They are similar to these model classes and I'd implement them later.
Here's the error I'm facing:
Based on the reference you gave in the question, you need a model that contains all your different properties like EventViewModel in the link and populate the list based on the viewType.
ArrayList<EventViewModel> eventList = "YOUR LIST"
GenericModelAdapter adapter= new GenericModelAdapter(eventList, this)
It must be ArrayList of different collected properties:
GenericModelAdapter adapter= new GenericModelAdapter(ArrayList<YourModel> eventList, this)
Your model:
public class YourModel() {
private Property1 mProperty1;
private Property2 mProperty2;
private YourModel(Property1 property1, Property2 property2) {
this.mProperty1 = property1;
this.mProperty2 = property2;
}
public boolean isProperty1() {
return mProperty1 != null
}
public boolean isProperty2() {
return mProperty2 != null
}
public static YourModel getProperty1Instance(Property1 property1) {
return new YourModel(property1, null);
}
public static EventViewModel getProperty2Instance(Property1 property2) {
return new YourModel(null, property2);
}
public Property1 getProperty1() {
return mProperty1;
}
public Property2 getProperty2() {
return mProperty2;
}
}
I have added data in firebase. All i have to do is get that data in recyclerview. i have done this many type, but this time it is not showing and i don't know the reason because it is not showing in log. Can any one help?
here's my Activity where the RV is located
rvsalonlist is recyclerview
public void firebasedata() {
FirebaseRecyclerOptions<salonList> options =
new FirebaseRecyclerOptions.Builder<salonList>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("salon"), salonList.class)
.build();
adapter = new SalonListAdapter(options);
rvSalonList.setAdapter(adapter);
adapter.startListening();
}
This is the adapter
public class SalonListAdapter extends FirebaseRecyclerAdapter<salonList,SalonListAdapter.myviewholder> {
public SalonListAdapter(#NonNull FirebaseRecyclerOptions<salonList> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull myviewholder holder, int position, #NonNull salonList model) {
holder.tvSalonName.setText(String.valueOf(model.getSalonName()));
holder.tvSalonAddress.setText(String.valueOf(model.getSalonAddresss()));
Glide.with(holder.ivSalonImage.getContext()).load(model.getImageUrl()).into(holder.ivSalonImage);
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_salon,parent,false);
return new myviewholder(view);
}
class myviewholder extends RecyclerView.ViewHolder{
ImageView ivSalonImage;
TextView tvSalonName, tvSalonMobileNumber, tvSalonAddress;
public myviewholder(#NonNull View itemView) {
super(itemView);
ivSalonImage = itemView.findViewById(R.id.ivSalonImage);
tvSalonName = itemView.findViewById(R.id.tvSalonName);
tvSalonMobileNumber = itemView.findViewById(R.id.tvSalonMobileNumber);
tvSalonAddress = itemView.findViewById(R.id.tvSalonAddress);
}
}
}
Heres the model class .
[![public class salonList {
private String imageUrl, salonName, ownerName, salonEmail, salonMobileNumber, salonAddresss, salonOpenTime, salonCloseTime;
public salonList() {
}
public salonList(String imageUrl, String salonName, String ownerName, String salonEmail, String salonMobileNumber, String salonAddresss, String salonOpenTime, String salonCloseTime) {
this.imageUrl = imageUrl;
this.salonName = salonName;
this.ownerName = ownerName;
this.salonEmail = salonEmail;
this.salonMobileNumber = salonMobileNumber;
this.salonAddresss = salonAddresss;
this.salonOpenTime = salonOpenTime;
this.salonCloseTime = salonCloseTime;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getSalonName() {
return salonName;
}
public void setSalonName(String salonName) {
this.salonName = salonName;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getSalonEmail() {
return salonEmail;
}
public void setSalonEmail(String salonEmail) {
this.salonEmail = salonEmail;
}
public String getSalonMobileNumber() {
return salonMobileNumber;
}
public void setSalonMobileNumber(String salonMobileNumber) {
this.salonMobileNumber = salonMobileNumber;
}
public String getSalonAddresss() {
return salonAddresss;
}
public void setSalonAddresss(String salonAddresss) {
this.salonAddresss = salonAddresss;
}
public String getSalonOpenTime() {
return salonOpenTime;
}
public void setSalonOpenTime(String salonOpenTime) {
this.salonOpenTime = salonOpenTime;
}
public String getSalonCloseTime() {
return salonCloseTime;
}
public void setSalonCloseTime(String salonCloseTime) {
this.salonCloseTime = salonCloseTime;
}
}
Database Screenshot
your model class variable names and firebase attributes name are not same. use same name in both places.
for example in firebase use salonName instead of name. similarly for other attributes as well
The names have to be identical
For eg, you have ownerName in the class but ownername in the database. Those should all be identical to the ones you have in your class.
im using thoughtbot expandable recyclerview (https://github.com/thoughtbot/expandable-recycler-view) and i can't get to expand groups on clicks. also i know that the child items are not even binded (not sure if they were supposed to bind or only on expanding of group.)
my view holders:
public class PlaylistViewHolder extends GroupViewHolder {
private TextView mPlaylistName, mPlaylistCount;
private ImageView arrow;
ExpandableListView.OnGroupClickListener listener;
public PlaylistViewHolder(View itemView) {
super(itemView);
mPlaylistName = itemView.findViewById(R.id.playlistNameView);
mPlaylistCount = itemView.findViewById(R.id.videosCount);
arrow = itemView.findViewById(R.id.expandBtn);
}
public void setCurrentPlaylist(YoutubePlaylist playlist){
Log.e("###",playlist.toString());
mPlaylistName.setText(playlist.getListTitle());
mPlaylistCount.setText("5");
}
}
/////
public class VideoViewHolder extends ChildViewHolder {
TextView mVideoName,mVideoLinkView;
ImageView mVideoThumb;
public VideoViewHolder(View itemView) {
super(itemView);
mVideoName = itemView.findViewById(R.id.videoNameView);
mVideoThumb = itemView.findViewById(R.id.videoThumb);
mVideoLinkView = itemView.findViewById(R.id.videoLinkView);
}
public void onBind(YoutubeVideo video){
Log.e("###","Video binded!!!!!!!");
mVideoName.setText(video.getTitle());
mVideoLinkView.setText(video.getThumbnailLink());
}
}
my classes:
the group class:
public class YoutubePlaylist extends ExpandableGroup<YoutubeVideo> {
#SerializedName("ListTitle")
private String title;
#SerializedName("ListItems")
private ArrayList<YoutubeVideo> videos;
public YoutubePlaylist(String title, List<YoutubeVideo> items) {
super(title, items);
this.title = title;
}
public String getListTitle() {
return title;
}
public void setListTitle(String listTitle) {
this.title = listTitle;
}
public ArrayList<YoutubeVideo> getVideos() {
return videos;
}
public void setVideos(ArrayList<YoutubeVideo> videos) {
this.videos = videos;
}
#Override
public String toString() {
return "YoutubePlaylist{" +
"title='" + title + '\'' +
", videos=" + videos +
'}';
}
}
my child class:
class YoutubeVideo implements Parcelable {
#SerializedName("Title")
private String title;
#SerializedName("link")
private String linkToVideo;
#SerializedName("thumb")
private String thumbnailLink;
public YoutubeVideo(String title, String linkToVideo, String thumbnailLink) {
this.title = title;
this.linkToVideo = linkToVideo;
this.thumbnailLink = thumbnailLink;
}
protected YoutubeVideo(Parcel in) {
title = in.readString();
linkToVideo = in.readString();
thumbnailLink = in.readString();
}
public static final Creator<YoutubeVideo> CREATOR = new Creator<YoutubeVideo>() {
#Override
public YoutubeVideo createFromParcel(Parcel in) {
return new YoutubeVideo(in);
}
#Override
public YoutubeVideo[] newArray(int size) {
return new YoutubeVideo[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLinkToVideo() {
String newLink;
if (linkToVideo.contains(" ")) {
newLink = linkToVideo.replaceAll(" ", "");
return newLink;
}
return linkToVideo;
}
public void setLinkToVideo(String linkToVideo) {
this.linkToVideo = linkToVideo;
}
public String getThumbnailLink() {
String fixedThumb=thumbnailLink;
if (thumbnailLink.contains(" ")) {
fixedThumb = thumbnailLink.replaceAll(" ", "");
return fixedThumb;
}
return thumbnailLink;
}
public void setThumbnailLink(String thumbnailLink) {
this.thumbnailLink = thumbnailLink;
}
#Override
public String toString() {
return "YoutubeVideo{" +
"title='" + getTitle() + '\'' +
", linkToVideo='" + getLinkToVideo() + '\'' +
", thumbnailLink='" + getThumbnailLink() + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(linkToVideo);
dest.writeString(thumbnailLink);
}
}
the adapter:
public class PlaylistAdapter extends
ExpandableRecyclerViewAdapter<PlaylistViewHolder, VideoViewHolder> {
public PlaylistAdapter(List<? extends ExpandableGroup> groups) {
super(groups);
}
#Override
public PlaylistViewHolder onCreateGroupViewHolder(ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.playlist_item,
parent, false);
return new PlaylistViewHolder(view);
}
#Override
public VideoViewHolder onCreateChildViewHolder(ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.video_item,
parent,
false);
return new VideoViewHolder(view);
}
#Override
public void onBindChildViewHolder(VideoViewHolder holder, int flatPosition,
ExpandableGroup group, int childIndex) {
YoutubeVideo video = (YoutubeVideo) group.getItems().get(childIndex);
holder.onBind(video);
}
#Override
public void onBindGroupViewHolder(PlaylistViewHolder holder, int
flatPosition, ExpandableGroup group) {
holder.setCurrentPlaylist((YoutubePlaylist) group);
}
}
main activity:
public class MainActivity extends AppCompatActivity {
RecyclerView videoListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetJsonFromUrl getJsonService = RetrofitInstance.getRetrofitInstance().create(GetJsonFromUrl.class);
Call<JsonObject> call = getJsonService.getJSON();
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.isSuccessful()){
JsonArray array = response.body().getAsJsonArray("Playlists");
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<YoutubePlaylist>>(){}.getType();
ArrayList<YoutubePlaylist> youtubePlay = gson.fromJson(array, type);
for(YoutubePlaylist playlist : youtubePlay){
ArrayList<YoutubeVideo> videos = playlist.getVideos();
Log.e("###",videos.toString());
}
setArrayToAdapter(youtubePlay);
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
}
private void setArrayToAdapter(ArrayList<YoutubePlaylist> youtubePlay) {
videoListView = findViewById(R.id.videosView);
LinearLayoutManager manager = new LinearLayoutManager(this);
PlaylistAdapter adapter = new PlaylistAdapter(youtubePlay);
videoListView.setLayoutManager(manager);
videoListView.setAdapter(adapter);
}
}
playlist object output example:
YoutubePlaylist{title='Zen Work Music', videos=[YoutubeVideo{title='HEALING ZEN Music', linkToVideo='https://www.youtube.com/watch?v=SbCpzWMWb68', thumbnailLink='https://i.ytimg.com/vi_webp/SbCpzWMWb68/mqdefault.webp'}, YoutubeVideo{title='Relaxing Music - Meditation', linkToVideo='https://www.youtube.com/watch?v=qrx1vyvtRLY', thumbnailLink='https://i.ytimg.com/vi_webp/qrx1vyvtRLY/mqdefault.webp'}, YoutubeVideo{title='Relaxing Music - Background', linkToVideo='https://www.youtube.com/watch?v=loIZy6GqhUw', thumbnailLink='https://i.ytimg.com/vi_webp/loIZy6GqhUw/mqdefault.webp'}, YoutubeVideo{title='Delta Waves Sleep Music', linkToVideo='https://www.youtube.com/watch?v=EshmcHB3yMg', thumbnailLink='https://i.ytimg.com/vi_webp/EshmcHB3yMg/mqdefault.webp'}]}
im getting the groups binded and shown on list, but nothing happens onClick and i did'nt see anything regarding onClickListener in the documentation.
Thanks in advance!
The issue with this is that from the documentation here you don't have to pass your custom model YoutubePlaylist.java as a parameter as you did rather you replace it with ExpandableGroup so for your code
public class PlaylistViewHolder extends GroupViewHolder {
private TextView mPlaylistName, mPlaylistCount;
private ImageView arrow;
ExpandableListView.OnGroupClickListener listener;
public PlaylistViewHolder(View itemView) {
super(itemView);
mPlaylistName = itemView.findViewById(R.id.playlistNameView);
mPlaylistCount = itemView.findViewById(R.id.videosCount);
arrow = itemView.findViewById(R.id.expandBtn);
}
public void setCurrentPlaylist(ExpandableGroup playlist){
//the parameter has to be ExpandableGroup class and you can only get title
Log.e("###",playlist.getTitle());//you must call the getTitle() method
mPlaylistName.setText(playlist.getListTitle());
mPlaylistCount.setText("5");
}
}
This could be the way it was built. maybe a workaround this may be for
this method to then accept two parameters which is the ExpandableGroup
class and the custom model, class
public void setCurrentPlaylist(ExpandableGroup playlist, YoutubePlaylist playlist2){
//the parameter has to be ExpandableGroup class and you can only get title
Log.e("###",playlist.getTitle());//you must call the getTitle() method
mPlaylistName.setText(playlist2.getListTitle());
mPlaylistCount.setText("5");
}
I'm updating the database to other classes and I want the custom listview to be updated when I get to the main activity. My customListview is still standing
I have searched for this problem, but I could not solve it myself. Where should I add the code to solve this problem? Please help me 3 days did not solve my problem.
public class MainActivity extends AppCompatActivity {
veritabani vtabani; //database
List<Yukleclas> yuklele =new ArrayList<Yukleclas>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vtabani=new veritabani(this);
OzelAdaptor adaptor=new OzelAdaptor(this,yuklele);
ListView listView=(ListView) findViewById(R.id.listview);
String[] sutunlar =
{"id","bilgi","simdikiyil","simdikiay","simdikigun","alarmsaat",
"alarmdakika","gsonrayil","gsonraay","gsonragun","hsonrayil","hsonraay",
"hsonragun","asonrayil","asonraay","asonragun","seviye","durum"};
SQLiteDatabase dboku =vtabani.getReadableDatabase();
Cursorcursor=dboku.query("tablo_adi",sutunlar,null,null,null,null,null);
while (cursor.moveToNext()) {
if (cursor.getInt(17)==1) {
yuklele.add(new Yukleclas(cursor.getString(1), cursor.getInt(2),
cursor.getInt(3), cursor.getInt(4),
cursor.getInt(7),cursor.getInt(8),cursor.getInt(9),cursor.getInt(10),
cursor.getInt(11),cursor.getInt(12),cursor.getInt(13),cursor.getInt(14),
cursor.getInt(15),cursor.getInt(16)));
}
}
cursor.close();
dboku.close();
listView.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
}
public void ekleyegit(View view) {
Intent intent =new Intent(this,ekleactivity.class);
startActivity(intent);
finish();
}}
and this is myAdapter:
public class OzelAdaptor extends BaseAdapter {
LayoutInflater layoutInflater;
List<Yukleclas> list;
public OzelAdaptor(Activity activity,List<Yukleclas> mList){
layoutInflater= (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
list=mList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View satirView;
satirView=layoutInflater.inflate(R.layout.satir,null);
TextView tv_tarih = (TextView) satirView.findViewById(R.id.text_tarih);
TextView tv_bilgi= (TextView) satirView.findViewById(R.id.text_bilgi);
ImageView imageView= (ImageView) satirView.findViewById(R.id.imageView);
Yukleclas yukleclas =list.get(position);
tv_bilgi.setText(yukleclas.getBilgi());
if(yukleclas.getSeviye()==1){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGun() +"/" +yukleclas.getAy() + "/" +yukleclas.getYil() );
}else if(yukleclas.getSeviye()==2){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getGsgun() +"/" +yukleclas.getGsay() + "/" +yukleclas.getGsyil() );
}else if (yukleclas.getSeviye()==3){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getHsgun() +"/" +yukleclas.getHsay() + "/" +yukleclas.getHsyil() );
}else if (yukleclas.getSeviye()==4){
tv_tarih.setText("Sonraki tekrar:" +yukleclas.getAsgun() +"/" +yukleclas.getAsay() + "/" +yukleclas.getAsyil() );
}
if(yukleclas.getSeviye()==1){
imageView.setImageResource(bir); // eğer 1. seviyede ise bir isimli ikonu göster
}else if(yukleclas.getSeviye()==2){
imageView.setImageResource(iki);
}else if(yukleclas.getSeviye()==3){
imageView.setImageResource(uc);
}else if(yukleclas.getSeviye()==4){
imageView.setImageResource(ic_launcher);
}
return satirView;
}
}
and this is my class to get-set:
public class Yukleclas {
private String bilgi;
private int yil;
private int ay;
private int gun;
private int seviye;
private int gsyil;
private int gsay;
private int gsgun;
private int hsyil;
private int hsay;
private int hsgun;
private int asyil;
private int asay;
private int asgun;
public Yukleclas(String mBilgi,int mYil,int mAy,int mGun,int mGsyil,int
mGsay,int mGsgun,int mHsyil,int mHsay,int mHsgun,int mAsyil,int mAsay,int
mAsgun,int mSeviye){
yil=mYil;
bilgi=mBilgi;
ay=mAy;
gun=mGun;
gsyil=mGsyil;
gsay=mGsay;
gsgun=mGsgun;
hsyil=mHsyil;
hsay=mHsay;
hsgun=mHsgun;
asyil=mAsyil;
asay=mAsay;
asgun=mAsgun;
seviye=mSeviye;
}
public int getYil() {
return yil;
}
public void setYil(int yil) {
this.yil = yil;
}
public int getSeviye() {
return seviye;
}
public void setSeviye(int yil) {
this.seviye = seviye;
}
public String getBilgi() {
return bilgi;
}
public void setBilgi(String bilgi) {
this.bilgi = bilgi;
}
public int getAy() {
return ay;
}
public void setAy(int ay) {
this.ay = ay;
}
public int getGun() {
return gun;
}
public void setGun(int gun) {
this.gun = gun;
}
public int getGsyil() {return gsyil;
}
public void setGsyil(int gsyil) {this.gsyil = gsyil;
}
public int getGsay() {return gsay;
}
public void setGsay(int gsay) {this.gsay = gsay;
}
public int getGsgun() {return gsgun;
}
public void setGsgun(int gsgun) {this.gsgun = gsgun;
}
public int getHsyil() {return hsyil;
}
public void setHsyil(int hsyil) {this.hsyil = hsyil;
}
public int getHsay() {return hsay;
}
public void setHsay(int hsay) {this.hsay = hsay;
}
public int getHsgun() {return hsgun;
}
public void setHsgun(int hsgun) {this.hsgun = hsgun;
}
public int getAsyil() {return asyil;
}
public void setAsyil(int asyil) {this.asyil = asyil;
}
public int getAsay() {return asay;
}
public void setAsay(int asay) {this.asay = asay;
}
public int getAsgun() {return asgun;
}
public void setAsgun(int asgun) {this.asgun = asgun;
}
}
I know it is very complex but How to replace my customlistview ?
Easy way is to call adapter.notifyDataSetChanged() in your onResume function.
But I would suggest you check if your list has been updated then only you call adapter.notifyDataSetChanged(). You can do this in multiple ways, but for a cleaner approach use EventBus which allows you to fire events and listen to them, So you can fire an event every time you update your dataBaseand on listening to this event, simply call adapter.notifyDataSetChanged
I have a JSON nested object and i have been trying to pass for example, stations "name" to next activity in the onClick method. 2 questions:
1) Have i set my model class right or is there a better way?
2) What steps am i missing to pass "name" from stations from the specific object clicked onto the next activity?
My error for code provided (
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.ogure.trolleyproject.Adapter.StationsAdapter$ViewHolder.onClick(StationsAdapter.java:52)
Here is my JSON nested object
{
id: 1,
name: "Bus 1",
code: "TROL1",
tag_uid: "2HF4780H240827H40F284",
last_spotted_at: "2015-09-25 01:20:30",
last_spotted_station: 1,
stations: [
{
id: 1,
name: "Hennings Hall Station", //WHAT i want to pass
lat: "40.000000",
long: "41.000000",
_pivot_bus_id: 1,
_pivot_station_id: 1
}
}
Here is my model class
public class Bus implements Serializable {
#SerializedName("id")
private int mStationId;
#SerializedName("name")
private String mStationName;
#SerializedName("code")
private String mStationCode;
#SerializedName("tag_uid")
private String mStationTag_uid;
#SerializedName("last_spotted_at")
private String mStationLast_spot_time;
#SerializedName("last_spotted_station")
private int mStationLast_spot_station;
#SerializedName("stations")
private List<stations> stationInfo;
public int getmStationId() {
return mStationId;
}
public void setmStationId(int mStationId) {
this.mStationId = mStationId;
}
public List<stations> getStationInfo() {
return stationInfo;
}
public void setStationInfo(List<stations> stationInfo) {
this.stationInfo = stationInfo;
}
public int getmStationLast_spot_station() {
return mStationLast_spot_station;
}
public void setmStationLast_spot_station(int mStationLast_spot_station) {
this.mStationLast_spot_station = mStationLast_spot_station;
}
public String getmStationLast_spot_time() {
return mStationLast_spot_time;
}
public void setmStationLast_spot_time(String mStationLast_spot_time) {
this.mStationLast_spot_time = mStationLast_spot_time;
}
public String getmStationTag_uid() {
return mStationTag_uid;
}
public void setmStationTag_uid(String mStationTag_uid) {
this.mStationTag_uid = mStationTag_uid;
}
public String getmStationCode() {
return mStationCode;
}
public void setmStationCode(String mStationCode) {
this.mStationCode = mStationCode;
}
public String getmStationName() {
return mStationName;
}
public void setmStationName(String mStationName) {
this.mStationName = mStationName;
}
public class stations {
#SerializedName("id")
private int stationID;
#SerializedName("name")
private String stationName;
#SerializedName("lat")
private double stationLat;
#SerializedName("long")
private double stationLong;
#SerializedName("_pivot_bus_id")
private int mStationPiviotBusId;
#SerializedName("_pivot_station_id")
private int mStationPiviotStationId;
public int getmStationPiviotStationId() {
return mStationPiviotStationId;
}
public void setmStationPiviotStationId(int mStationPiviotStationId) {
this.mStationPiviotStationId = mStationPiviotStationId;
}
public int getmStationPiviotBusId() {
return mStationPiviotBusId;
}
public void setmStationPiviotBusId(int mStationPiviotBusId) {
this.mStationPiviotBusId = mStationPiviotBusId;
}
public double getStationLong() {
return stationLong;
}
public void setStationLong(double stationLong) {
this.stationLong = stationLong;
}
public double getStationLat() {
return stationLat;
}
public void setStationLat(double stationLat) {
this.stationLat = stationLat;
}
public String getStationName() {
return stationName;
}
public void setStationName(String stationName) {
this.stationName = stationName;
}
public int getStationID() {
return stationID;
}
public void setStationID(int stationID) {
this.stationID = stationID;
}
}
}
Here is my adapter class
public class StationsAdapter extends RecyclerView.Adapter<StationsAdapter.ViewHolder> {
private static List<Bus> mStations;
private static List<Bus.stations> mBusStations;
public StationsAdapter(List<Bus> stations) {
mStations = stations;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView TvStationName;
public ImageView IvImageView;
public CardView mCardView;
public ViewHolder(View itemView) {
super(itemView);
TvStationName = (TextView) itemView.findViewById(R.id.station_name);
IvImageView = (ImageView) itemView.findViewById(R.id.station_photo);
mCardView = (CardView) itemView.findViewById(R.id.cv);
mCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Bus s = mStations.get(position);
Bus.stations og = mBusStations.get(position); //HERE
Intent i = new Intent(v.getContext(), StationActivity.class);
i.putExtra("station_name", og.getStationName()); //and HERE is my problem
v.getContext().startActivity(i);
}
}
#Override
public StationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_card_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(StationsAdapter.ViewHolder holder, int position) {
Bus stationPos = mStations.get(position);
holder.TvStationName.setText(stationPos.getmStationName());
holder.mCardView.setTag(position);
}
#Override
public int getItemCount() {
return mStations.size();
}
Change your code to following:
public StationsAdapter(List<Bus> stations) {
List<Bus.stations> busStations = new ArrayList<>();
for (Bus bus : stations) {
busStations.addAll(bus.getStationInfo());
}
}
Issue is that you don't assign nothing to your mBusStations variable, that's why NPE throws.
Btw, don't use that confusing naming. Im talking about stationInfo in your Bus class.