I am trying to get a list of posts to display on a RecyclerView in a fragment in Android Studio using Java I do have the ".setAdapter()" code displayed but I am still receiving this error message and I have been stuck on this for a week. I am sure it is something Stupid but here is my fragment, my adapter, and the XML file for the fragment
Fragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.zapster_picture_sharing.Adapter.PostAdapter;
import com.example.zapster_picture_sharing.Model.Post;
import com.example.zapster_picture_sharing.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post> postLists;
private List<String> followingList;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
progressBar = view.findViewById(R.id.progress_circular);
checkFollowing();
recyclerView = view.findViewById(R.id.recycler_view_story);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists, true);
recyclerView.setAdapter(postAdapter);
return view;
}
private void checkFollowing(){
followingList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followingList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
followingList.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readPosts(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Post post = snapshot.getValue(Post.class);
for(String id:followingList){
if(post.getPublisher().equals(id)){
postLists.add(post);
}
}
}
postAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
PostAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.zapster_picture_sharing.Model.Post;
import com.example.zapster_picture_sharing.Model.User;
import com.example.zapster_picture_sharing.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
public List<Post> mPosts;
//private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts, boolean b){
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Post post = mPosts.get(i);
Glide.with(mContext).load(post.getPostimage()).into(viewHolder.post_image);
if (post.getDescription().equals("")){
viewHolder.description.setVisibility(View.GONE);
} else {
viewHolder.description.setVisibility(View.VISIBLE);
viewHolder.description.setText(post.getDescription());
}
publisherInfo(viewHolder.image_profile, viewHolder.username, viewHolder.publisher, post.getPublisher());
}
#Override
public int getItemCount() {
return mPosts.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView image_profile, post_image, like, comment, save;
public TextView username, likes, publisher, description, comments;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
post_image = itemView.findViewById(R.id.post_image);
comments = itemView.findViewById(R.id.comments);
like = itemView.findViewById(R.id.like);
comment = itemView.findViewById(R.id.comment);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
publisher = itemView.findViewById(R.id.publisher);
description = itemView.findViewById(R.id.description);
}
}
private void publisherInfo(final ImageView image_profile, final TextView username, final TextView publisher, final String userid){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Glide.with(mContext).load(user.getImageurl()).into(image_profile);
username.setText(user.getUsername());
publisher.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
XML for the fragment
<?xml version="1.0" encoding="utf-8"?>
<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.HomeFragment">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="180dp"
android:layout_height="35dp"
android:src="#drawable/zapster_logo"
android:id="#+id/logo"
android:layout_marginLeft="-20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:src="#drawable/ic_inbox"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view_story"
android:layout_margin="5dp"
android:layout_below="#id/bar"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view"
android:layout_below="#id/recycler_view_story"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
Post Model
package com.example.zapster_picture_sharing.Model;
public class Post {
private String postid;
private String postimage;
private String description;
private String publisher;
public Post(String postid, String postimage, String description, String publisher){
this.postid = postid;
this.postimage = postimage;
this.description = description;
this.publisher = publisher;
}
public Post(){
}
public String getPostid() {
return postid;
}
public void setPostid(String postid) {
this.postid = postid;
}
public String getPostimage() {
return postimage;
}
public void setPostimage(String postimage) {
this.postimage = postimage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
In the XML, there are actually two instances of androidx.recyclerview.widget.RecyclerView.
But in your code, you only attach an adapter to one of them, which causes this warning.
require add setLayoutManager
postAdapter = new PostAdapter(getContext(), postLists, true);
recyclerView.setAdapter(postAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView#setLayoutManager(androidx.recyclerview.widget.RecyclerView.LayoutManager)
You are re-initializing postsList after calling your checkFollowing() method.
try
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists, true);
recyclerView.setAdapter(postAdapter);
checkFollowing();
Related
I am new to android development and am trying to bind recycler View with setAdapter but am getting this error "Cannot resolve method 'setAdapter' in 'ConstraintLayout' "
my mainActivity.java code is:
my main objective is to use ActivityMainBinding to bind recyclerView with setAdapter
package com.example.baatcheet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.baatcheet.usersAdapter.*;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.baatcheet.databinding.ActivityMainBinding;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
FirebaseDatabase database;
ArrayList<User> users;
usersAdapter UserAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
database = FirebaseDatabase.getInstance();
users = new ArrayList<>();
UserAdapter = new usersAdapter(this, users);
binding.recyclerView.setAdapter(UserAdapter);
database.getReference().child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users.clear();
for(DataSnapshot snapshot1 : snapshot.getChildren()){
User user = snapshot1.getValue(User.class);
users.add(user);
}
UserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
Toast.makeText(this,"Search Clicked" , Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(this , " setting Clicked" , Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.top_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
this is the part where i am getting an error -> binding.recyclerView.setAdapter(UserAdapter);
and it tells me to rename reference
what does this actually mean?
the activity_main.xml file is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:elevation="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu">
</com.google.android.material.bottomnavigation.BottomNavigationView>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/row_conversation"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
the users.java code is:
package com.example.baatcheet;
public class User {
private String uid,name,phoneNumber,profileImage;
public User(){
}
public User(String uid, String name, String phoneNumber, String profileImage) {
this.uid = uid;
this.name = name;
this.phoneNumber = phoneNumber;
this.profileImage = profileImage;
}
public void setUid(String uid) {
this.uid = uid;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setProfileImage(String profileImage) {
this.profileImage = profileImage;
}
public String getUid() {
return uid;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getProfileImage() {
return profileImage;
}
}
the usersAdapter.java code is:
package com.example.baatcheet;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baatcheet.databinding.RowConversationBinding;
import java.util.ArrayList;
public class usersAdapter extends RecyclerView.Adapter<usersAdapter.UsersViewHolder>{
Context context;
ArrayList<User> users;
public usersAdapter(Context context , ArrayList<User> users){
this.context = context;
this.users = users;
}
{
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_conversation,parent,false);
return new UsersViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UsersViewHolder holder, int position) {
User user = users.get(position);
holder.binding.userName.setText(user.getName());
}
#Override
public int getItemCount() {
return users.size();
}
public class UsersViewHolder extends RecyclerView.ViewHolder{
RowConversationBinding binding;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
binding = RowConversationBinding.bind(itemView);
}
}
}
In your layout file, it is the root ConstraintLayout that has the #+id/recyclerView id:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerView"
... />
You should move this id to the RecyclerView itself:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
... />
Once you do this, binding.recyclerView will refer to the RecyclerView instead of the ConstraintLayout.
If you need to access the ConstraintLayout via the view binding for some other reason, you can use binding.root.
I have recently created a chatting application, which gets crash due to these lines :-
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
t_username.setText(user.getUsername());
if (user.getImageURL().equals("No image")){
profile_image.setImageResource(R.drawable.profile_img);
} else {
//change this
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I don't understand why this crashes my application.
MainActivity.java :-
package com.dccodes.chugli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.dccodes.chugli.Adapter.OnItemClick;
import com.dccodes.chugli.Fragments.ChatsFragment;
import com.dccodes.chugli.Fragments.ProfileFragment;
import com.dccodes.chugli.Fragments.UsersFragment;
import com.dccodes.chugli.Model.Chat;
import com.dccodes.chugli.Model.User;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements OnItemClick {
boolean doubleBackToExitPressedOnce = false;
CircleImageView profile_image;
TextView t_username;
ProgressDialog dialog;
Typeface MR,MRR;
FirebaseUser firebaseUser;
DatabaseReference reference;
OnItemClick onItemClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.onItemClick = this;
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
profile_image = findViewById(R.id.profile_image);
final TabLayout tabLayout = findViewById(R.id.tab_layout);
final ViewPager viewPager = findViewById(R.id.view_pager);
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
}
});
t_username = findViewById(R.id.t_username);
t_username.setTypeface(MR);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
t_username.setText(user.getUsername());
if (user.getImageURL().equals("No image")){
profile_image.setImageResource(R.drawable.profile_img);
} else {
//change this
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
reference = FirebaseDatabase.getInstance().getReference("Chats");
dialog = com.dccodes.chugli.Utils.showLoader(MainActivity.this);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
int unread = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(firebaseUser.getUid()) && !chat.isIsseen()){
unread++;
}
}
if (unread == 0){
viewPagerAdapter.addFragment(ChatsFragment.newInstance(onItemClick), "Chats");
} else {
viewPagerAdapter.addFragment(ChatsFragment.newInstance(onItemClick), "("+unread+") Chats");
}
viewPagerAdapter.addFragment(UsersFragment.newInstance(onItemClick), "Users");
viewPagerAdapter.addFragment(new ProfileFragment(), "Profile");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if(dialog!=null){
dialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.logout:
FirebaseAuth.getInstance().signOut();
// change this code beacuse your app will crash
startActivity(new Intent(MainActivity.this, StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
}
return false;
}
#Override
public void onItemCLick(String uid, View view) {
ViewProfileActivity viewProfileActivity =
ViewProfileActivity.newInstance(uid,this);
viewProfileActivity.show(getSupportFragmentManager(),
"view_profile");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments;
private ArrayList<String> titles;
ViewPagerAdapter(FragmentManager fm){
super(fm);
this.fragments = new ArrayList<>();
this.titles = new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragment(Fragment fragment, String title){
fragments.add(fragment);
titles.add(title);
}
// Ctrl + O
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
private void status(String status){
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
status("offline");
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000); }
}
MainActivity.xml :-
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:background="#color/white"
android:orientation="vertical"
tools:context="com.dccodes.chugli.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dgreen"
android:padding="#dimen/padding_10_dp"
android:theme="#style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/MenuStyle">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/profile_img"
android:id="#+id/profile_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/t_username"
android:textSize="22sp"
android:layout_marginLeft="25dp"
android:textColor="#fff"
android:textStyle="bold"
android:layout_marginStart="25dp" />
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dgreen"
app:tabIndicatorColor="#fff"
app:tabSelectedTextColor="#fff"
app:tabTextColor="#fff"
tools:ignore="SpeakableTextPresentCheck,SpeakableTextPresentCheck" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:ignore="SpeakableTextPresentCheck,SpeakableTextPresentCheck" />
</LinearLayout>
I don't understand why I get this error, I have searched it everywhere, but I couldn't find the answer. I hope anyone will help me!
sorry in adavaced bcz i am first time askking question on stack flow so and if need any other please let me know
okk my firestore Collestion is like these collection("user").document(currentUserId).collection("AddBlog").document
and i need AddBlog document and last my field name of firestore is same to model.java variable
code of activity name Trial.java
package com.example.talkvirtual;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class TrialActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Model> dataList;
FirebaseFirestore db;
FirebaseAuth mAuth;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trial);
recyclerView = findViewById(R.id.recyclerViewTrial);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dataList = new ArrayList<>();
recyclerView.setAdapter(myAdapter);
myAdapter = new MyAdapter(dataList,this);
db = FirebaseFirestore.getInstance();
mAuth= FirebaseAuth.getInstance();
String currentUserId = mAuth.getCurrentUser().getUid();
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
}
}
code of adpater class name MyAdapter.java
package com.example.talkvirtual;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public MyAdapter(ArrayList<Model> listblogProfile, Context context) {
this.ListblogProfile = listblogProfile;
this.context = context;
}
private ArrayList<Model> ListblogProfile;
private Context context;
// private ShowActivity activity;
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_blog, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
Model model = ListblogProfile.get(position);
holder.blogTitleTv.setText(model.getBlogTitle());
holder.blogContentTv.setText(model.getBlogContent());
}
#Override
public int getItemCount() {
return ListblogProfile.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView blogTitleTv, blogContentTv;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
blogContentTv = itemView.findViewById(R.id.blogContentContainer);
blogTitleTv = itemView.findViewById(R.id.getTitleContainer);
}
}
}
code of my cardView xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layoutNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?attr/selectableItemBackgroundBorderless"
app:cardElevation="8dp"
android:layout_margin="10dp"
android:background="#color/light_dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/getTitleContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:textColor="#color/textColor"
android:textSize="24dp"
android:textStyle="bold"
android:padding="10dp"
/>
<TextView
android:id="#+id/blogContentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp"
android:textColor="#color/textColor"
android:hint="Blog Content"
android:textColorHint="#color/gray"
android:textSize="20dp"
android:padding="10dp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
code of model class
package com.example.talkvirtual;
public class Model {
String blogTitle;
String blogContent;
String id;
public Model(){}//empty constructor is neccessary firebase
public Model(String blogTitle, String blogContent, String id) {
this.blogTitle = blogTitle;
this.blogContent = blogContent;
this.id = id;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I think There are two mistake
1.Your adapter does not have the valid value
when you set it for the recyclerview
2.Your data is null because you don't add any member to it as well as the adapter.
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
myAdapter = new MyAdapter(dataList,this);
recyclerView.setAdapter(myAdapter);
I guess this should be work.
The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the image. As of now when one clicks the image it only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RECYCLERVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CARDVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.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="match_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="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MAIN ACTIVITY
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RECYCLERVIEWADAPTER
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
IMAGEADAPTER
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DATAADAPTER
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
just when the user clicked on an item do like me...
Intent i = new Intent(context,BigImageActivity);
intent.putExtra("image_url",iamge_url);
context.startActivity(i);
in big_image_layout.xml
<ImageView
android:id="#+id/iv_big_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
in onCreate BigImageActivity:
String img_url = getIntent.getStringExtra("image_url");
and for showing image use Glide:
Glide.with(context)
.load(img_url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.dontAnimate()
.into(iv_big_image);
and done!!!
I hope this useful for you.
I made it to show full images by fetching the url and parsing it to a new activity. Thanks for the positive responses
I tried to create a List with RecyclerView in Android. However, I don't understand why the RecyclerView could not load data properly. I tried to compare my codes with the example available online and I could not tell what is the difference between example codes and my codes.
Can anyone help to point out what is missing or what is wrong with my code?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="daozui.assignment3_task3.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
contact_arrangement.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/contactIcon_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/man"
android:layout_margin="10dp"/>
<TextView
android:id="#+id/contactName_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="30sp"
android:text="Name"
android:layout_toEndOf="#id/contactIcon_ID"
android:layout_marginTop="25dp"
android:layout_marginStart="25dp"/>
<TextView
android:id="#+id/contactRelationship_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFBEB9B9"
android:textSize="20sp"
android:text="Relationship"
android:layout_alignStart="#id/contactName_ID"
android:layout_below="#id/contactName_ID"/>
</RelativeLayout>
MainActivity.Java
package daozui.assignment3_task3;
import android.app.ListFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView theRecyclerView;
List<Contact> contactList;
ContactAdapter theAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createList();
theRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
theRecyclerView.setLayoutManager(new LinearLayoutManager(this));
theAdapter = new ContactAdapter(contactList);
theRecyclerView.setAdapter(theAdapter);
}
private void createList() {
contactList = new ArrayList<Contact>();
contactList.add(new Contact("Alex", "male", "Friends", "0123456789"));
contactList.add(new Contact("Mona", "female", "Friends", "9876543210"));
}
}
ContactAdapter.Java
package daozui.assignment3_task3;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.theViewHolder> {
private List<Contact> contacList;
public ContactAdapter(List<Contact> ContactList) {
this.contacList = ContactList;
}
#Override
public ContactAdapter.theViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_arrangement, parent, false);
return new theViewHolder(itemView);
}
#Override
public void onBindViewHolder(theViewHolder holder, int position) {
Contact contact = contacList.get(position);
holder.contactName.setText(contact.getName());
holder.contactRelationship.setText(contact.getRelationship());
if (contact.getGender().equals("male")) {
holder.contactIcon.setImageResource(R.drawable.man);
} else {
holder.contactIcon.setImageResource(R.drawable.woman);
}
}
#Override
public int getItemCount() {
return 0;
}
public static class theViewHolder extends RecyclerView.ViewHolder {
public TextView contactName, contactRelationship;
public ImageView contactIcon;
public theViewHolder(View itemView) {
super(itemView);
contactIcon = (ImageView) itemView.findViewById(R.id.contactIcon_ID);
contactName = (TextView) itemView.findViewById(R.id.contactName_ID);
contactRelationship = (TextView) itemView.findViewById(R.id.contactRelationship_ID);
// itemView.setOnClickListener(this);
}
// #Override
// public void onClick(View view)
// {
// int pos= getAdapterPosition();
// Toast.makeText(itemView.getContext(),contacList.get(pos).getContactNumber(),Toast.LENGTH_LONG);
// }
}
}
Contact.Java
package daozui.assignment3_task3;
public class Contact {
private String name;
private String gender;
private String relationship;
private String contactNumber;
public Contact(String Name, String Gender, String Relationship, String ContactNumber) {
this.name = Name;
this.gender = Gender;
this.relationship = Relationship;
this.contactNumber = ContactNumber;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getRelationship() {
return relationship;
}
public String getContactNumber() {
return contactNumber;
}
}
The problem is here:
#Override
public int getItemCount() {
return 0;
}
You should return the size of your list:
#Override
public int getItemCount() {
return contactList.size();
}
You should return the size of your collection here:
#Override
public void getItemCount(){
return contactList.size();
}
getItemCount() Returns the total number of items in the data set held by the adapter.
The int value that getItemCount() returns is the number of times the RecyclerView is going to look for data from your collection to bind.
notify your adapter that data is updated.!
notifyDataSetChanged();
#Override
public int getItemCount() {
return contactList.size();
}
In the event the list is null, use this simple ternary to avoid a null pointer exception;
#Override
public int getItemCount() {
return contactList == null ? 0 : contactList.size();
}