User image and full name are not displaying in AdapterView? - java

I am trying to implement a search bar for a social media app that displays users with a profile image at the right, the username and the full name aligned vertically next to the image and a follow button at the bottom right that only appears if the user is not following.
I am using a Firebase realtime database to pull data from and the username displays fine but the image and the full name are not displaying and the follow Button is not the right size, as you can see from the image below:
Wrong display
While I need to achieve this:
Correct display
Here is the xml for the user item that will populate the recycler view for the adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/image_profile"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/image_profile"
android:layout_marginStart="5dp"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="username"
android:maxLines="1"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/fullname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Full Name"
android:maxLines="1"/>
</LinearLayout>
<Button
android:id="#+id/btn_follow"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</RelativeLayout>
Here the User Adapter:
package com.andrea.uncut.ui.Adapter;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.andrea.uncut.R;
import com.andrea.uncut.ui.Model.User;
import com.andrea.uncut.ui.profile.ProfileFragment;
import com.bumptech.glide.Glide;
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.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder>{
private Context mContext;
private List<User> mUsers;
private FirebaseUser firebaseUser;
public UserAdapter(Context mContext, List<User> mUsers) {
this.mContext = mContext;
this.mUsers = mUsers;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final User user = mUsers.get(position);
holder.btn_follow.setVisibility(View.VISIBLE);
holder.username.setText(user.getUsername());
holder.fullname.setText(user.getFullname());
Glide.with(mContext).load(user.getImageURL()).into(holder.image_profile);
isFollowing(user.getId(), holder.btn_follow);
if (user.getId().equals(firebaseUser.getUid())){
holder.btn_follow.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = mContext.getSharedPreferences("PREFS", Context.MODE_PRIVATE).edit();
editor.putString("profileid", user.getId());
editor.apply();
((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
}
});
holder.btn_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.btn_follow.getText().toString().equals("follow")){
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).setValue(true);
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).setValue(true);
}else{
FirebaseDatabase.getInstance().getReference().child("Follow").child(firebaseUser.getUid())
.child("following").child(user.getId()).removeValue();
FirebaseDatabase.getInstance().getReference().child("Follow").child(user.getId())
.child("followers").child(firebaseUser.getUid()).removeValue();
}
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView username;
public TextView fullname;
public CircleImageView image_profile;
public Button btn_follow;
public ViewHolder(#NonNull View itemView){
super(itemView);
username = itemView.findViewById(R.id.username);
fullname = itemView.findViewById(R.id.fullname);
image_profile = itemView.findViewById(R.id.image_profile);
btn_follow = itemView.findViewById(R.id.btn_follow);
}
}
private void isFollowing(String userid, Button button){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("Follow").child(firebaseUser.getUid()).child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.child(userid).exists()){
button.setText("following");
}else{
button.setText("follow");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Thanks in advance for the help!

This could probably be due to wrap_content value for both the relative layout of user-item and button element.
So trying assigning fixed values to the layout and view.
Also, add font size and padding for the text in the button element to not look distorted or broken.

Related

Unable to display contact list in Android Studio using RecyclerView

I am trying to display my contact list for my mobile application. I have already connected the database and I figured that there is no problem with the database since I can add new contact but I am unable to display the list. I use RecyclerView which I already created Adapter class, item layout and model for.
Adapter class - contAdapter.java
item layout - item.xml
Model - Contact
RecyclerView Layout - contactList.xml
contactList - to bind recyclerview with adapter
I wish to see the list of contact added to the database to be displayed on the screen but I have been stuck here for quite some time since I cannot figure out what the problem is :(
Here is my Contact Model:
public Contact() {
}
public Contact(String contName, String contNumber) {
this.contName = contName;
this.contNumber = contNumber;
}
public String getContName() {
return contName;
}
public void setContName(String contName) {
this.contName = contName;
}
public String getContNumber() {
return contNumber;
}
public void setContNumber(String contNumber) {
this.contNumber = contNumber;
}
contactList.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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" xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="25dp" tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/contList"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
contactList.java:
package com.example.lucentproj;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
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;
public class contactList extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference reference;
contAdapter adapter;
ArrayList<Contact> list;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
user = FirebaseAuth.getInstance().getCurrentUser();
recyclerView = findViewById(R.id.contList);
reference = FirebaseDatabase.getInstance().getReference("Contact");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
adapter = new contAdapter(this, list);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Contact contact = dataSnapshot.getValue(Contact.class);
list.add(contact);
}
adapter.updateList(list);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_margin="16dp"
app:cardElevation="8dp" app:cardCornerRadius="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:orientation="vertical"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
<TextView
android:id="#+id/contname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/amaranth"
android:text="Name"
android:layout_marginLeft="10dp"
android:layout_marginTop="8dp"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/contno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:fontFamily="#font/amaranth_italic"
android:paddingLeft="10dp"
android:text="Number"
android:textSize="20dp"
android:textStyle="italic" />
<ImageView
android:id="#+id/cCall"
android:layout_width="38dp"
android:layout_height="30dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="15dp"
android:clickable="true"
android:src="#drawable/call" />
<ImageView
android:id="#+id/cEdit"
android:layout_width="45dp"
android:layout_height="30dp"
android:layout_marginLeft="320dp"
android:layout_marginTop="15dp"
android:clickable="true"
android:src="#drawable/edit" />
</androidx.cardview.widget.CardView>
contAdapter:
package com.example.lucentproj;
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 contAdapter extends RecyclerView.Adapter<contAdapter.ViewHolder> {Context context;
ArrayList<Contact> list;
public contAdapter(Context context, ArrayList<Contact> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Contact cont = list.get(position);
holder.cname.setText(cont.getContName());
holder.cnum.setText(cont.getContNumber());
}
#Override
public int getItemCount() {
return list.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView cname, cnum;
public ViewHolder(#NonNull View itemView) {
super(itemView);
cname = itemView.findViewById(R.id.contName);
cnum = itemView.findViewById(R.id.contNumber);
}
}
public void updateList(ArrayList<Contact> list){
this.list=list;
notifyDataSetChanged();
}
}
You are not updating list in Adaptor
Please add this method in your adaptor class -
public void updateList(ArrayList<Contact> list){
this.list=list;
notifyDataSetChanged();
}
And replace this line from your contactList activity to adapter.notifyDataSetChanged(); --> adapter.updateList(list);
contactList.java
package com.example.lucentproj;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
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;
public class contactList extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference reference;
contAdapter adapter;
ArrayList<Contact> list;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
user = FirebaseAuth.getInstance().getCurrentUser();
recyclerView = findViewById(R.id.contList);
reference = FirebaseDatabase.getInstance().getReference("Contact");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Contact contact = dataSnapshot.getValue(Contact.class);
list.add(contact);
}
}
adapter = new contAdapter(this, list);
recyclerView.setAdapter(adapter);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Contact contact = dataSnapshot.getValue(Contact.class);
list.add(contact);
}
adapter.updateList(list);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}

