App doesn't display items on RecyclerView - java

I'm new to android studio . I'm trying to display items in RecycleView but it's doesn't show anything.
This is what android studio says:
E/RecyclerView: No layout manager attached; skipping layout
My Fragment :
public class Articles extends Fragment {
View root;
RecyclerView recyclerView;
NewsList[] myListData = new NewsList[] {
new NewsList("Article 1", "Some Author"),
new NewsList("Article2", "Some Author"),
new NewsList("Article3", "Some Author"),
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_articles, container, false);
recyclerView = root.findViewById(R.id.recyclerView);
NewsAdapter adapter = new NewsAdapter(myListData);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
return root;
}
Here is the code of my Adapter class :
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private NewsList[] listdata;
// RecyclerView recyclerView;
public NewsAdapter(NewsList[] listdata) {
this.listdata = listdata;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.list_item, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final NewsList myListData = listdata[position];
holder.textView1.setText(listdata[position].getTitle());
holder.textView2.setText(listdata[position].getAuthor());
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(),"click on item: "+myListData.getTitle(),Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return listdata.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView1;
public TextView textView2;
public RelativeLayout relativeLayout;
public ViewHolder(View itemView) {
super(itemView);
this.textView1 = (TextView) itemView.findViewById(R.id.textView1);
this.textView2 = (TextView) itemView.findViewById(R.id.textView2);
relativeLayout = (RelativeLayout)itemView.findViewById(R.id.relativeLayout);
}
}
Previously I had an error where the app crashed when opened the fragment but now it's skips the RecyclerView.
I will be gratefull if you help me to resolve this issue.

You need to add a layoutManager to your recycler view:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_articles, container, false);
recyclerView = root.findViewById(R.id.recyclerView);
NewsAdapter adapter = new NewsAdapter(myListData);
recyclerView.setHasFixedSize(true);
// Add this line
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()))
recyclerView.setAdapter(adapter);
return root;
}

It's mandatory to have a Layout manager for your Recyclerview. For example, you can use a linear one by adding this after inflating your view :
recyclerView.setLayoutManager(new LinearLayoutManager( context ));
where context is whatever your context is

Related

Recycler View double items on change fragment

I have a problem with the recyclerview in my app i have 2 fragments in the first one there is the recycler view which has to find the songs present in the device and put them in line in the second for now nothing. when I switch from one fragment to another the recycler view items double each time.
CODE:
HomeActvity
public class HomeActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
TextView noMusicTextView;
HomeFragment homeFragment = new HomeFragment();
ProvaFragment provaFragment = new ProvaFragment();
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportActionBar().hide();
noMusicTextView = findViewById(R.id.noSongs);
recyclerView = findViewById(R.id.recycler_view);
bottomNavigationView = findViewById(R.id.barra_navigazione);
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
return true;
case R.id.prova:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, provaFragment).commit();
return true;
}
return false;
}
});
}
}
HomeFragment
public class HomeFragment extends Fragment {
ArrayList<AudioModel> songsList = new ArrayList<>();
RecyclerView recyclerView;
TextView noMusicTextView;
#SuppressLint("MissingInflatedId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
noMusicTextView = view.findViewById(R.id.noSongs);
String[] projection = {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION,
};
String selection = MediaStore.Audio.Media.IS_MUSIC + " !=0";
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection,selection,null,null);
while(cursor.moveToNext()){
AudioModel songData = new AudioModel(cursor.getString(1), cursor.getString(0),cursor.getString(2));
if(new File(songData.getPath()).exists())
songsList.add(songData);
}
if(songsList.size() == 0){
noMusicTextView.setVisibility(View.VISIBLE);
}else{
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new MusicListAdapter(songsList, getContext()));
}
return view;
}
}
MusicListAdapter
public class MusicListAdapter extends RecyclerView.Adapter<MusicListAdapter.ViewHolder>{
ArrayList<AudioModel> songsList;
Context context;
public MusicListAdapter(ArrayList<AudioModel> songsList, Context context) {
this.songsList = songsList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false);
return new MusicListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AudioModel songData = songsList.get(position);
holder.titleTextView.setText(songData.getTitle());
}
#Override
public int getItemCount() {
return songsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleTextView;
ImageView iconImageView;
public ViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.music_title_text);
iconImageView = itemView.findViewById(R.id.icon_view);
}
}
}
I have tryed to use songsList.clear(); but this don't work(Sorry for my english).
When switching fragments, existing fragments aren't deleted.
Also, songsList isn't initialized; onViewCreated() is called at this time, so it seems that the transition adds the item to the songsList.
In order to solve the problem, it seems that it is necessary to do a good comparison so that the same item as the previously saved item is not added, or to not add an item every time in onViewCreated.

