Not printing the position of recyclerView in logcat - android

I'm trying to print the position of RecyclerView in logcat when I click on the list of recyclerView, but it's not printing anything. Actually in this app, if I click on a position of the recyclerview, that should take me to new activity and grab all the details of that position on which I clicked.
Here is my ImageAdapter.java class
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UserDetails> mUploads;
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public ImageAdapter(Context context, List<UserDetails> uploads) {
mContext = context;
mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.user_display, viewGroup, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder imageViewHolder, int i) {
UserDetails currentItem = mUploads.get(i);
UserDetails userDetails = mUploads.get(i);
imageViewHolder.requestId.setText("Request Id : " + userDetails.getMobileNumber());
imageViewHolder.customerName.setText(userDetails.getName());
imageViewHolder.customerMobile.setText("Mobile : " + userDetails.getMobileNumber());
imageViewHolder.customerAddress.setText(userDetails.getAddress());
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
public TextView requestId, customerName, customerAddress, customerMobile, serviceType, date;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
requestId = itemView.findViewById(R.id.requestId);
customerName = itemView.findViewById(R.id.customerName);
customerAddress = itemView.findViewById(R.id.customerAddress);
customerMobile = itemView.findViewById(R.id.customerMobile);
serviceType = itemView.findViewById(R.id.serviceType);
date = itemView.findViewById(R.id.date);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
and here is the recyclerView class
public class requestList extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
RecyclerView recyclerView;
DatabaseReference databaseReference;
List<UserDetails> downloadDataArray;
ImageAdapter adapter;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_list);
progressBar = findViewById(R.id.progressBar);
Toolbar toolbar = findViewById(R.id.roServiceToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Requests");
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(requestList.this, customerRequests.class));
}
});
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
downloadDataArray = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("Service Request/RO Service");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
downloadDataArray.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
UserDetails userDetails = postSnapshot.getValue(UserDetails.class);
downloadDataArray.add(userDetails);
}
adapter = new ImageAdapter(requestList.this, downloadDataArray);
getSupportActionBar().setTitle("Requests" + "(" +adapter.getItemCount()+ ")");
recyclerView.setAdapter(adapter);
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Log.i("Position", String.valueOf(position));
}
}

itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
//print log message
}
}
}
});

Because you are not assigning the value of mListener. Add this line after initialize adapter object.
adapter.setOnItemClickListener(this)

Related

Recycler View not updating messages from Firebase Database: Android Studio