Images not showing in List Firebase

When using a custom adapter in Firebase, I ran into a problem that everything works, but the pictures in the sheet are not displayed. Something incomprehensible is highlighted, but not her. It is necessary that they be in a normal sheet and they can be seen. I think it's because of the context in Picasso. The guide I followed had a wish(mContext) method that I can't use now. Please help, I don't understand what is the problem. I am attaching the image_item.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:text="Name"
android:textColor="#android:color/black"
android:textSize="20sp" />
<ImageView
android:id="#+id/image_view_upload"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
activity_images
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".ImagesActivity">
<ProgressBar
android:id="#+id/progress_circle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
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.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
}
}
}
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
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 ImagesActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private DatabaseReference mDatabaseRef;
private List<Upload> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mProgressCircle = findViewById(R.id.progress_circle);
mUploads = new ArrayList<>();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Upload upload = postSnapshot.getValue(Upload.class);
mUploads.add(upload);
}
mAdapter = new ImageAdapter(ImagesActivity.this, mUploads);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
}

NullPointerException on RecyclerView, there is no id mistake

I have checked several times the name of my layout RecyclerView as I show on other StackOverflow questions but it is correct. The error of the logcat is this:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.selfcial/com.example.selfcial.Models.MessageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.LinearLayoutManager.setStackFromEnd(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.LinearLayoutManager.setStackFromEnd(boolean)' on a null object reference
at com.example.selfcial.Models.MessageActivity.onCreate(MessageActivity.java:69)
at android.app.Activity.performCreate(Activity.java:7893)
at android.app.Activity.performCreate(Activity.java:7880)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283)
This is my my MessageActivity:
package com.example.selfcial.Models;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.selfcial.Adapters.MessageAdapter;
import com.example.selfcial.R;
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 java.util.List;
public class MessageActivity extends AppCompatActivity {
TextView username;
ImageView profile;
RecyclerView recyclerViewy;
EditText sendMsg;
ImageButton sendBtn;
FirebaseUser firebaseUser;
DatabaseReference reference;
Intent intent;
MessageAdapter messageAdapter;
List<Chat> chats;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
profile = findViewById(R.id.imageview_profile);
username = findViewById(R.id.usernameLogin);
sendMsg = findViewById(R.id.writeMsg);
sendBtn = findViewById(R.id.sendBtn);
//RecyclerViewChat
recyclerView.findViewById(R.id.recycler_view_chat);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
intent = getIntent();
String id = intent.getStringExtra("id");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users").child(id);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Convert edittext to string
String msg = sendMsg.getText().toString();
//Send message
if (!msg.equals("")) {
sendMessage(firebaseUser.getUid(), id, msg);
} else {
Toast.makeText(MessageActivity.this, "It's an empty message", Toast.LENGTH_SHORT).show();
}
sendMsg.setText("");
}
});
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Users user = snapshot.getValue(Users.class);
username.setText(user.getUsername());
if (user.getImageUrl().equals("default")) {
profile.setImageResource(R.drawable.avatar);
} else {
Glide.with(MessageActivity.this)
.load(user.getImageUrl())
.into(profile);
}
readMessages(firebaseUser.getUid(), id, user.getImageUrl());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void sendMessage(String sender, String receiver, String message) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
reference.child("chats").push().setValue(hashMap);
}
private void readMessages(String myid, String id, String imgUrl) {
chats = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chats.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
Chat chat = snapshot1.getValue(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(id) ||
chat.getReceiver().equals(id) && chat.getSender().equals(myid)) {
chats.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, chats, imgUrl);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is the MessageAdapter:
ackage com.example.selfcial.Adapters;
import android.content.Context;
import android.content.Intent;
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.selfcial.Models.Chat;
import com.example.selfcial.Models.MessageActivity;
import com.example.selfcial.Models.Users;
import com.example.selfcial.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private Context context;
private List<Chat> mChat;
private String imgUrl;
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
//Firebase
FirebaseUser firebaseUser;
//Constructor
public MessageAdapter(Context context, List<Chat> mChat, String imgUrl) {
this.context = context;
this.mChat = mChat;
this.imgUrl = imgUrl;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == MSG_TYPE_RIGHT) {
view = LayoutInflater.from(context).inflate(R.layout.item_sent,
parent,
false);
}else {
view = LayoutInflater.from(context).inflate(R.layout.item_received,
parent,
false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
if (imgUrl.equals("default")) {
holder.profile_image.setImageResource(R.drawable.avatar);
}else {
Glide.with(context)
.load(imgUrl)
.into(holder.profile_image);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView show_message;
private ImageView profile_image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.message);
profile_image = itemView.findViewById(R.id.profileImgReceive);
}
}
#Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(firebaseUser.getUid())) {
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
And this is the activity_message.xml:
<?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/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Models.MessageActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imageview_profile"
android:layout_width="40dp"
android:layout_height="40dp"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="28dp"
tools:srcCompat="#drawable/avatar" />
<TextView
android:id="#+id/usernameLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:textColor="#color/white"
android:layout_marginLeft="23dp" />
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_chat"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#F8E1E1"
app:layout_constraintBottom_toTopOf="#+id/cardView5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
<androidx.cardview.widget.CardView
android:id="#+id/cardView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="#+id/sendVoice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_weight="1"
android:background="#android:color/transparent"
android:contentDescription="TODO"
app:srcCompat="#drawable/ic_mic" />
<ImageButton
android:id="#+id/photoBtn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#00FFFFFF"
android:scrollbarThumbHorizontal="#color/black"
android:scrollbarThumbVertical="#color/black"
app:srcCompat="#drawable/ic_baseline_camera_alt_24" />
<ImageButton
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#android:color/transparent"
app:srcCompat="#drawable/ic_gallery" />
<EditText
android:id="#+id/writeMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginBottom="0dp"
android:layout_weight="1"
android:background="#drawable/msg_shape"
android:ems="10"
android:hint="Bb"
android:inputType="textCapSentences"
android:padding="5dp" />
<ImageButton
android:id="#+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#00FFFFFF"
android:scrollbarThumbHorizontal="#color/black"
android:scrollbarThumbVertical="#color/black"
app:srcCompat="#drawable/ic_send" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
Is the error occured by a mistake on the MessageAdapter or is it a bug somewhere else? I also tried to change LinearLayoutManager line to LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); but this didn't work too.
You call findViewById() here:
recyclerView.findViewById(R.id.recycler_view_chat);
But you are calling the findViewById() method on your recyclerView variable, not assigning the result of your Activity's findViewById() to your variable, so your variable is always null.
recyclerView = findViewById(R.id.recycler_view_chat);

