How I retrieve data from firebase and represent it at recyclerview? - android

I can't retrieve data from the firebase and view it at recyclerView
this my database at firebaseenter image description here
There are no problem appear but in my run is not display the items this is my run enter image description here
and this my code I tried every thing I don't know what the problem help me please
public class account_preview extends AppCompatActivity {
private ArrayList<outflow>outflows;
private RecyclerView recyclerView;
RecyclerAdapter adapter;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_preview);
FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef =
database.getReference("user_account/(username)/bank_accounts/1");
adapter = new RecyclerAdapter(outflows, account_preview.this);
recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
llm.setOrientation(LinearLayoutManager.VERTICAL);
onStart();
new GetDataFromFirebase().
executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
myRef.child("outflow").child("1").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
outflows=new ArrayList<outflow>();
for (DataSnapshot dataSnapshot1:
dataSnapshot.getChildren()){
outflow values =
dataSnapshot1.getValue(outflow.class);
outflows.add(values);}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." +
error.toException());
}
});
}
private class GetDataFromFirebase extends
AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
}
public class RecyclerAdapter extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>{
private Context context;
private ArrayList<outflow> values;
public RecyclerAdapter(ArrayList<outflow> values, account_preview
context) {
this.values = values;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new ViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_outflows, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.name.setText( values.get(position).getCategory());
holder.c.setText((int) values.get(position).getAmount());
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(values.size()==0){
arr = 0;
}
else{
arr=values.size();
}
}catch (Exception e){
}
return arr;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView name,c;
ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.totaloutflow);
c=(TextView)itemView.findViewById(R.id.total);
}
}
}
public class outflow {
private double amount;
private String date;
private String time;
private String attachment;
private String category;
private String location;
private String vendor;
private int rate;
public outflow(double amount, String date, String time, String attachment, String category, String location, String vendor) {
this.amount = amount;
this.date = date;
this.time = time;
this.attachment = attachment;
this.category = category;
this.location = location;
this.vendor = vendor;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
activity_account_preview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
list_outflows.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".account_preview">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#27233A"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
<TextView
android:id="#+id/textView"
android:layout_width="84dp"
android:layout_height="44dp"
android:layout_marginEnd="36dp"
android:layout_marginStart="8dp"
android:padding="5dp"
android:text="(التاريخ)"
android:textColor="#000000"
android:textSize="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="64dp"
tools:ignore="MissingConstraints" />
<Button
android:id="#+id/button"
android:layout_width="251dp"
android:layout_height="61dp"
android:layout_marginBottom="24dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#9FB4C7"
android:text="حذف الحساب"
android:textColor="#ffffff"
android:textSize="30dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.437"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:background="#D6C9C9"
android:clickable="true"
app:backgroundTint="#D6C9C9"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.976"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#android:drawable/ic_input_add" />
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="392dp"
android:layout_height="64dp"
android:layout_margin="2.5dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="184dp"
app:cardBackgroundColor="#color/lightgrey"
app:cardCornerRadius="4dp"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="1.0"
tools:ignore="MissingConstraints">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="0.30"
android:orientation="vertical">
<TextView
android:id="#+id/totaloutflow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:text="الفواتير"
android:textColor="#color/colorPrimaryDark"
android:textSize="25sp" />
<TextView
android:id="#+id/total"
android:layout_width="388dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:text="ريال سعودي"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>

Firebase has its own Adapter for RecyclerView so better use that.
public FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> getmFirebaseAdapter() {
return mFirebaseAdapter;
}
public void setmFirebaseAdapter(FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> mFirebaseAdapter) {
this.mFirebaseAdapter = mFirebaseAdapter;
}
//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
private final TextView image_title ;
public ShowDataViewHolder(final View itemView)
{
super(itemView);
image_title = itemView.findViewById(R.id.taskname);
}
private void Image_Title(String title)
{
image_title.setText(title);
}
}
#Override
public void onStart() {
super.onStart();
FirebaseAuth mauth = FirebaseAuth.getInstance();
String userod = mauth.getCurrentUser().getUid();
myref = FirebaseDatabase.getInstance().getReference("Yourself").child(userod).child("task");
setmFirebaseAdapter(new FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder>(
taskdata.class, R.layout.taskitem, ShowDataViewHolder.class, myref.orderByValue()) {
public void populateViewHolder(final ShowDataViewHolder viewHolder, taskdata model, final int position) {
viewHolder.Image_Title(model.getTaskname());
}
});
recyclerView.setAdapter(getmFirebaseAdapter());
myref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getValue() == null){
Toast.makeText(getContext(),"No Bookmarks added yet!",Toast.LENGTH_SHORT).show();
}else {
mFirebaseAdapter.notifyItemChanged(0);
mFirebaseAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mFirebaseAdapter.notifyItemInserted(taskdata2.size()-1);
}
If you need more help on the code please go to my github - https://github.com/afreakyelf/Yourself/blob/master/app/src/main/java/com/example/rajat/yourself/taskadapterhome.java

To solve this, please just add the following lines of code inside the costructor:
public RecyclerAdapter(List<outflow> list, account_preview context) {
this.list = list
this.context = context
}

Related

my application that it crashes when I try to use the adapter

my code
**I have a UserAdapter, and a Search Fragment and the user_item and user class. The problem is, the three Click Listeners to open the "Search Fragment " the app crashe!! and close.
i hope so i give u good explanation for the problem
and thanks for the help in advance
**
public class SearchFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> userList;
EditText search_bar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_search, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
search_bar = view.findViewById(R.id.search_bar);
userList = new ArrayList<>();
userAdapter = new UserAdapter(getContext(), userList, true);
recyclerView.setAdapter(userAdapter);
readUsers();
search_bar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
searchUsers(charSequence.toString().toLowerCase());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
private void searchUsers(String s){
Query query = FirebaseDatabase.getInstance().getReference("Users").orderByChild("username")
.startAt(s)
.endAt(s+"\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readUsers() {
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
userList.add(user);
}
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
** my code class Use**
public class User {
private String id;
private String username;
private String fullname;
private String imageurl;
private String bio;
public User(String id, String username, String fullname, String imageurl, String bio) {
this.id = id;
this.username = username;
this.fullname = fullname;
this.imageurl = imageurl;
this.bio = bio;
}
public User() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
}
my code UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ImageViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean isFragment;
private FirebaseUser firebaseUser;
public UserAdapter(Context context, List<User> users, boolean isFragment){
mContext = context;
mUsers = users;
this.isFragment = isFragment;
}
#NonNull
#Override
public UserAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final UserAdapter.ImageViewHolder holder, final int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(position);
holder.btn_follow.setVisibility(View.VISIBLE);
isFollowing(user.getId(), holder.btn_follow);
holder.username.setText(user.getUsername());
holder.fullname.setText(user.getFullname());
Glide.with(mContext).load(user.getImageurl()).into(holder.image_profile);
if (user.getId().equals(firebaseUser.getUid())){
holder.btn_follow.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFragment) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity) mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
} else {
Intent intent = new Intent(mContext, Main2Activity.class);
intent.putExtra("publisherid", user.getId());
mContext.startActivity(intent);
}
}
});
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.btn_follow.getText().toString().equals("follow")) {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).setValue(true);
addNotification(user.getId());
} else {
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).removeValue();
}
}
});
}
private void addNotification(String userid){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("userid", firebaseUser.getUid());
hashMap.put("text", "started following you");
hashMap.put("postid", "");
hashMap.put("ispost", false);
reference.push().setValue(hashMap);
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public TextView fullname;
public CircleImageView image_profile;
public Button btn_follow;
public ImageViewHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username);
fullname = itemView.findViewById(R.id.fullname);
image_profile = itemView.findViewById(R.id.image_profile);
btn_follow = itemView.findViewById(R.id.btn_follow);
}
}
private void isFollowing(final String userid, final Button button){
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Follow").child(firebaseUser.getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(userid).exists()){
button.setText("following");
} else{
button.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
** user_item**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/image_profile"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/image_profile"
android:layout_marginStart="5dp"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/username"
android:text="username"
android:maxLines="1"
android:textStyle="bold"
android:textColor="#color/colorPrimaryDark"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fullname"
android:text="full_name"
android:maxLines="1"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="30dp"
android:background="#drawable/button_background"
android:id="#+id/btn_follow"
android:textColor="#color/colorPrimary"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</RelativeLayout>
stack trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: commenting, PID: 24881
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatButton cannot be cast to androidx.recyclerview.widget.RecyclerView
at commenting.Fragment.SearchFragment.onCreateView(SearchFragment.java:47)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
I/Process: Sending signal. PID: 24881 SIG: 9
Fragment.SearchFragment
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment.SearchFragment">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bar"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
android:id="#+id/toolbar">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_search_light"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/search_bar"
android:background="#android:color/transparent"
android:hint="search_bar"
android:layout_marginStart="10dp"
android:inputType="text"/>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bar"
android:id="#+id/recycler_view"/>
</RelativeLayout>
It looks like your search fragment layout doesn't have the RecyclerView component and the button on that layout has the recycler_view id which you try to use to inflate your RecyclerView. That's why you're getting this exception.
Add a RecyclerView to your layout and set its id to recycler_view so that you can grab the RV in your code.

RecyclerView inside RecyclerViewAdapter does not show any item?

I am trying to create recyclerview inside recyclerview which is retrieving the data from Firebase.
So far, I have two recyclerview adapters. GenreAdapter and AnimeInsideGenreAdapter classes.
I was able to show GenreAdapter data into my HomeFragment, but the AnimeInsideGenreAdapter is not showing any data and I have no idea why. I've been looking for my problem on Google but still not getting any luck.
So here are my classes and layouts:
GenreAdapter.class
public class GenreAdapter extends RecyclerView.Adapter {
private List<Genre> genreList;
private Context context;
private List<Anime> perAnimes;
private RecyclerView rvPerAnime;
private RecyclerView.Adapter adapterPerAnime;
class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
FontAppCompatTextView genre_id, genre_title;
LinearLayout main;
public ViewHolder(final View itemView) {
super(itemView);
main = itemView.findViewById(R.id.main_layout);
genre_id = itemView.findViewById(R.id.genre_id);
genre_title = itemView.findViewById(R.id.genre_title);
}
}
public GenreAdapter(List<Genre> genreList, Context context) {
this.genreList = genreList;
this.context = context;
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_genre, parent, false));
}
public void onBindViewHolder(ViewHolder holder, int position) {
Genre genre = this.genreList.get(position);
holder.genre_id.setText(genre.id);
holder.genre_title.setText(genre.genre);
perAnimes = new ArrayList<>();
DatabaseReference databaseAnime = FirebaseDatabase.getInstance().getReference("anime");
Query query_anime = databaseAnime.orderByChild("genreid").equalTo(genre.id);
query_anime.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
perAnimes.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Anime anime = snapshot.getValue(Anime.class);
perAnimes.add(anime);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
perAnimes.sort(new Comparator<Anime>() {
#Override
public int compare(Anime compare1, Anime compare2) {
return compare1.getTitle().compareToIgnoreCase(compare2.getTitle());
}
});
}
adapterPerAnime.notifyDataSetChanged();
} else {
perAnimes.clear();
adapterPerAnime.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
rvPerAnime = holder.itemView.findViewById(R.id.rvanime);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rvPerAnime.setLayoutManager(linearLayoutManager);
rvPerAnime.setHasFixedSize(true);
adapterPerAnime = new AnimeInsideGenreAdapter(perAnimes, context);
rvPerAnime.setAdapter(adapterPerAnime);
Animation up_from_bottom = AnimationUtils.loadAnimation(context, R.anim.up_from_bottom);
holder.itemView.startAnimation(up_from_bottom);
}
public int getItemCount() {
return this.genreList.size();
}
}
item_genre.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.pixplicity.fontview.FontAppCompatTextView
android:id="#+id/genre_title"
style="#style/FontTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="2"
android:singleLine="true"
android:text="Genre Anime"
android:textColor="#f59e24"
android:textSize="14dp"
android:textStyle="bold" />
<com.pixplicity.fontview.FontAppCompatTextView
android:id="#+id/genre_id"
style="#style/FontTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="ID Genre"
android:textColor="#7c7c7c"
android:textSize="12dp"
android:visibility="gone" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rvanime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp" />
</LinearLayout>
AnimeInsideGenreAdapter.class
public class AnimeInsideGenreAdapter extends RecyclerView.Adapter<AnimeInsideGenreAdapter.ViewHolder> {
List<Anime> perAnimes;
private Context context;
private Random mRandom = new Random();
class ViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder {
public FontAppCompatTextView anime_id, anime_title;
public ImageView img_anime;
public LinearLayout main;
public ViewHolder(final View itemView) {
super(itemView);
main = itemView.findViewById(R.id.main_layout);
anime_id = itemView.findViewById(R.id.anime_id);
anime_title = itemView.findViewById(R.id.anime_title);
img_anime = itemView.findViewById(R.id.img_anime);
Animation up_from_bottom = AnimationUtils.loadAnimation(itemView.getContext(), R.anim.up_from_bottom);
itemView.startAnimation(up_from_bottom);
}
}
public AnimeInsideGenreAdapter(List<Anime> perAnimes, Context context) {
this.perAnimes = perAnimes;
this.context = context;
}
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_anime_inside_genre, parent, false));
}
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Anime perAnime = this.perAnimes.get(position);
holder.anime_id.setText(perAnime.getId());
holder.anime_title.setText(perAnime.getTitle());
Toast.makeText(context, perAnime.toString(), Toast.LENGTH_SHORT).show();
Picasso.with(context).load(perAnime.getImgcover()).fit().into(holder.img_anime);
holder.img_anime.getLayoutParams().width = getRandomIntInRange(270,200);
holder.img_anime.getLayoutParams().height = 250;
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
}
public int getItemCount() {
return this.perAnimes.size();
}
// Custom method to get a random number between a range
protected int getRandomIntInRange(int max, int min){
return mRandom.nextInt((max-min)+min)+min;
}
}
item_anime_inside_genre.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<com.pixplicity.fontview.FontAppCompatTextView
android:id="#+id/anime_id"
style="#style/FontTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="2"
android:singleLine="true"
android:text="Anime ID"
android:textColor="#f59e24"
android:textSize="14dp"
android:textStyle="bold" />
<ImageView
android:id="#+id/img_anime"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"/>
<com.pixplicity.fontview.FontAppCompatTextView
android:id="#+id/anime_title"
style="#style/FontTextViewStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Anime Title"
android:textColor="#7c7c7c"
android:textSize="12dp" />
</LinearLayout>
</android.support.v7.widget.CardView>
Genre.class
public class Genre {
String id;
String genre;
public Genre() {
}
public Genre(String id, String genre) {
this.id = id;
this.genre = genre;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}}
Anime.class
public class Anime {
String id;
String genreid;
String title;
String description;
String imgcover;
public Anime() {
}
public Anime(String id, String genreid, String title, String description, String imgcover) {
this.id = id;
this.genreid = genreid;
this.title = title;
this.description = description;
this.imgcover = imgcover;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGenreid() {
return genreid;
}
public void setGenreid(String genreid) {
this.genreid = genreid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImgcover() {
return imgcover;
}
public void setImgcover(String imgcover) {
this.imgcover = imgcover;
}}
I need to show the anime list from Firebase inside each genres adapter.
Any help will be much appreciated.
Thank you.

RecyclerView doesn't display any item view at load

I am retrieving JSON data and parcing it by Retrofit. I want to display it on RecyclerView but can't make it display the views. Where am I doing it wrong? Here MainActivity, Model and ListFlowerAdapter are given
public class MainActivity extends AppCompatActivity {
private ListFlowerAdapter mListFlowerAdapter;
private RecyclerView mRecyclerView;
private RetrofitClient mRetrofitClient;
LinearLayoutManager linearLayoutManager;
//private List<FlowerModel> myFlowers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configViews();
mRetrofitClient = new RetrofitClient();
Call<List<FlowerModel>> listCall = mRetrofitClient.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<FlowerModel>>() {
#Override
public void onResponse(Call<List<FlowerModel>> call, Response<List<FlowerModel>> response) {
if (response.isSuccessful()) {
List<FlowerModel> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
FlowerModel flowerModel = flowerList.get(i);
mListFlowerAdapter.addFlower(flowerModel);
}
} else {
int sc = response.code();
switch (sc) {
}
}
}
#Override
public void onFailure(Call<List<FlowerModel>> call, Throwable t) {
}
});
}
private void configViews() {
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mListFlowerAdapter = new ListFlowerAdapter();
mRecyclerView.setAdapter(mListFlowerAdapter);
//mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false));
//mListFlowerAdapter = new ListFlowerAdapter();
// mRecyclerView.setAdapter(mListFlowerAdapter);
}
}
ListFlowerAdapter class
public class ListFlowerAdapter extends RecyclerView.Adapter<ListFlowerAdapter.MyViewHolder> {
private static final String TAG = ListFlowerAdapter.class.getSimpleName();
private Context context;
private List<FlowerModel> myFlowers;
public ListFlowerAdapter() {
myFlowers = new ArrayList<>();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, null, false);
return new MyViewHolder(row);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
FlowerModel currFlower = myFlowers.get(position);
holder.mName.setText(currFlower.getName());
holder.mPrice.setText(Double.toString(currFlower.getPrice()));
Picasso.with(holder.itemView.getContext()).load("http://services.hanselandpetal.com/photos/" + currFlower.getPhoto()).into(holder.mPhoto);
}
#Override
public int getItemCount() {
return myFlowers.size();
}
public void addFlower(FlowerModel flowerModel) {
myFlowers.add(flowerModel);
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView mPhoto;
private TextView mName, mPrice;
public MyViewHolder(View itemView) {
super(itemView);
mPhoto = itemView.findViewById(R.id.flower_photo);
mName = itemView.findViewById(R.id.flower_name);
mPrice = itemView.findViewById(R.id.flower_price);
}
}
}
FlowerModel class
public class FlowerModel implements Serializable {
#Expose
private String category;
#Expose
private String price;
#Expose
private String instructions;
#Expose
private String photo;
#Expose
private String name;
#Expose
private int productId;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/flower_photo"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/flower_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:text="Large Text" />
<TextView
android:id="#+id/flower_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:text="Medium Text" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Downloading" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:visibility="visible" />
Could you help me with the issue, please? Thank you very much.
Don't notify your adapter recursively,
Your code :
for (int i = 0; i < flowerList.size(); i++) {
FlowerModel flowerModel = flowerList.get(i);
mListFlowerAdapter.addFlower(flowerModel); // Called from here
}
Code from adapter
public void addFlower(FlowerModel flowerModel) {
myFlowers.add(flowerModel);
notifyDataSetChanged(); // Notifying everytime
}
Instead, you should add all data to adapter and notify only once : (Updated code)
for (int i = 0; i < flowerList.size(); i++) {
FlowerModel flowerModel = flowerList.get(i);
mListFlowerAdapter.addFlower(flowerModel);
}
mListFlowerAdapter.notifyDataSetChanged(); // Notify like this
Code from adapter
public void addFlower(FlowerModel flowerModel) {
myFlowers.add(flowerModel);
//notifyDataSetChanged(); Remove from here
}
Pass activity context to the adapter and use that context for populating item on list view.
private Context mContext;
public ListFlowerAdapter(Context context) {
myFlowers = new ArrayList<>();
this.mContext = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View row = LayoutInflater.from(mContext).inflate(R.layout.row_item, parent, false);
return new MyViewHolder(row);
}
From activity send the activity context for initializing the adapter like this
mListFlowerAdapter = new ListFlowerAdapter(this);
And for adding a new item
public void addFlowers(List<FlowerModel> flowerModels) {
for (int i = 0; i < flowerModels.size(); i++) {
FlowerModel flowerModel = flowerModels.get(i);
myFlowers.add(flowerModel);
}
notifyDataSetChanged();
}
And successful response just send the list for updating the adapter
List<FlowerModel> flowerList = response.body();
mListFlowerAdapter.addFlowers(flowerList);
Hope this will help.
Try to remove this line:
mRecyclerView.setHasFixedSize(true);
And add this in the XML file:
android:fillViewport="true"
Without that line, your RecyclerView content initial height is 0 (empty list), and with the fixed size it can't grow although you add items to the adapter.

RecyclerView﹕ No adapter attached; skipping layout in fragment

I have been reading the different answers here on StackOverflow and tried to implement their solutions but I am still getting the error:
RecyclerView﹕ No adapter attached; skipping layout,
So I initialize my recycler view in onCreateView in my fragment like this :
public class StatusFragment extends Fragment {
DatabaseReference databaseStatus;
ProgressDialog progressDialog;
List<ElectricityClass> list = new ArrayList<ElectricityClass>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
public StatusFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_status, container, false);
recyclerView = rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading Data from Firebase Database");
progressDialog.show();
databaseStatus = FirebaseDatabase.getInstance().getReference().child("Electricity");
databaseStatus.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
ElectricityClass electricityClass = dataSnapshot.getValue(ElectricityClass.class);
list.add(electricityClass);
}
recyclerView.setLayoutManager(new LinearLayoutManager(getContext().getApplicationContext()));
adapter = new RecyclerViewAdapter(getContext().getApplicationContext(), list);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
return rootView;
}
}
my RecyclerViewAdapter class :
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<ElectricityClass> dataList;
public RecyclerViewAdapter(Context context, List<ElectricityClass> list) {
this.dataList = list;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ElectricityClass studentDetails = dataList.get(position);
holder.StudentNameTextView.setText(studentDetails.getName());
holder.StudentNumberTextView.setText(studentDetails.getType());
}
#Override
public int getItemCount() {
return dataList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView StudentNameTextView;
public TextView StudentNumberTextView;
public ViewHolder(View itemView) {
super(itemView);
StudentNameTextView = itemView.findViewById(R.id.ShowStudentNameTextView);
StudentNumberTextView = itemView.findViewById(R.id.ShowStudentNumberTextView);
}
}
}
My list Electricity Class :
class ElectricityClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public ElectricityClass() {
// Required empty public constructor
}
public ElectricityClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString){
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
and here is my The layout in the fragment:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
And the layout of an item:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1"
android:padding="10dp">
<TextView
android:id="#+id/StudentName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Student Name: "
android:textColor="#000"
android:textSize="20dp" />
<TextView
android:id="#+id/ShowStudentNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Show Student Name"
android:textColor="#000"
android:textSize="20dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/StudentName"
android:layout_toEndOf="#+id/StudentName"
android:layout_marginLeft="19dp"
android:layout_marginStart="19dp" />
<TextView
android:id="#+id/StudentNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Phone Number: "
android:textColor="#000"
android:textSize="20dp"
android:layout_below="#+id/StudentName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/ShowStudentNumberTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Show Number"
android:textColor="#000"
android:textSize="20dp"
android:layout_marginLeft="11dp"
android:layout_marginStart="11dp"
android:layout_below="#+id/ShowStudentNameTextView"
android:layout_toRightOf="#+id/StudentNumber"
android:layout_toEndOf="#+id/StudentNumber" />
</RelativeLayout>
</android.support.v7.widget.CardView>
now it shows,
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged()' on a null object reference
here I define my List2
public class StatusFragment extends Fragment {
DatabaseReference databaseStatus;
ProgressDialog progressDialog;
List<ElectricityClass> list2 = new ArrayList<ElectricityClass>();
List<ElectricityClass> list = new ArrayList<ElectricityClass>();
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
and inside onDataChanged(),
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
ElectricityClass electricityClass = dataSnapshot.getValue(ElectricityClass.class);
list2.add(electricityClass);
}
refreshRv((ArrayList<ElectricityClass>) list2);
adapter = new RecyclerViewAdapter(getContext().getApplicationContext(), list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
private void refreshRv(ArrayList<ElectricityClass> list2){
list.clear();
list.addAll(list2);
}
You are doing this wrong setting layout and adapter inside that onDataChange method. Rather create a private function that will instantiate your adapter, will set it to RecyclerView and will set layout manager too. (you may want to define the list from constructor of the adapter also like this list = new ArrayList<>(); )
When you are done with this function, call it in onCreateView method of the fragment, and inside onDataChange just call a refresh function(also private) that will clear your list(or not depending on your behaviour), add all new values and notify your adapter using adapter.notifyDataSetChanged() method.
Hope this will help you :)
EDIT: as someone mentioned in a comment, your error is just telling you that adapter is not set to RecyclerView, probably because onDataChanged() was not called. My explanation from above will solve the problem for sure
EDIT:
Define another list let's say list2, replace list.add(); with list2.add(); inside that for from onDataSetChanged();
Then after for, call this function
private void refreshRv(ArrayList<YourDataType> list2){
list.clear();
list.addAll(list2);
adapter.notifyDataSetChanged();
}
this works for me
#felicity just add this function properly
private void refreshRv(ArrayList<YourDataType> list2)
{
list.clear();
list.addAll(list2);
adapter.notifyDataSetChanged();
}
as lonut J.Bejan said

How can I populate my data using recyclerview? [duplicate]

My main activity shows an empty RecyclerView. My CardView is not displayed.
The data is stored in a Firebase Database but is not displayed for some reason.
I have also searched the web but nothing helped me. I tried everything listed on web as well as on Stack Overflow.
MainActivity.java
public class MainActivity1 extends AppCompatActivity {
private RecyclerView mQuestionList;
private CardView mCardVieww;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference mDatabaseUsers;
private LinearLayoutManager layoutManager;
private DatabaseReference mDatabaseCurrentUsers;
private DatabaseReference mDatabaseLike;
private boolean mProcessLike = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
mAuth=FirebaseAuth.getInstance();
mAuthListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser()== null){
Intent loginIntent=new Intent(MainActivity1.this,LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mDatabase= FirebaseDatabase.getInstance().getReference().child("Question");
mDatabaseUsers=FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseLike=FirebaseDatabase.getInstance().getReference().child("Likes");
mDatabaseUsers.keepSynced(true);
mDatabaseLike.keepSynced(true);
mDatabase.keepSynced(true);
mQuestionList=(RecyclerView) findViewById(R.id.question_list);
layoutManager=new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mQuestionList.setHasFixedSize(true);
mQuestionList.setLayoutManager(layoutManager);
checkUserExist();
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter <Question,QuestionViewHolder> fireRecyclerAdapter = new FirebaseRecyclerAdapter <Question,QuestionViewHolder>(
Question.class,
R.layout.question,
QuestionViewHolder.class,
mDatabase
){
#Override
protected void populateViewHolder(QuestionViewHolder viewHolder,Question model, int position){
final String post_key = getRef(position).getKey()
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(),model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setLikeBtn(post_key);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(MainActivity1.this,post_key,Toast.LENGTH_LONG).show();
Intent singleQuestionIntent=new Intent(MainActivity1.this,QuestionSingleActivity.class);
singleQuestionIntent.putExtra("question_id",post_key);
startActivity(singleQuestionIntent);
}
});
viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessLike = true;
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessLike) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessLike = false;
} else {
mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
mProcessLike = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
};
mQuestionList.setHasFixedSize(true);
mQuestionList.setLayoutManager(layoutManager);
mQuestionList.setAdapter(fireRecyclerAdapter);
}
//cgeck user exist or not
private void checkUserExist() {
if (mAuth.getCurrentUser() != null) {
final String user_id = mAuth.getCurrentUser().getUid();
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(user_id)) {
Intent setupIntent = new Intent(MainActivity1.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(setupIntent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
public static class QuestionViewHolder extends RecyclerView.ViewHolder{
View mView;
ImageButton mLikeBtn;
DatabaseReference mDatabaseLike;
FirebaseAuth mAuth;
public QuestionViewHolder(View itemView) {
super(itemView);
mView=itemView;
mLikeBtn=(ImageButton) mView.findViewById(R.id.likeBtn);
mDatabaseLike= FirebaseDatabase.getInstance().getReference().child("Likes");
mAuth=FirebaseAuth.getInstance();
mDatabaseLike.keepSynced(true);
}
public void setLikeBtn(final String post_key){
mDatabaseLike.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
mLikeBtn.setImageResource(R.mipmap.thumb_grey);
}else{
mLikeBtn.setImageResource(R.mipmap.thumb_grey);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setTitle(String title){
TextView post_title=(TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc=(TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setUsername(String username){
TextView post_username=(TextView) mView.findViewById(R.id.post_username);
post_username.setText(username);
}
public void setImage(final Context ctx, final String image){
final ImageView post_image=(ImageView) mView.findViewById(R.id.post_image);
//Picasso.with(ctx).load(image).into(post_image);
Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(image).into(post_image);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_add){
startActivity(new Intent(MainActivity1.this,PostActivity.class));
}
if(item.getItemId()==R.id.action_logout){
logout();
}
if(item.getItemId()==R.id.action_Qp){
startActivity(new Intent(MainActivity1.this,MainActivity2.class));
}
return super.onOptionsItemSelected(item);
}
private void logout() {
mAuth.signOut();
}
}
Question.java
public class Question {
private CardView mCardView;
private String title;
private String desc;
private String image;
private String username;
public Question(){
}
public Question(String title, String desc, String image,String username) {
this.title = title;
this.desc = desc;
this.image = image;
this.username = username;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
activity_main1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.akhil.rtmnuforum.MainActivity1">
<android.support.v7.widget.RecyclerView
android:id="#+id/question_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
question.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:visibility="visible"
tools:context="com.example.akhil.rtmnuforum.MainActivity1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/post_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#mipmap/add_btn" />
<TextView
android:id="#+id/post_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Post Title Goes here"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/post_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Question Description Goes here" />
<TextView
android:id="#+id/post_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="username"
android:textSize="12dp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/likeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="#color/cardview_light_background"
app:srcCompat="#mipmap/ic_thumb_up_black_24dp" />
</LinearLayout>
</android.support.v7.widget.CardView>

Categories

Resources