When sending messages to firebase recycler view reading them but recycler view not updating instantly....i have tried notifyDataSetChanged() but not working.................................................................................................................................................................
MessagingActivity.java
public class MessagingActivity extends AppCompatActivity {
RecyclerView recyclerView;
ImageView ivBack, ivSend;
EditText etTypeMessage;
TextView tvName;
String Receiverphone, image, name;
CircleImageView civProfile;
DatabaseReference reference;
MessagingAdapter adapter;
ArrayList<MessagingBinding> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
recyclerView = findViewById(R.id.rv_messagingActivity);
ivBack = findViewById(R.id.ivBack_messagingActivity);
etTypeMessage = findViewById(R.id.etTypeMessage_activityMessaging);
tvName = findViewById(R.id.tvName_activityMessaging);
civProfile = findViewById(R.id.civProfile_messagingActivity);
ivSend = findViewById(R.id.ivSend_activityMessaging);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
image = getIntent().getStringExtra("image");
name = getIntent().getStringExtra("name");
Receiverphone = getIntent().getStringExtra("phone");
tvName.setText(name);
Picasso.get().load(image).into(civProfile);
reference = FirebaseDatabase.getInstance().getReference().child("Users");
ivSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Messages messages = new Messages(etTypeMessage.getText().toString(), name, image, Singleton.obj.phone, Receiverphone);
reference.child("messages").push().setValue(messages);
etTypeMessage.setText("");
adapter.notifyDataSetChanged();
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MessagingActivity.this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
reference.child("messages").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Messages messages = dataSnapshot.getValue(Messages.class);
if (messages.getSenderphone().equals(Singleton.obj.phone) && messages.getReceiverPhone().equals(Receiverphone)) {
list.add(messages);
}
}
adapter = new MessagingAdapter(list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MessagingActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
MessagingAdapter.javastrong text
public class MessagingAdapter extends RecyclerView.Adapter {
private ArrayList<MessagingBinding> bindingList;
public MessagingAdapter(ArrayList<MessagingBinding> bindingList) {
this.bindingList = bindingList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case (MessagingBinding.TYPE_SENDER):
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_sendermessaging, parent, false);
return new SenderViewHolder(view);
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_receivermessaging, parent, false);
return new ReceiverViewHodler(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case (MessagingBinding.TYPE_SENDER):
((SenderViewHolder) holder).bindView(position);
break;
case (MessagingBinding.TYPE_RECEIVER):
((ReceiverViewHodler)holder).bindView(position);
break;
}
}
#Override
public int getItemCount() {
if (bindingList == null) {
return 0;
} else {
return bindingList.size();
}
}
#Override
public int getItemViewType(int position) {
return bindingList.get(position).getType();
}
class SenderViewHolder extends RecyclerView.ViewHolder {
TextView tvSender;
ImageView ivSender;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
tvSender = itemView.findViewById(R.id.tvSender_listItemsMessaging);
ivSender = itemView.findViewById(R.id.ivSender_listItemMessaging);
}
void bindView(int position) {
SenderMessaging sender = (SenderMessaging) bindingList.get(position);
tvSender.setText(sender.getTvSenderMsg());
ivSender.setImageResource(sender.getImg());
}
}
//-------------------------------ReceiverViewHolder----------------------------------
class ReceiverViewHodler extends RecyclerView.ViewHolder {
TextView tvReceiver;
public ReceiverViewHodler(#NonNull View itemView) {
super(itemView);
tvReceiver = itemView.findViewById(R.id.tvReceiver_listItemsMessaging);
}
void bindView(int position) {
Messages receiver = (Messages) bindingList.get(position);
tvReceiver.setText(receiver.getMessage());
}
}
}
From your code, your messages should be visible when firebase notify you with changes in your db.
Please, try next code:
MessagingActivity
public class MessagingActivity extends AppCompatActivity {
RecyclerView recyclerView;
ImageView ivBack, ivSend;
EditText etTypeMessage;
TextView tvName;
String Receiverphone, image, name;
CircleImageView civProfile;
DatabaseReference reference;
MessagingAdapter adapter;
ArrayList<MessagingBinding> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
recyclerView = findViewById(R.id.rv_messagingActivity);
ivBack = findViewById(R.id.ivBack_messagingActivity);
etTypeMessage = findViewById(R.id.etTypeMessage_activityMessaging);
tvName = findViewById(R.id.tvName_activityMessaging);
civProfile = findViewById(R.id.civProfile_messagingActivity);
ivSend = findViewById(R.id.ivSend_activityMessaging);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
image = getIntent().getStringExtra("image");
name = getIntent().getStringExtra("name");
Receiverphone = getIntent().getStringExtra("phone");
tvName.setText(name);
Picasso.get().load(image).into(civProfile);
reference = FirebaseDatabase.getInstance().getReference().child("Users");
ivSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Messages messages = new Messages(etTypeMessage.getText().toString(), name, image, Singleton.obj.phone, Receiverphone);
reference.child("messages").push().setValue(messages);
etTypeMessage.setText("");
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MessagingActivity.this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
list = new ArrayList<>();
reference.child("messages").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
Messages messages = dataSnapshot.getValue(Messages.class);
if (messages.getSenderphone().equals(Singleton.obj.phone) && messages.getReceiverPhone().equals(Receiverphone)) {
list.add(messages);
}
}
adapter = new MessagingAdapter(list);
recyclerView.setAdapter(adapter);
adapter.updateList(list);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MessagingActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
And the Adapter:
public class MessagingAdapter extends RecyclerView.Adapter {
private ArrayList<MessagingBinding> bindingList;
public MessagingAdapter(ArrayList<MessagingBinding> bindingList) {
this.bindingList = bindingList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case (MessagingBinding.TYPE_SENDER):
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_sendermessaging, parent, false);
return new SenderViewHolder(view);
default:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_receivermessaging, parent, false);
return new ReceiverViewHodler(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case (MessagingBinding.TYPE_SENDER):
((SenderViewHolder) holder).bindView(position);
break;
case (MessagingBinding.TYPE_RECEIVER):
((ReceiverViewHodler)holder).bindView(position);
break;
}
}
#Override
public int getItemCount() {
if (bindingList == null) {
return 0;
} else {
return bindingList.size();
}
}
public void updateList(ArrayList<MessagingBinding> messages){
this.bindingList = messages;
this.notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return bindingList.get(position).getType();
}
class SenderViewHolder extends RecyclerView.ViewHolder {
TextView tvSender;
ImageView ivSender;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
tvSender = itemView.findViewById(R.id.tvSender_listItemsMessaging);
ivSender = itemView.findViewById(R.id.ivSender_listItemMessaging);
}
void bindView(int position) {
SenderMessaging sender = (SenderMessaging) bindingList.get(position);
tvSender.setText(sender.getTvSenderMsg());
ivSender.setImageResource(sender.getImg());
}
}
//-------------------------------ReceiverViewHolder----------------------------------
class ReceiverViewHodler extends RecyclerView.ViewHolder {
TextView tvReceiver;
public ReceiverViewHodler(#NonNull View itemView) {
super(itemView);
tvReceiver = itemView.findViewById(R.id.tvReceiver_listItemsMessaging);
}
void bindView(int position) {
Messages receiver = (Messages) bindingList.get(position);
tvReceiver.setText(receiver.getMessage());
}
}
}