Making buttons in recyclerview and cardview clickable

I've added buttons into a a cardview and recyclerview. I'm struggling to make the buttons clickable. Every time I click the buttons it's actually registering the recyclerview as being clicked.
Activity containing cardview and recyclerview
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
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.Query;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.adapter.RecyclerAdapter;
import com.khumomashapa.notes.arraylists.Messages;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class StoreActivity extends AppCompatActivity {
// Widget
RecyclerView recyclerView;
//Firebase
private DatabaseReference mref;
// Variable
private ArrayList<Messages> messagesList;
private RecyclerAdapter recyclerAdapter;
private Context mContext;
Button PurchaseBtn;
Button DownloadBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store);
recyclerView = findViewById(R.id.products_view);
PurchaseBtn = (Button) findViewById(R.id.PurchaseBtn);
DownloadBtn = (Button) findViewById(R.id.DownloadBtn);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext()
,recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ImageView imageView = view.findViewById(R.id.ImageView);
Drawable mDrawable = imageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
Intent intent = new Intent(view.getContext(),PreviewActivity.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]bytes = stream.toByteArray();
intent.putExtra("image", bytes);
startActivity(intent);
Messages messages = messagesList.get(position);
Toast.makeText(StoreActivity.this, "You have selected: "+ messages.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
#Override
public void onButtonClicks(View view, int position) {
}
})
);
// Firebase
mref = FirebaseDatabase.getInstance().getReference();
// Arraylist
messagesList = new ArrayList<Messages>();
// Clear arraylist
ClearAll();
// Get data Method
GetDataFromFirebase();
}
private void GetDataFromFirebase(){
Query query = mref.child("Wallpapers");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Messages messages = new Messages();
messages.setImage(snapshot.child("image").getValue().toString());
messages.setTitle(snapshot.child("title").getValue().toString());
messagesList.add(messages);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), messagesList);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(messagesList != null){
messagesList.clear();
if (recyclerAdapter !=null){
recyclerAdapter.notifyDataSetChanged();
}
}
messagesList = new ArrayList<Messages>();
}
}
Recycler Adapter
package com.khumomashapa.notes.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.activities.StoreActivity;
import com.khumomashapa.notes.arraylists.Messages;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<Messages> messagesList;
Button PurchaseBtn;
Button DownloadBtn;
View imageView;
public RecyclerAdapter(Context mContext, ArrayList<Messages> messagesArrayList) {
this.mContext = mContext;
this.messagesList = messagesArrayList;
View imageView;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Textview
holder.textView.setText(messagesList.get(position).getTitle());
holder.PurchaseBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Imageview: Glide library
Glide.with(mContext)
.load(messagesList.get(position).getImage())
.into(holder.imageView);
}
#Override
public int getItemCount() {
return messagesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
// Widgets;
ImageView imageView;
TextView textView;
Button PurchaseBtn;
Button DownloadBtn;
View v;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.ImageView);
textView = itemView.findViewById(R.id.Title);
PurchaseBtn = itemView.findViewById(R.id.PurchaseBtn);
DownloadBtn = itemView.findViewById(R.id.DownloadBtn);
View v;
}
}
}
Recycler Touch Listener
package com.khumomashapa.notes.activities
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
class RecyclerTouchListener(
context: Context?,
recyclerView: RecyclerView,
private val clickListener: ClickListener?
) :
OnItemTouchListener {
private val gestureDetector: GestureDetector
override fun onInterceptTouchEvent(recyclerView: RecyclerView, e: MotionEvent): Boolean {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recyclerView.getChildAdapterPosition(child))
}
return false
}
override fun onTouchEvent(recyclerView: RecyclerView, e: MotionEvent) {}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
interface ClickListener {
fun onClick(view: View?, position: Int)
fun onLongClick(view: View?, position: Int)
fun onButtonClicks(view: View?, position: Int)
}
init {
gestureDetector = GestureDetector(context, object : SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
return true
}
override fun onLongPress(e: MotionEvent) {
val child = recyclerView.findChildViewUnder(e.x, e.y)
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child))
}
}
})
}
}
Cardview layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:contentPadding="5dp"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true"
app:cardElevation="3dp"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Imagelayout">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
android:padding="2dp"
android:id="#+id/ImageView"
android:contentDescription="#string/image" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Imagelayout">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title"
android:textColor="#color/textColor"
android:textSize="20sp"
android:fontFamily="#font/biorhyme_extralight"
android:id="#+id/Title"/>
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/PurchaseBtn"
android:layout_width="350dp"
android:clickable="true"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:onClick="purchase"
android:text="#string/purchase"
android:layout_below="#+id/Title"
android:background="#drawable/btn_rounded"
android:textColor="#color/textColor"
android:textSize="12sp"
app:cornerRadius="20dp"
android:focusable="true" />
<androidx.appcompat.widget.AppCompatButton
android:id="#+id/DownloadBtn"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_below="#+id/PurchaseBtn"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_marginTop="6dp"
android:background="#drawable/btn_rounded"
android:text="#string/download"
android:textColor="#color/textColor"
android:textSize="12sp"
android:visibility="invisible"
app:cornerRadius="20dp" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Recyclerview layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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"
tools:context=".activities.StoreActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/products_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout >
Another issue I know I'll encounter is the null reference exception.
How do I reference the buttons from the cardview layout when the content view is set to be shown from the other one.