CardView not shown on RecyclerView (In Fragment)

I want to make CardViews visible on a RecyclerView inside a Fragment, but all I get is a infinite loading sign and no cardviews are being showed. I'm very new to Android Programming so please be kind..
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentPage fragment = new FragmentPage();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.placeholder, fragment);
fragmentTransaction.commit();
ViewPager viewpager = findViewById(R.id.viewpager);
viewpager.setOffscreenPageLimit(1);
SwipeAdapter adapter = new SwipeAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setPageTransformer(true, new DepthPageTransformer());
viewpager.setCurrentItem(0);
}
}
This is my Adapter class(I followed a Tutorial)
public class ListAdapterIT extends RecyclerView.Adapter {
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
private class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mImageView;
public ListViewHolder (View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image2);
itemView.setOnClickListener(this);
}
public void BindViewHolder(int position) {
mImageView.setImageResource(OurData.picturePath[position]);
}
public void onClick(View view) {
}
}
}
This is my Fragment I also think the Problem is in that class
public class FragmentPage extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.page_fragment, container, false);
ArrayList<Integer> items = new ArrayList<>();
items.add(R.layout.example_item);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.listRecyclerView);
ListAdapterIT listAdapter = new ListAdapterIT() {};
recyclerView.setAdapter(listAdapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
return view;
}
}

Unable to implement the Recycler view Adaptor in fragment [duplicate]

This question already has an answer here:
showing RecyclerView on fragment with data from Firebase
(1 answer)
Closed 3 years ago.
I am not able to attach the Firestore Recycler Adapter in the fragment.
I googled many things but no good yet.
The fragment is one of the tabs of the bottomtablayout.
The data is retrieved from a single collection. I want represent the list of multlipe-user post in a single view.
I have tried the below code but to no good yet.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
final FragmentActivity c = getActivity();
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<PostsModel> options = new FirestoreRecyclerOptions.Builder<PostsModel>()
.setQuery(query, PostsModel.class)
.build();
adapter = new PostsAdapter(options);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(c));
recyclerView.setAdapter(adapter);
mParent =view.findViewById(R.id.relative_home);
return inflater.inflate(R.layout.fragment_home, null);
}
Adapter Code
public class PostsAdapter extends FirestoreRecyclerAdapter<PostsModel, PostsAdapter.PostsHolder> {
private OnItemClickListener listener;
public PostsAdapter(#NonNull FirestoreRecyclerOptions<PostsModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull PostsHolder holder, int position, #NonNull PostsModel model) {
//retrieve the fields here
holder.textViewTitle.setText(model.getPostTitle());
holder.textViewDescription.setText(model.getPostContent());
holder.textViewPriority.setText(String.valueOf(model.getSpinnerC()));
holder.AuthorName.setText(model.getName());
holder.AuthorGender.setText(model.getGender());
}
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list_layout,
parent, false);
return new PostsHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
class PostsHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
TextView AuthorName;
TextView AuthorGender;
public PostsHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.quote1);
textViewDescription = itemView.findViewById(R.id.name1);
textViewPriority = itemView.findViewById(R.id.timestamp1);
}
}
}
You're inflating the other view in the onCreateView method.
return inflater.inflate(R.layout.fragment_home, null);

