I have referred quite few posts regarding this error but none of them could able to solve my issue. I have a fragment where I get my values using retrofit which I have shown below:
public class Tab extends Fragment
{
public String nlink;
public RecyclerView recycler;
public List<Initialise> item;
public Adapter adapter;
public Context mContext;
public Tab(Context mContext)
{
this.mContext=mContext;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v= inflater.inflate(R.layout.tab_layout,container,false);
item = new ArrayList<>();
recycler=(RecyclerView)v.findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(llm);
recycler.setItemAnimator(new DefaultItemAnimator());
adapter = new Adapter(item,mContext);
recycler.setAdapter(adapter);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
Bundle bundle=getArguments();
nlink=bundle.getString("link");
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ItemAdapter.ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Service Serviceapi = adapter.create(Service.class);
Serviceapi.getitem(nlink).enqueue(new Callback<Item>()
{
#Override
public void onResponse(Call<Item> call, Response<Item> response)
{
for(int i=0;i<response.body().getitems().size();i++)
{
item.add(new Initialise(response.body().getitems().get(i).getTitle(),response.body().getitems().get(i).getDate(),response.body().getitems().get(i).getcount(),response.body().getitems().get(i).getImage()));
}
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<Item> call, Throwable t)
{
}
});
}
}
And the following is my RecyclerView Adapter class:
public class Adapter extends RecyclerView.Adapter<Adapter.Holder>
{
static class Holder extends RecyclerView.ViewHolder
{
CardView cv;
ImageView thum_img;
TextView thum_time;
TextView thum_count;
TextView thum_text;
Holder(View itemView)
{
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
thum_img = (ImageView)itemView.findViewById(R.id.thum_img);
thum_time = (TextView)itemView.findViewById(R.id.thum_time);
thum_count = (TextView)itemView.findViewById(R.id.thum_scount);
thum_text = (TextView)itemView.findViewById(R.id.thum_text);
}
}
private List<Initialise> item;
private Context mContext;
public Adapter(List<Initialise> item, Context mContext)
{
this.item=item;
this.mContext=mContext;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab_layout, parent, false);
return new Holder(v);
}
#Override
public void onBindViewHolder(Holder holder, int position)
{
holder.thum_text.setText(item.get(position).gettitle());
holder.thum_time.setText(item.get(position).gettime());
holder.thum_count.setText(item.get(position).getcount());
Picasso.with(mContext).load(item.get(position).getstoryImage()).resize(120, 60).into(holder.thum_img);
}
#Override
public int getItemCount()
{
return item.size();
}
}
I'm getting the following error:
E/RecyclerView: No adapter attached; skipping layout
My cardview is not getting displayed and the viewpager is empty. Where am I going wrong ?
Try to edit onCreateViewHolder() method
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.tab_layout,parent,false);
Holder rcv = new Holder(layoutView,mContext);
return rcv;
Related
I have implemented a basic ListAdapter in RecyclerView as I am using View Model. The data I am getting is from networkManager to Viewmodel by calling API. Even when I did got the data the submitList is not Working and thus no data is getting inflated.
UpcomingGroupFragment
public class UpcomingGroupFragment extends Fragment {
private UpcomingViewModel mViewModel;
private RecyclerView recyclerView;
private GroupAdapter_new adapter;
public static UpcomingGroupFragment newInstance() {
return new UpcomingGroupFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_chatgroups, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new GroupAdapter_new();
recyclerView.setAdapter(adapter);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(UpcomingViewModel.class);
mViewModel.getMutableLiveData().observe(this, new Observer<List<ChatGroups_New>>() {
#Override
public void onChanged(#Nullable List<ChatGroups_New> chatGroups_news) {
adapter.submitList(chatGroups_news);
Log.e("Upcoming", String.valueOf(chatGroups_news.size()));
}
});
}
}
The Adapter Class extends the ListAdapter.
Link for overriding submitlist: https://stackoverflow.com/a/50062174
The Code is as follows:
GroupAdapter_new
public class GroupAdapter_new extends ListAdapter<ChatGroups_New,GroupAdapter_new.ViewHolder> {
public GroupAdapter_new() {
super(DIFF_CALLBACK);
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
int layoutID = R.layout.ongoing_group;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(layoutID,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ChatGroups_New currentGroup = getItem(position);
holder.text_flightarrival.setText(currentGroup.getFlightNameArrival());
}
class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
//... Finding ID's for various Views
}
}
/****ADDED THIS FROM CODE*****/
#Override
public void submitList(List<ChatGroups_New> list) {
super.submitList(list != null ? new ArrayList<ChatGroups_New>() : null);
}
/***********/
private static final DiffUtil.ItemCallback<ChatGroups_New> DIFF_CALLBACK =
new DiffUtil.ItemCallback<ChatGroups_New>() {
#Override
public boolean areItemsTheSame(ChatGroups_New oldItem, ChatGroups_New newItem) {
Log.e("areItemsTheSame", String.valueOf(oldItem.getMergedLogId() == newItem.getMergedLogId()));
return oldItem.getMergedLogId() == newItem.getMergedLogId();
}
#Override
public boolean areContentsTheSame(ChatGroups_New oldItem, ChatGroups_New newItem) {
if(oldItem.getFlightIcon().equals(newItem.getFlightIcon()) && oldItem.getFlightNameArrival().equals(newItem.getFlightNameArrival())){
if(oldItem.getGateValue().equals(newItem.getGateValue()) && oldItem.getEtaValue().equals(newItem.getEtaValue())){
if(oldItem.getAlertValue().equals(newItem.getAlertValue()) && oldItem.getTaskcompletedValue().equals(newItem.getTaskcompletedValue())){
Log.e("areContentsTheSame", "true");
return true;
}
}
}
return false;
}
};
}
If you want to see my ViewModel Class then:
UpcomingViewModel
public class UpcomingViewModel extends AndroidViewModel
implements I_NetworkResponse {
private NetworkManager networkManager;
private SharedPrefService prefService;
private HashMap<String, String> header;
private final String TAG = "UpcomingViewModel";
private List<ChatGroups_New> upcomingList;
private MutableLiveData<List<ChatGroups_New>> mutableLiveData;
public UpcomingViewModel(#NonNull Application application) {
super(application);
prefService = SharedPrefService.getInstance(application);
networkManager = new NetworkManager(application,this);
upcomingList = new ArrayList<>();
mutableLiveData = new MutableLiveData<>();
mutableLiveData.setValue(upcomingList);
header = new HashMap<>();
header.put("authorizationcode",prefService.getStringValue(Keys.getPreferenceAuthKey()));
if(upcomingList.isEmpty()){
networkManager.Volley_JsonObjectRequest(Keys.getBaseUrl()+"AviLeap/flights/upcoming",
header,null,TAG,"AviLeap/flights/upcoming");
}
}
public MutableLiveData<List<ChatGroups_New>> getMutableLiveData() { return mutableLiveData; }
#Override
public void getNetworkSuccessResponse(String TAG, String successResponse, String TAGforApi) {
Log.e(TAGforApi,successResponse);
parseUpcomingFlight(successResponse, upcomingList);
mutableLiveData.setValue(upcomingList);
}
#Override
public void getNetworkFailResponse(String TAG, VolleyError failResponse, String TAGforApi) { }
#Override
protected void onCleared() {
super.onCleared();
networkManager.stopNetworkCallsWithTag(TAG);
}
private void parseUpcomingFlight(String successResponse, List<ChatGroups_New> upcomingList) {
try {
JSONObject rootObject = new JSONObject(successResponse);
if(rootObject.has("upcomingflights") && rootObject.opt("upcomingflights") instanceof JSONArray){
JSONArray flightsArray = rootObject.optJSONArray("upcomingflights");
for(int flightIndex = 0; flightIndex < flightsArray.length(); flightIndex++){
JSONObject flightObject = flightsArray.optJSONObject(flightIndex);
int mergedLogId = flightObject.optInt("logid");
upcomingList.add(new ChatGroups_New(mergedLogId));
Log.e("parseUpcomingFlight", String.valueOf(upcomingList.size()));//..... Log Point
}
}
}
catch (JSONException e) { e.printStackTrace(); }
}
}
Initially the Size of the List is zero, so the Error is coming for as
AviLeap/flights/upcoming: //.... API CALL
2019-03-02 13:25:53.652 8477-8477/com.avileapconnect.com E/parseUpcomingFlight: 1 2019-03-02 13:25:53.652 8477-8477/com.avileapconnect.com E/parseUpcomingFlight: 2
2019-03-02 13:25:53.653 8477-8477/com.avileapconnect.com E/Upcoming: 2
The above logs show that the data is being added to the arraylist, but it is not updating. Also after all these logs when I go back to my Fragment I get the following error.
no adapter Attached, Skipping Layout
One more thing to add is that the adapter's getItemCount is getting updated properly. But even after that I am getting error:
no adapter Attached, Skipping Layout
EDIT: I fixed the error by commenting out the code for overriding the SubmitList method. I am also setting the adapter in the observer method in the fragment Class
I'm developing simple project. CategoryFragment is the first added fragment in MainActivity. I expect receive data from FireBase and display it with RecyclerView.
Below my code. The app doesn't fall during launching. There is no any error.
I guess I should use some method for my purpose, but I'm new in Firebase.
public class CategoryFragment extends Fragment {
public DatabaseReference mRootDB;
private RecyclerView mRecyclerView;
public FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mRootDB = FirebaseDatabase.getInstance().getReference().child("categories");
adapter = new FirebaseRecyclerAdapter <Category, CategoryViewHolder>(
Category.class,
R.layout.model_category,
CategoryViewHolder.class,
mRootDB)
{
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, Category model, int position) {
viewHolder.setCategory(model.getName());
}
};
mRecyclerView.setAdapter(adapter);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_category, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_RV);
return rootView;
}
public static class CategoryViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView category_CV;
public CategoryViewHolder(View itemView) {
super(itemView);
mView = itemView;
category_CV = (TextView) mView.findViewById(R.id.category_CV);
}
public void setCategory(String data){
category_CV.setText(data);
}
}
}
I would not override onActivityCreated() if I were you, you can create and return the RecyclerView in the onCreateView(). Are you sure you have data in Firebase? You can override parseSnapshot() like this and maybe put a break point to make sure that something is coming back, and if it does then you may want to check your RecyclerView custom layout.
public class CategoryFragment extends Fragment {
public DatabaseReference mRootDB;
private RecyclerView mRecyclerView;
public FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_category, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.category_RV);
mRootDB = FirebaseDatabase.getInstance().getReference().child("categories");
adapter = new FirebaseRecyclerAdapter <Category, CategoryViewHolder>(
Category.class,
R.layout.model_category,
CategoryViewHolder.class,
mRootDB)
{
#Override
protected Category parseSnapshot(DataSnapshot snapshot) {
Category category = super.parseSnapshot(snapshot);
if (category != null){
category.setId(snapshot.getKey());
}
return category;
}
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, Category model, int position) {
viewHolder.setCategory(model.getName());
}
};
mRecyclerView.setAdapter(adapter);
return rootView;
}
public static class CategoryViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView category_CV;
public CategoryViewHolder(View itemView) {
super(itemView);
mView = itemView;
category_CV = (TextView) mView.findViewById(R.id.category_CV);
}
public void setCategory(String data){
category_CV.setText(data);
}
}
}
homepageThis is my fragment class
public class Premiums extends Fragment {
private RecyclerView recyclerPremium;
private RecyclerView.LayoutManager mLayoutManager;
private List<FeaturedAddDetails> featuredAddDetailsList = new ArrayList<>();
private List<PremiumDetails> premiumDetailslist = new ArrayList<>();
private NewestAdapter newestAdapter;
private PremiumAdapter premiumAdapter;
private String jsonResponse;
private PremiumDetails premiumDetails;
private JSONObject jsonobject;
public Premiums() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.premium_fragment, container, false);
recyclerPremium = (RecyclerView) mainView.findViewById(R.id.recycler_premium);
premiumAdd();
premiumAdapter = new PremiumAdapter(getActivity().getApplicationContext(), premiumDetailslist);
recyclerPremium.setAdapter(premiumAdapter);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerPremium.setLayoutManager(mLayoutManager);
recyclerPremium.setHasFixedSize(true);
}
private void premiumAdd() {
PremiumRequestHandler premiumHandler = new PremiumRequestHandler("premiumADD");
premiumHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
Log.e("id", String.valueOf(jsonobject.getInt("id")));
premiumDetails = new PremiumDetails(jsonobject.getInt("id"),
jsonobject.getInt("userid"),
jsonobject.getInt("mobile"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("comments"),
jsonobject.getInt("created"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("views"),
jsonobject.getInt("ImageCount"),
jsonobject.getInt("storeid"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("currency"),
jsonobject.getString("description"));
premiumDetailslist.add(premiumDetails);
premiumAdapter.setPremiumDetails(premiumDetailslist);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
This is my adapter class
public class PremiumAdapter extends RecyclerView.Adapter<PremiumAdapter.MyViewHolderPremium> {
private List<PremiumDetails> premiumDetailsList;
private ImageLoader imageLoader;
private Context context;
public PremiumAdapter(Context context, List<PremiumDetails> premiumDetailsList) {
this.premiumDetailsList = premiumDetailsList;
this.context = context;
notifyDataSetChanged();
}
public void setPremiumDetails(List<PremiumDetails> premiumDetailsList) {
this.premiumDetailsList = premiumDetailsList;
notifyDataSetChanged();
}
public class MyViewHolderPremium extends RecyclerView.ViewHolder {
private TextView txtTitle,txtDescription,txtCityName,txtPrice,txtCategory,txtHour,txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolderPremium(View itemView) {
super(itemView);
txtTitle = (TextView)itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView)itemView.findViewById(R.id.description_fad);
txtCityName = (TextView)itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView)itemView.findViewById(R.id.price_fad);
txtCategory = (TextView)itemView.findViewById(R.id.category_fad);
txtHour = (TextView)itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView)itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto=(NetworkImageView)itemView.findViewById(R.id.img_photo_lod_fad);
}
}
#Override
public MyViewHolderPremium onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout,parent,false);
final MyViewHolderPremium myViewHolderPremium = new MyViewHolderPremium(itemView);
return myViewHolderPremium;
}
#Override
public void onBindViewHolder(MyViewHolderPremium holder, int position) {
PremiumDetails premiumDetails = premiumDetailsList.get(position);
holder.txtTitle.setText(premiumDetails.getTitle());
holder.txtDescription.setText(premiumDetails.getDescription());
holder.txtCityName.setText(premiumDetails.getCityName());
holder.txtPrice.setText(Integer.toString(premiumDetails.getPrice()));
holder.txtCategory.setText(premiumDetails.getCategoryName());
holder.txtHour.setText(Integer.toString(premiumDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(premiumDetails.getImageCount())+" photos " );
try {
imageLoader= VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
//imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
//imageLoader.get(featuredAddDetails.getDefault_photo(), ImageLoader.getImageListener(holder.imgPhoto, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imgPhoto.setImageUrl(premiumDetails.getDefault_photo(),imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(premiumDetailsList.size()));
return premiumDetailsList.size();
}}
I am getting error on showing values but I got values from json and I can't add it to adapter and model class, plz help me I look stackoverflow whole day but I can't find my issue
my getItemCount() is showing as 0"
You are setting the adapter and then you are calling premiumAdd() method.First call that method and then set the adapter.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.premium_fragment, container, false);
recyclerPremium = (RecyclerView) mainView.findViewById(R.id.recycler_premium);
premiumAdd();
premiumAdapter = new PremiumAdapter(getActivity().getApplicationContext(), premiumDetailslist);
recyclerPremium.setAdapter(premiumAdapter);
return mainView;
Try notifyDataSetChanged() after setting data in the Constructor of your Adapter
[EDIT] Whenever your data changes, you need to inform your Adapter about it also, then call notifyDataSetChanged() on it.
You are probably setting empty data into the Adapter, your List changes, but the Adapter does not know about it.
[Update]
In addition to your Adapter constructor, add a setData(List) to your adapter to change your dataset at runtime.
public void setPremiumDetails(List<PremiumDetails> premiumDetailsList) {
this.premiumDetailsList = premiumDetailsList;
notifyDataSetChanged();
}
When your request in premiumAdd() returns, and you receive a new set of data, you call setPremiumDetails on your Adapter with the new data and the List will update.
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.premium_fragment, container, false);
recyclerPremium = (RecyclerView) mainView.findViewById(R.id.recycler_premium);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerPremium.setLayoutManager(mLayoutManager);
recyclerPremium.setHasFixedSize(true);
premiumAdd();
premiumAdapter = new PremiumAdapter(getActivity().getApplicationContext(), premiumDetailslist);
recyclerPremium.setAdapter(premiumAdapter);
return mainView;
}
and remove premiumAdapter.notifyDataSetChanged();
added adapter code:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.ViewHolder> {
ArrayList<Model> dataset;
public RVAdapter(ArrayList<Model> dataset) {
this.dataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Model model = dataset.get(position);
holder.name.setText(model.name) ;
holder.status.setText(model.status);
if (model.status.equalsIgnoreCase("good"))
holder.ivStatus.setImageResource(R.drawable.ic_tick_48);
else
holder.ivStatus.setImageResource(R.drawable.ic_delete_48);
}
#Override
public int getItemCount() {
Log.e("TAG","SIZE: "+dataset.size());
return dataset.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView status;
ImageView ivStatus;
RelativeLayout parent;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.rv_item_name);
status = (TextView) itemView.findViewById(R.id.rv_item_status);
ivStatus = (ImageView) itemView.findViewById(R.id.rv_item_iv);
parent = (RelativeLayout) itemView.findViewById(R.id.rv_item_parent);
}
}
}
your notifiy adapter on every single add
for (...){
....
premiumDetailslist.add(premiumDetails);
premiumAdapter.notifyDataSetChanged();// called every time wrong
}
also provide what exact error log says
and move the notifyDataSetChanged() after the for not in the loop
if no data is showing try recyclerview.invalidate , but i wont particularly do that way, would try debugging, log every step, inspect with method in the expected sequence isnt working
When I try Recyclerview With Fragments its getting error Fragments With RecyclerView not working. Its getting Error No layout manager attached. Skipping entry.
My FrgamentList.java
public class FragmentList extends Fragment {
String [] names={"Nitin","Manish","Ankit","Hardik","Mayur","Mayank"};
RecyclerView mRecyclerView;
Context context;
RecyclerAdapter mAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_list,container,false);
mRecyclerView= (RecyclerView)v.findViewById(R.id.recycler_nit);
LinearLayoutManager mLayout= new LinearLayoutManager(getActivity());
mLayout.setOrientation(LinearLayoutManager.VERTICAL);
mAdapter= new RecyclerAdapter(getActivity(),names);
mRecyclerView.setAdapter(mAdapter);
return v;
}
}
RecyclerAdapeter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
Context context;
String[] names;
public RecyclerAdapter(Context context, String[] names) {
this.context = context;
this.names = names;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.raw_list,parent,false);
vh=new ViewHolder(v);
return (ViewHolder) vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.txt.setText(names[position]);
}
#Override
public int getItemCount() {
return names.length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView txt;
public ViewHolder(View itemView) {
super(itemView);
txt= (TextView) itemView.findViewById(R.id.name_listtext);
}
}
}
You should set your created layout manager to RecyclerView
mRecyclerView= (RecyclerView)v.findViewById(R.id.recycler_nit);
LinearLayoutManager mLayout= new LinearLayoutManager(getActivity());
mLayout.setOrientation(LinearLayoutManager.VERTICAL);
//add this line
mRecyclerView.setLayoutManager(mLayout);
You need to set a LayoutManager to recyclerView like this:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
or
mRecyclerView.setLayoutManager(mLayout);
I have a Fragment with a RecyclerView that I want to update after I get some data from an IntentService.
The service finishes and sends the data to the Fragment using Otto EventBus.I can confirm that cause I add some log messages and print some values eg : dataSet.get(0).getName().
After that I call adapter.notifyDataSetChanged() but nothing appears on my screen.
I can give you the code of my custom Adapter if you think that it can help :
public class FilteredVideoListAdapter extends RecyclerView.Adapter<FilteredVideoListAdapter.ViewHolder> {
public static final String TAG = "FILTEREDVIDEO-ADAPTER";
public List<FilteredVideo> data;
public Context context;
public FilteredVideoListAdapter(List<FilteredVideo> data) {
this.data = data;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView tvTitle;
TextView tvSubtitle;
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
tvTitle = (TextView) itemView.findViewById(R.id.tv_filtered_video_title);
tvSubtitle = (TextView) itemView.findViewById(R.id.tv_filtered_video_subtitle);
imageView = (ImageView) itemView.findViewById(R.id.iv_filtered_video_image);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_filtered_video, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.tvTitle.setText(data.get(position).getName());
viewHolder.tvSubtitle.setText(data.get(position).getDataUrl());
int dimen = context.getResources().getDimensionPixelSize(R.dimen.filtered_video_image_size);
Picasso.with(context)
.load(data.get(position).getThumbnailUrl())
.resize(dimen, dimen)
.into(viewHolder.imageView);
}
#Override
public int getItemCount() {
return data.size();
}
}
And the code of the Fragment class :
public class FilteredVideoListFragment extends BaseFragment {
private static final String TAG = "FILTEREDVLIST-FRAGMENT";
public RecyclerView recyclerView;
protected FilteredVideoListAdapter adapter;
protected RecyclerView.LayoutManager layoutManager;
public List<FilteredVideo> dataSet;
//first time there aren't any populated data
private boolean datasetIsNull = true;
public static FilteredVideoListFragment newInstance() {
return new FilteredVideoListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataSet = new ArrayList<>();
BusProvider.getInstance().register(this);
// startService here -
Intent intentService = new Intent(activity, GetMostPopularIntentService.class);
activity.startService(intentService);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_filtered_video_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.rv_filtered_video_list);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new FilteredVideoListAdapter(dataSet);
recyclerView.setAdapter(adapter);
return view;
}
private BroadcastReceiver mostpopularReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String resultCode = intent.getStringExtra("resultCode");
if ("OK".equals(resultCode)) {
Toast.makeText(activity, "Most Popular Results Received!", Toast.LENGTH_SHORT).show();
}
}
};
/** Register/ unRegister Receiver */
#Override
public void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(GetMostPopularIntentService.ACTION);
LocalBroadcastManager.getInstance(activity).registerReceiver(mostpopularReceiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(activity).unregisterReceiver(mostpopularReceiver);
}
/**
* Receives Event from GetMostPopularIntentService when data retrieved
* successfully.
*/
#Subscribe
public void onMostPopularReceivedEvent(MostPopularReceivedEvent event) {
Log.i(TAG, "clickevent ");
dataSet = event.getFilteredVideoList();
Log.i(TAG, "NOTIFY ADAPTER SIZE == " + dataSet.size() );
Log.i(TAG, "NOTIFY ADAPTER SIZE == " + dataSet.get(0).getName() );
adapter.notifyDataSetChanged();
Log.i(TAG, "AFTER NOTIFY ADAPTER ");
}
#Subscribe
public void onToastRequest(ToastRequest request) {
Log.i(TAG, "onToastRequest ");
Toast.makeText(activity, request.message, request.duration).show();
}
}
Try -
#Subscribe
public void onMostPopularReceivedEvent(MostPopularReceivedEvent event) {
adapter = new FilteredVideoListAdapter(event.getFilteredVideoList());
recyclerView.setAdapter(adapter);
}
Try this adapter
public class FilteredVideoListAdapter extends RecyclerView.Adapter<FilteredVideoListAdapter.ViewHolder> {
public static final String TAG = "FILTEREDVIDEO-ADAPTER";
public List<FilteredVideo> data;
public Context mContext;
public FilteredVideoListAdapter(Context context, List<FilteredVideo> data) {
this.data = data;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_filtered_video, null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder customViewHolder, int i) {
FilteredVideo filteredVideo = data.get(i);
customViewHolder.tvTitle.setText(filteredVideo.getName());
customViewHolder.tvSubtitle.setText(filteredVideo.getDataUrl());
int dimen = mContext.getResources().getDimensionPixelSize(R.dimen.filtered_video_image_size);
Picasso.with(mContext)
.load(filteredVideo.getThumbnailUrl())
.resize(dimen, dimen)
.into(customViewHolder.imageView);
}
#Override
public int getItemCount() {
return (null != data ? data.size() : 0);
}
}
And call in your Fragment like this
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_filtered_video_list, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.rv_filtered_video_list);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new FilteredVideoListAdapter(getActivity(), dataSet);
recyclerView.setAdapter(adapter);
return view;
}