RecyclerView childView always with the same id

MY PROBLEM
All views inside my RecyclerView, I am talking about elements(TextView and ImageView ....) are displayed well, normal but when i want to list all items inside the recyclerView with this:
for(int i=0;i<recyclerView.getChildCount();i++){
ids=ids+"-"+recyclerView.getChildAt(i).getId();
}
when i display ids always show me the same id which is the RelativeLayout id and it supose to display the id of the elements inside the RecyclerView as the TextView, ImageView and more
MY RESEARCH
i was following a video from slidenerd of
RecyclerView.OnItemTouchListener
and for him is working fine i dont know why for my is not working i was reading a lot about my problem to find the exact problem because:
First thing i did change the ids names for all my layouts to be different
Move the position of my code
Confirm that the data sent by MotionEvent e.getX() and y.getY() was correct and even thought i change the methods for getRaw
Read about RecyclerView class and find that there is not issue in this method findChildVIewUnder because all things that do are mathematicals
Read the id number of each important resource in R file an then convert it to dec to compare the prompt
I am close to the frustation
MY CODE
teacher_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/problem"
android:layout_width="328dp"
android:layout_height="130dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:clickable="true"
android:background="#drawable/borders">
<ImageView
android:layout_width="90dp"
android:layout_height="100dp"
android:id="#+id/teacher_item_picture"
style="#style/TeacherItemImage" />
<RatingBar
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/teacher_item_ratingbar"
style="#style/TeacherItemRatingBar" />
<TextView
android:id="#+id/teacher_item_name"
android:layout_width="180dp"
android:layout_height="16.5dp"
style="#style/TeacherItemName" />
<TextView
android:id="#+id/teacher_item_courses"
android:layout_width="180dp"
android:layout_height="33dp"
style="#style/TeacherItemCourses" />
<TextView
android:id="#+id/teacher_item_faculties"
android:layout_width="180dp"
android:layout_height="33dp"
style="#style/TeacherItemFaculties" />
</RelativeLayout>
recyclerview.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:id="#+id/generic_listView"
android:layout_height="wrap_content"
style="#style/GenericListItem">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
teacherListFragment.javaimportant code
teacherListAdapter=new TeacherListAdapter(getActivity(),getData());
teacherListAdapter.setListener(this);
recyclerView.addItemDecoration(new RecyclerViewDivider(getActivity()));
recyclerView.setAdapter(teacherListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerViewClickListener(getActivity(), recyclerView, new RecyclerViewClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Log.d("D", view.getId() + "-" + position);
}
}));
getData() returns an List, this code is inside onCreateView
TeacherListAdatper
package wan.wanmarcos.views.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import wan.wanmarcos.R;
import wan.wanmarcos.managers.ItemAdapterListener;
import wan.wanmarcos.managers.ViewHolderSetters;
import wan.wanmarcos.models.Teacher;
import wan.wanmarcos.utils.Constants;
import wan.wanmarcos.views.widgets.CircleTransform;
public class TeacherListAdapter extends RecyclerView.Adapter<TeacherListAdapter.TeacherHolder> {
private LayoutInflater inflater;
private List<Teacher> teachers= Collections.emptyList();
private ItemAdapterListener itemAdapterListener;
public TeacherListAdapter(Context context,List<Teacher> teachers){
inflater= LayoutInflater.from(context);
this.teachers=teachers;
}
#Override
public TeacherHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(Constants.TEACHER_NEW_ITEM, parent, false);
TeacherHolder teacherCustomer = new TeacherHolder(view);
return teacherCustomer;
}
#Override
public void onBindViewHolder(TeacherHolder holder, int position) {
Teacher teacher=teachers.get(position);
holder.setElements(teacher);
}
public void setListener(ItemAdapterListener listener){
this.itemAdapterListener =listener;
}
#Override
public int getItemCount() {
return teachers.size();
}
public class TeacherHolder extends RecyclerView.ViewHolder implements ViewHolderSetters<Teacher>,View.OnClickListener{
private TextView teacherName;
private RatingBar teacherRating;
private ImageView teacherImage;
private TextView teacherCourses;
private TextView teacherAssumptions;
private Teacher current;
public TeacherHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
teacherName= (TextView) itemView.findViewById(R.id.teacher_item_name);
teacherRating=(RatingBar)itemView.findViewById(R.id.teacher_item_ratingbar);
teacherImage=(ImageView)itemView.findViewById(R.id.teacher_item_picture);
teacherCourses=(TextView)itemView.findViewById(R.id.teacher_item_courses);
teacherAssumptions=(TextView)itemView.findViewById(R.id.teacher_item_faculties);
}
#Override
public void setElements(Teacher elements) {
current=elements;
teacherName.setText(elements.getName());
teacherRating.setRating(elements.getRaiting());
teacherCourses.setText(itemView.getResources().getString(R.string.teacher_capabilities)+ elements.getFaculties());
teacherAssumptions.setText(itemView.getResources().getString(R.string.teacher_ped) + elements.getDescription());
Picasso.with(itemView.getContext()).load(elements.getImageUrl()).transform(new CircleTransform()).into(teacherImage);
}
#Override
public void onClick(View v) {
//itemAdapterListener.itemClicked(v,current);
}
}
}
WHAT I WANT IS: why child items of my RecyclerVIew are the layouts containers?
I need someone to help me Thanks

Categories

Resources