How to put a RecyclerView into a Fragment?

I am still new for the android development. Currently, I am trying to show a RecyclerView within a Fragment. I tried to show the RecyclerView without using Fragment and it worked fine. But when it come to using Fragment, nothing is shown.
Here is the MainActivity containing the Fragment:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.fragment_container, missionListFragment).addToBackStack(null).commit();
}
And the Fragment's onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_mission_list, container, false);
//ButterKnife.bind(rootview);
mRecycler = (RecyclerView) rootView.findViewById(R.id.recycler);
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("COLLECTION_NAME").limit(LIMIT);
if (mQuery == null) {
Log.w(TAG, "No query, not initializing RecyclerView. Created data on server.");
}
mAdapter = new RecyclerViewAdapter(mQuery, this) {
#Override
protected void onDataChanged() {
}
#Override
protected void onError(FirebaseFirestoreException e) {
// Show a snackbar on errors
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Error: check logs for info.", Snackbar.LENGTH_LONG).show();
}
};
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
return rootView;
}
With the RecyclerViewAdapter:
public class RecyclerViewAdapter extends FirestoreAdapter<RecyclerViewAdapter.ViewHolder> {
private static final int UNAVAILABLE = 0, AVAILABLE = 1;
public interface OnItemSelectedListener {
void onItemSelected(DocumentSnapshot item);
}
private OnItemSelectedListener mListener;
public RecyclerViewAdapter(Query query, OnItemSelectedListener listener) {
super(query);
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListener);
}
static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.view1)
TextView view1;
#BindView(R.id.view2)
TextView view2;
#BindView(R.id.view3)
TextView view3;
#BindView(R.id.view4)
TextView view4;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnItemSelectedListener listener) {
Item item = snapshot.toObject(Item.class);
Resources resources = itemView.getResources();
view1.setText(item.getfield1());
view2.setText(Integer.toString(item.getfield2()));
if(item.getfield3() == AVAILABLE)
view3.setText("Available");
else
view3.setText("Unavailable");
view4.setText(item.getfield4().toString());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemSelected(snapshot);
}
}
});
}
}
}
As you can notice above, I am getting data from the Firebase and displaying them as a RecyclerView. But I don't think it is the problem of empty query data, so please help.
It could be that data from firebase is not being retrieved, hence there is no content for recyclerview to display. Please check if your firebase connection is working fine and you are retrieving something from it

RecyclerView in Fragment

I am setting up a RecyclerView inside a Fragment following the Android docs example here.
I pasted my code below, there is not much. (The only difference is I'm using a Fragment instead of an Activity).
The error I'm getting is:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
All solutions to this problem online are to add false argument in layout inflation for fragment. But I've already done this, and I still get the error.
My code:
MainActivity
...
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new NewsFragment()).commit();
...
NewsFragment
public class NewsFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.news_layout,container, false);
mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new NewsAdapter(new String[]{"hello","world","qwert","test","greg","peck"});
mRecyclerView.setAdapter(mAdapter);
return v;
}
}
NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private String[] mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(TextView tv) {
super(tv);
mTextView = tv;
}
}
public NewsAdapter(String[] myDataset) {
mDataset = myDataset;
}
#Override
public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_item, parent, false);
TextView tv = (TextView)v.findViewById(R.id.textView2);
ViewHolder vh = new ViewHolder(tv);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
Any help would be hugely appreciated!
The error is on this line:
TextView tv = (TextView)v.findViewById(R.id.textView2);
ViewHolder vh = new ViewHolder(tv);
Change it to:
TextView tv = (TextView)v.findViewById(R.id.textView2);
ViewHolder vh = new ViewHolder(v);
The text view is already having a parent. That's why you are getting this error.
Updated code:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private String[] mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View view) {
super(tv);
mTextView= (TextView)view.findViewById(R.id.textView2);
}
}
public NewsAdapter(String[] myDataset) {
mDataset = myDataset;
}
#Override
public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}

Categories