Why adnroidx recycler-view click not working when click it's item?

I'm trying to implement RecyclerView onclick listener, but it is not working. I've tried a lot, and try to implement other way too, but not working at all.
My Main Class:
public class MainMenuDashboard extends AppCompatActivity{
private RecyclerView recyclerMenu;
private RecyclerViewMenuAdapter menuAdapter;
private Call<CategoryModel> categoryModelCall;
private TokenManager tokenManagerMainMenu;
private ApiService serviceMainMenu;
List<CategoryModel.Subset> menuList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_dashboard);
tokenManagerMainMenu = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
serviceMainMenu = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManagerMainMenu);
recyclerMenu = findViewById(R.id.recyclerMenu);
menuList = new ArrayList<>();
GridLayoutManager layoutManager = new GridLayoutManager(MainMenuDashboard.this, 2, GridLayoutManager.VERTICAL, false);
recyclerMenu.setLayoutManager(layoutManager);
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
menuAdapter.notifyDataSetChanged();
mainMenuDashBoardToolbar = findViewById(R.id.mainMenuDashBoardToolbar);
setSupportActionBar(mainMenuDashBoardToolbar);
menuContent();
}
private void menuContent() {
categoryModelCall = serviceMainMenu.menuContent(incomingRoleId, true);
categoryModelCall.enqueue(new Callback<CategoryModel>() {
#Override
public void onResponse(#NotNull Call<CategoryModel> call, #NotNull Response<CategoryModel> response) {
if (response.isSuccessful() && response.body() != null && response.code() != 400) {
//findViewById(R.id.shimmerCategory).setVisibility(View.GONE);
CategoryModel categoryModel = response.body();
menuList = categoryModel.getSubset();
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
//menuAdapter.notifyDataSetChanged();
menuAdapter.setOnItemClickListener(new RecyclerViewMenuAdapter.ClickListenerMenu() {
#Override
public void onClick(int position) {
Toast.makeText(MainMenuDashboard.this, "Position "+position+" Clicked", Toast.LENGTH_SHORT).show();
menuAdapter.notifyDataSetChanged();
}
});
menuAdapter.notifyDataSetChanged();
}else {
if (response.code() == 401) {
Intent i = new Intent(MainMenuDashboard.this, MainActivity.class);
i.putExtra("USER_SESSION", true);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
tokenManagerMainMenu.deleteToken();
startActivity(i);
finish();
}
}
}
#Override
public void onFailure(#NotNull Call<CategoryModel> call, #NotNull Throwable t) {
}
});
}
}
My Adapter:
public class RecyclerViewMenuAdapter extends RecyclerView.Adapter<RecyclerViewMenuAdapter.RecyclerViewHolder> {
private static final String TAG = "NotesRecyclerAdapter";
private List<CategoryModel.Subset> subsetsCategories;
private ClickListenerMenu mClickListener;
private Context context;
public RecyclerViewMenuAdapter(List<CategoryModel.Subset> subsetsCategories) {
this.subsetsCategories = subsetsCategories;
}
#NonNull
#Override
public RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_main_menu_category, parent, false);
return new RecyclerViewHolder(view, mClickListener);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewHolder viewHolder, final int position) {
String menuCategoryImage = subsetsCategories.get(position).getIcon();
Picasso.get().load(menuCategoryImage).placeholder(R.drawable.admin).into(viewHolder.menuThumb);
String menuCategoryName = subsetsCategories.get(position).getName();
viewHolder.menuName.setText(menuCategoryName);
//Item click
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
mClickListener.onClick(position);
//Toast.makeText(context, "Position "+position+" Clicked", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return subsetsCategories.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder{
ImageView menuThumb;
TextView menuName;
private ClickListenerMenu mListener;
//ClickListenerMenu clickListenerMenu;
public RecyclerViewHolder(View view, ClickListenerMenu clickListenerMenu) {
super(view);
menuThumb = view.findViewById(R.id.menuThumb);
menuName = view.findViewById(R.id.menuName);
mListener = clickListenerMenu;
}
}
public void setOnItemClickListener(ClickListenerMenu clickListener) {
mClickListener = clickListener;
}
public interface ClickListenerMenu {
void onClick(int position);
}
}
I still can't find where I did wrong!! Any insight will be very appreciated
Thank You
Add item click listener in your adapter.
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder viewHolder, int position) {
String menuCategoryImage = subsetsCategories.get(position).getIcon();
Picasso.get().load(menuCategoryImage).placeholder(R.drawable.admin).into(viewHolder.menuThumb);
String menuCategoryName = subsetsCategories.get(position).getName();
viewHolder.menuName.setText(menuCategoryName);
//Item click
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Do something
}
});
}
Initialise your recycler view outside and put this line menuAdapter.notifyDataSetChanged(); where you add data in your list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu_dashboard);
tokenManagerMainMenu = TokenManager.getInstance(getSharedPreferences("prefs", MODE_PRIVATE));
serviceMainMenu = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManagerMainMenu);
recyclerMenu = findViewById(R.id.recyclerMenu);
menuList = new List<CategoryModel.Subset>();
GridLayoutManager layoutManager = new GridLayoutManager(MainMenuDashboard.this, 2, GridLayoutManager.VERTICAL, false);
recyclerMenu.setLayoutManager(layoutManager);
menuAdapter = new RecyclerViewMenuAdapter(menuList);
recyclerMenu.setAdapter(menuAdapter);
menuAdapter.notifyDataSetChanged();
menuContent();
}
I hope this can help you!
Add these line in the onBindViewHolder() method:
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//remove this lines
//mClickListener.onClick(position);
//notifyDataSetChanged();
//add this
context.startActivity(new Intent(context,SecondActivity.class))
}
});
and in your MainMenuDashboard class, initialize your Adapter like this:
menuAdapter = new RecyclerViewMenuAdapter(this,menuList);
also change your Adapter constructor like this:
public RecyclerViewMenuAdapter(Context context,List<CategoryModel.Subset> subsetsCategories) {
this.subsetsCategories = subsetsCategories;
this.context = context;
}
```

Unable to pass intent.Extra from UserAdapter to c_Message_Activity

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
public UserAdapter(Context mContext, List<User> mUsers){
this.mUsers = mUsers;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.student_item, parent, false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final User user = mUsers.get(position);
holder.std_name.setText(user.getName());
if(user.getImage() != null && user.getImage().equals("default")){
holder.std_profile_image.setImageResource(R.mipmap.ic_launcher);
}else{
Glide.with(mContext).load(user.getImage()).into(holder.std_profile_image);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, c_Message_Activity.class);
intent.putExtra("userid", user.getId());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView std_name;
public ImageView std_profile_image;
public ViewHolder(View itemview){
super(itemview);
std_name = itemview.findViewById(R.id.std_name);
std_profile_image = itemview.findViewById(R.id.std_profile_image);
}
}
}
Activity Code :
public class c_Message_Activity extends AppCompatActivity {
CircleImageView s_profile_image;
TextView s_profile_name;
FirebaseUser fuser;
DatabaseReference reference;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c_message_activity);
Toolbar toolbar = findViewById(R.id.c_chat_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
s_profile_image = findViewById(R.id.s_profile_image);
s_profile_name = findViewById(R.id.s_profile_name);
intent = getIntent();
String userid = intent.getStringExtra("userid");
fuser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("User").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
s_profile_name.setText(user.getName());
if(user.getImage() != null && user.getImage().equals("default")){
s_profile_image.setImageResource(R.mipmap.ic_launcher);
}else {
Glide.with(c_Message_Activity.this).load(user.getImage()).into(s_profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
I can't pass my intent.putExtra("userid",user.getId()); to FirebaseDatabase.getInstance().getReference("User").child(userid);
Some can help me to solve this problem?
java.lang.NullPointerException: Can't pass null for argument
'pathString' in child()

RecyclerView onClick not working on search items

I have implemented a search function on my application and it displays the results however the results can not be clicked. When not in search the onClick method works fine. Here is the code for my main class where the search takes place
MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerViewAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<Buildings> mUploads;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private FirebaseStorage mStorage;
private ValueEventListener mDBListener;
private EditText msearch;
ArrayList<Buildings> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mStorage = FirebaseStorage.getInstance();
mDatabaseRef =
FirebaseDatabase.getInstance().getReference("Buildings");
mAdapter = new RecyclerViewAdapter(MainActivity.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(MainActivity.this);
msearch = findViewById(R.id.search);
arrayList = new ArrayList<>();
msearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().isEmpty())
{
search(s.toString());
}
else{
search("");
}
}
});
//GET DATA FROM FIREBASE!!
mDBListener = mDatabaseRef.addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Buildings upload = postSnapshot.getValue(Buildings.class);
upload.setKey(postSnapshot.getKey());
mUploads.add(upload);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
} //end of on create
private void search(String s) {
Query query = mDatabaseRef.orderByChild("name")
.startAt(s).endAt(s + "\uf8ff");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onItemClick(int position) {
Buildings selectedItem = mUploads.get(position);
final String name = selectedItem.getName();
final String address = selectedItem.getAddress();
final String image_url = selectedItem.getImage_url();
final double longt = selectedItem.getLongitude();
final double lat = selectedItem.getLatitude();
final String uid = selectedItem.getUserID();
final String desc = selectedItem.getDescription();
final String categ = selectedItem.getCategorie();
Intent mainIntent = new Intent(MainActivity.this, ProfileActivity2.class);
mainIntent.putExtra("b_name", name);
mainIntent.putExtra("b_address", address);
mainIntent.putExtra("b_image_url", image_url);
mainIntent.putExtra("b_userId", uid);
mainIntent.putExtra("b_desc", desc);
mainIntent.putExtra("b_categ", categ);
Bundle b = new Bundle();
b.putDouble("longt", longt);
b.putDouble("lat", lat);
mainIntent.putExtras(b);
startActivity(mainIntent);
finish();
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ImageViewHolder> {
private Context mContext;
private List<Buildings> mUploads;
private OnItemClickListener mListener;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private boolean checkUid;
public RecyclerViewAdapter(Context context, List<Buildings> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.buildings_row_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Buildings uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
holder.textViewAddress.setText(uploadCurrent.getAddress());
Glide.with(mContext).load(mUploads.get(position).getImage_url()).into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public TextView textViewAddress;
LinearLayout view_container;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.building_name);
imageView = itemView.findViewById(R.id.thumbnail);
view_container = itemView.findViewById(R.id.container);
textViewAddress = itemView.findViewById(R.id.address);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if(checkUid =true && mCurrentUser != null){
MenuItem delete = menu.add(Menu.NONE, 1, 1, "Delete");
delete.setOnMenuItemClickListener(this);
}
else{
//do nothing
}
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
Should I be adding something to my search function?
You are creating new adapter on reponse of your query, which isn't having active interface attached. So instead of creating new adapter, just update the data list and notify adapter.
Refer below code.
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
// Remove below two lines,
// It is not needed as we only need to notify adapter about the data change.
// RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
// mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In search method, you create a new adapter but not setting its onItemClickListener.
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChildren()){
arrayList.clear();
for(DataSnapshot dss: dataSnapshot.getChildren()){
final Buildings buildings = dss.getValue(Buildings.class);
arrayList.add(buildings);
}
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(getApplicationContext(),arrayList);
mRecyclerView.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
}
Separate the setData and construct method for adapter, then you don't need to create new adapter every search. Or just set mAdapter.setOnItemClickListener for it.

How to handle RecyclerView positions in a correct way?

I am using a recyclerview and inside its adapter I have another recyclerview.
How to prevent item change and item refresh when an item is updated.
This is creating visual glitches and wrong positioning of the items
I have tried to read directly from a database reference on the current position of the holder.
Result: https://media.giphy.com/media/j6TpXZRE6e44cMZVIP/giphy.gif
public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder>{
private Context mContext;
private List<Comments> mComments;
private List<Replies> allReplies;
public CommentsAdapter(Context mContext, List<Comments> mComments, List<Replies> allReplies )
{
this.mContext = mContext;
this.mComments = mComments;
this.allReplies = allReplies;
}
#NonNull
#Override
public CommentsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.all_comments_layout, viewGroup, false);
return new CommentsAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position)
{
final Comments comments = mComments.get(position);
holder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommentUps.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
{
if (dataSnapshot.child(PostKey).child(com_uid).hasChild(currentUserID)) {
CommentUps.child(PostKey).child(com_uid).child(currentUserID).removeValue();
CommentsRef.child(PostKey).child(com_uid).child("likes").setValue(comments.getLikes() - 1);
} else {
CommentUps.child(PostKey).child(com_uid).child(currentUserID).setValue(true);
CommentsRef.child(PostKey).child(com_uid).child("likes").setValue(comments.getLikes() + 1);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Replies");
//reference.orderByChild("pLikes")
reference.orderByChild(com_uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
holder.repliesList.clear();
for (DataSnapshot snapshot : dataSnapshot.child(PostKey).child(com_uid).getChildren())
{
Replies replies = snapshot.getValue(Replies.class);
//final String com = comment.toString();
// Log.d(new String("Comments"), com);
//for (String id : followingList)
if (replies.getComment_uid().equals(com_uid))
{
holder.repliesList.add(replies);
}
}
holder.repliesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return mComments.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageButton like
List<Replies> repliesList;
RepliesAdapter repliesAdapter;
public ViewHolder(View itemView) {
super(itemView);
like = itemView.findViewById(R.id.comment_like_button);
repliesRecycler = itemView.findViewById(R.id.all_replies_recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
repliesRecycler.setLayoutManager(linearLayoutManager);
repliesRecycler.setHasFixedSize(true);
repliesList = new ArrayList<>();
repliesAdapter = new RepliesAdapter(mContext, repliesList);
repliesRecycler.setAdapter(repliesAdapter);
repliesAdapter.notifyDataSetChanged();
}
// Second Method - Same Result
private void displayReplies(final String com_uid ,final String PostKey, final boolean locked) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Replies");
reference.child(PostKey).child(com_uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
repliesList.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
final Replies replies = snapshot.getValue(Replies.class);
if (replies.getComment_uid().equals(com_uid)) {
repliesList.add(replies);
repliesAdapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
My replies adapter:
public class RepliesAdapter extends RecyclerView.Adapter<RepliesAdapter.ViewHolder>
{
public Context mContext;
public List<Replies> mReplies;
public RepliesAdapter(Context mContext, List<Replies> mReplies)
{
this.mContext = mContext;
this.mReplies = mReplies;
}
#NonNull
#Override
public RepliesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.all_replies_layout, viewGroup, false);
mAuth = FirebaseAuth.getInstance();
return new RepliesAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, final int position)
{
final Replies replies = mReplies.get(position);
holder.myUserName.setText(replies.getUsername());
holder.myComment.setText(replies.getReply());
holder.myTime.setText(replies.getTime());
}
#Override
public int getItemCount() {
return mReplies.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView myUserName, myComment,myTime;
public ViewHolder(View itemView) {
super(itemView);
myUserName = itemView.findViewById(R.id.reply_username);
myComment = itemView.findViewById(R.id.reply_text);
myTime = itemView.findViewById(R.id.reply_time);
}
}

Categories

Resources