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.
Related
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.
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();
I'm using a Spinner and a RecyclerView in a Fragment in my Android project.
My RecyclerView does not show any data until I select an item in the Spinner.
What should I do to show the RecyclerView's result without selecting an item from the Spinner?
at the first recycler should show 10 attraction.
My code:
Attraction.java
package com.rayantec.reservation.reservationdemo.Model;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.rayantec.reservation.reservationdemo.Adapter.AttractionAdapter;
import com.rayantec.reservation.reservationdemo.G;
import com.rayantec.reservation.reservationdemo.Lists.AttractionList;
import com.rayantec.reservation.reservationdemo.Lists.CityList;
import com.rayantec.reservation.reservationdemo.R;
import com.toptoche.searchablespinnerlibrary.SearchableSpinner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Attractions extends Fragment {
RecyclerView recyclerView;
ArrayList<AttractionList> AttractionData = new ArrayList<>();
public SearchableSpinner spinnerCitiest;
ArrayList<CityList> cityLists = new ArrayList<>();
ProgressDialog progressDialog;
public void showCity(View view) {
spinnerCitiest = (SearchableSpinner) view.findViewById(R.id.SpinnerCitiestId);
spinnerCitiest.setTitle("Please Select City");
spinnerCitiest.setPositiveButton("Ok");
//spinnerCitiest.setSelection(2);
JsonArrayRequest JsonObjectRequest = new JsonArrayRequest(Request.Method.GET, G.serverURL + "/android/jsyncs/getdata/city", null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//progressDialog.dismiss();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonOBJ = response.getJSONObject(i);
String id = jsonOBJ.getString("id");
String title = jsonOBJ.getString("title");
cityLists.add(new CityList(id, title));
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//progressDialog.dismiss();
Toast.makeText(G.context, "Server Connection error", Toast.LENGTH_SHORT).show();
}
});
JsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(7000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(G.context);
requestQueue.add(JsonObjectRequest);
ArrayAdapter<CityList> adapterCities = new ArrayAdapter<CityList>(G.context, android.R.layout.simple_spinner_item, cityLists);
adapterCities.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCitiest.setAdapter(adapterCities);
spinnerCitiest.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
CityList cityList = (CityList) adapterView.getSelectedItem();
Toast.makeText(G.context, "City ID: " + cityList.getId() + ", City Name : " + cityList.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
public void showRandomAttractions(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.RecyclerAttracionId);
JsonArrayRequest JsonObjectRequests = new JsonArrayRequest(Request.Method.GET, G.serverURL + "/android/jsyncs/getdata/randattraction", null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressDialog.dismiss();
//AttractionList sampledata = new AttractionList();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonOBJs = response.getJSONObject(i);
String id = jsonOBJs.getString("id");
String title = jsonOBJs.getString("title");
String imageUrl = jsonOBJs.getString("imageUrl");
String location = jsonOBJs.getString("location");
String type = jsonOBJs.getString("type");
String body = jsonOBJs.getString("body");
AttractionData.add(new AttractionList(id, title, body, location, imageUrl, type));
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(G.context, "Server Connection error", Toast.LENGTH_SHORT).show();
}
});
JsonObjectRequests.setRetryPolicy(new DefaultRetryPolicy(7000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(G.context);
requestQueue.add(JsonObjectRequests);
recyclerView.setLayoutManager(new LinearLayoutManager(G.context, LinearLayoutManager.VERTICAL, false));
AttractionAdapter attractionAdapter = new AttractionAdapter(AttractionData);
recyclerView.setAdapter(attractionAdapter);
}
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.attraction, container, false);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Please wait ...");
progressDialog.setCancelable(false);
progressDialog.show();
showCity(view);
showRandomAttractions(view);
return view;
}
}
Attraction.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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:id="#+id/cardviewattraction"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:padding="3dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.toptoche.searchablespinnerlibrary.SearchableSpinner
android:id="#+id/SpinnerCitiestId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:padding="3dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerAttracionId"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/cardviewattraction"
tools:ignore="MissingConstraints" />
</android.support.constraint.ConstraintLayout>
AttractionAdapter
package com.rayantec.reservation.reservationdemo.Adapter;
import android.support.annotation.NonNull;
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 com.rayantec.reservation.reservationdemo.Lists.AttractionList;
import com.rayantec.reservation.reservationdemo.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class AttractionAdapter extends RecyclerView.Adapter<AttractionAdapter.AttractionViewHolder> {
ArrayList<AttractionList> attractionArrayList;
public AttractionAdapter(ArrayList<AttractionList> attractions) {
attractionArrayList = new ArrayList<>();
attractionArrayList = attractions;
}
#NonNull
#Override
public AttractionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_attraction, parent, false);
return new AttractionViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AttractionViewHolder holder, int position) {
AttractionList dataModel = attractionArrayList.get(position);
holder.txtTitle.setText(dataModel.getTitle());
holder.txtBody.setText(dataModel.getBody());
holder.txtType.setText(dataModel.getType());
holder.txtLocation.setText(dataModel.getLocation());
Picasso.get().load(dataModel.getImgUrl()).resize(130, 100).centerCrop().into(holder.imgAttraction);
}
#Override
public int getItemCount() {
return attractionArrayList.size();
}
public class AttractionViewHolder extends RecyclerView.ViewHolder{
public ImageView imgAttraction;
public TextView txtTitle;
public TextView txtBody;
public TextView txtLocation;
public TextView txtType;
public AttractionViewHolder(View itemView) {
super(itemView);
imgAttraction = (ImageView)itemView.findViewById(R.id.img_recycler_attraction);
txtTitle = (TextView)itemView.findViewById(R.id.txt_recycler_attractionTitle);
txtBody = (TextView)itemView.findViewById(R.id.txt_recycler_attractionBody);
txtLocation = (TextView)itemView.findViewById(R.id.txt_recycler_attractionPositions);
txtType = (TextView)itemView.findViewById(R.id.txt_recycler_attractionType);
}
//
}
}
AttractionList.java
package com.rayantec.reservation.reservationdemo.Lists;
public class AttractionList {
private String id;
private String title;
private String body;
private String location;
private String imgUrl;
public AttractionList(String id, String title, String body, String location, String imgUrl, String type) {
this.id = id;
this.title = title;
this.body = body;
this.location = location;
this.imgUrl = imgUrl;
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
There are a few things that you should test, did you check to see if you're receiving the onResponse callback in your showRandomAttractions(View view) method? This would verify that the Get call is working as intended.
If you are receiving that onResponse call, try calling attractionAdapter.notifyDataSetChanged() after your for-loop when you're done adding data to your AttractionData ArrayList. It would look like this:
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonOBJs = response.getJSONObject(i);
String id = jsonOBJs.getString("id");
String title = jsonOBJs.getString("title");
String imageUrl = jsonOBJs.getString("imageUrl");
String location = jsonOBJs.getString("location");
String type = jsonOBJs.getString("type");
String body = jsonOBJs.getString("body");
AttractionData.add(new AttractionList(id, title, body, location, imageUrl, type));
// Notify your adapter that its data has changed.
attractionAdapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
You can check out this documentation for more info on how notifyDataSetChanged works.
I believe your request to the server to collect the Data is Asynchronous and happens on a Worker Thread. If that's the case then your View is rendered before actually getting the data.
I would suggest to add a setData function in your adapter:
public void setData(ArrayList<Attractions> attractions){
this.attractionArrayList = attractions
notifyDataSetChanged()
}
Then on your activity when you get the response and build the array of attraction, just call adapter.setData(attractions)
UPDATE:
Make sure to set your adapter when the view is actually initialized, so you need to call it on onViewCreated:
public void onViewCreated(View view,Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
showCity(view);
showRandomAttractions(view);
}
by replace this line after try/catch this problem solved
recyclerView.setLayoutManager(new LinearLayoutManager(G.context, LinearLayoutManager.VERTICAL, false));
AttractionAdapter attractionAdapter = new AttractionAdapter(AttractionData);
recyclerView.setAdapter(attractionAdapter);
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();
}