I have made Notificatiion Activity that getting the data from Cloud Firestore. After I test the app. I got always null from database, I checked in the debug. I found the data is read from database, but not setting it in Notification.java. Here is my code:
NotificationActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notifications);
getSupportActionBar().setTitle(R.string.menu_notifications);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
initRecyclerView();
getNotifications();
Adview();
}
private void initRecyclerView() {
Log.d(TAG, "initRecyclerView: init recyclerview.");
mRecyclerView = findViewById(R.id.recyclerv_view);
if (mNotificationsAdapter == null) {
mNotificationsAdapter = new NotificationsAdapter(this, mNotifications);
}
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mNotificationsAdapter);
}
private void getNotifications() {
SharedPreferences prefs = getSharedPreferences("TOKEN_PREF", MODE_PRIVATE);
String token = prefs.getString("token", "");
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference notificationsCollectionRef = db.collection("notifications").document(token).collection("messages");
Query query = notificationsCollectionRef
.orderBy("Date", Query.Direction.DESCENDING);
query.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Notifications notifications = document.toObject(Notifications.class);
mNotifications.add(notifications);
}
mNotificationsAdapter.notifyDataSetChanged();
} else {
Log.d(TAG,"Query Failed. Check Logs.");
}
});
}
NotificationsAdapter.java:
class NotificationsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = "NotificationsAdapter";
private ArrayList<Notifications> mNotifications;
private Context mContext;
public NotificationsAdapter(Context context, ArrayList<Notifications> notifications) {
mNotifications = notifications;
mContext = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder;
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.notifications_listitem, parent, false);
holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
if (holder instanceof ViewHolder) {
((ViewHolder) holder).title.setText(mNotifications.get(position).getTitle());
((ViewHolder) holder).message.setText(mNotifications.get(position).getMessage());
((ViewHolder) holder).date_time.setText(mNotifications.get(position).getDate() + "\n" + mNotifications.get(position).getTime());
((ViewHolder) holder).parentLayout.setOnClickListener(view -> {
Log.d(TAG, "onClick: clicked on: " + mNotifications.get(position).getTitle());
Intent intent = new Intent(mContext, NotificationDetails.class);
// intent.putExtra("image_url", mImages.get(position));
intent.putExtra("shop_name", mNotifications.get(position).getTitle());
intent.putExtra("message", mNotifications.get(position).getMessage());
mContext.startActivity(intent);
});
}
}
#Override
public int getItemCount() {
return mNotifications.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView title, message, date_time;
RelativeLayout parentLayout;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.shop_image);
title = itemView.findViewById(R.id.title);
message = itemView.findViewById(R.id.message);
date_time = itemView.findViewById(R.id.date_time);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
Notifications.java
#IgnoreExtraProperties
public class Notifications {
private String title;
private String message;
private String date;
private String time;
public Notifications() {
}
public Notifications(String title, String message, String date, String time) {
this.title = title;
this.message = message;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
Make sure your Firestore / firebase attributes and you java/Kotlin data class attributes are the same. I mean caps letters and everything.
Call the getNotification() method first.
I solved the issue by changing the variables in the model class to be starting with capital letter.
Related
I have a RecyclerView with an ImageView being a part of the items. I want to hide the ImageView from an item in the RecyclerView if a certain condition is met. How can I do that? I am attaching the image of how I want it to look like.
I am just defining the ImageViews in my xml layout file, so I cannot figure out how to actually remove it based on a certain condition in my android activity. I am attaching the code for the adapter class and my activity as well.
Here is the code for my adapter class
Adapter Class
public class ReportAdapter extends RecyclerView.Adapter<ReportAdapter.ReportViewHolder> {
private ArrayList<ReportItem> reportlist;
private OnItemClickListener mListener;
private Context mContext;
public ReportAdapter(ArrayList<ReportItem> reportlist, Context context) {
this.reportlist = reportlist;
this.mContext = context;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class ReportViewHolder extends RecyclerView.ViewHolder {
public TextView departureDate;
public TextView flightNumber;
public View relativelayout;
public ReportViewHolder(#NonNull View itemView, OnItemClickListener listener, Context context) {
super(itemView);
departureDate = itemView.findViewById(R.id.departureDaterecyclerview);
flightNumber = itemView.findViewById(R.id.flightnumberrecyclerview);
relativelayout = itemView.findViewById(R.id.relativeLayoutReports);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
}
}
#NonNull
#Override
public ReportViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.report_listing_item, parent, false);
ReportViewHolder rvh= new ReportViewHolder(v,mListener,mContext);
return rvh;
}
#SuppressLint("ResourceAsColor")
#Override
public void onBindViewHolder(#NonNull ReportViewHolder holder, int position) {
ReportItem currentItem = reportlist.get(position);
if(position%2==0){
holder.relativelayout.setBackgroundColor(mContext.getResources().getColor(R.color.reportlistingteal));
} else {
holder.relativelayout.setBackgroundColor(mContext.getResources().getColor(R.color.reportlistinglightteal));
}
holder.departureDate.setText((currentItem.getDepartureDate()));
holder.flightNumber.setText(currentItem.getFlightNumber());
}
Here is the code for my activity file
Activity file
public class ReportListingActivity extends AppCompatActivity {
private Button uploadAllBtn;
private EditText searchFlights;
private RecyclerView mRecyclerView;
private ReportAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
ArrayList<ReportItem> reportitems = new ArrayList<>();
private FlightViewModel flightViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_listing);
uploadAllBtn = findViewById(R.id.uploadAllReports);
searchFlights = findViewById(R.id.searchFlightText);
mRecyclerView = findViewById(R.id.recyclerView);
flightViewModel = new ViewModelProvider(this).get(FlightViewModel.class);
flightViewModel.getAllFlights().observe(this, new Observer<List<Flight>>() {
#Override
public void onChanged(List<Flight> flight_list) {
if (flight_list.size() == 0) return;
String flightno = flight_list.get(0).getFlightNumber();
String flightdate = flight_list.get(0).getDate();
String[] flight_details = new String[2];
flight_details[0]= flightno;
flight_details[1] = flightdate;
Log.v("pp", flight_details[0]);
for(int i = 0; i <flight_list.size();i++){
String flightnumber = flight_list.get(i).getFlightNumber();
String departuredate = flight_list.get(i).getDate();
reportitems.add(new ReportItem(flightnumber,departuredate));
}
mRecyclerView.getAdapter().notifyDataSetChanged();
flightViewModel.getAllFlights().removeObservers(ReportListingActivity.this);
}
});
mLayoutManager = new LinearLayoutManager(ReportListingActivity.this);
mAdapter = new ReportAdapter(reportitems, ReportListingActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
Report Item
public class ReportItem {
private String departureDate;
private String flightNumber;
public ReportItem(String departureDate, String flightNumber) {
this.departureDate = departureDate;
this.flightNumber = flightNumber;
}
public String getDepartureDate() {
return departureDate;
}
public String getFlightNumber() {
return flightNumber;
}
}
Add a boolean flag to your ReportItem class for each RecyclerView item. You will need to specify which rows show or hide this field when each item is created:
public class ReportItem {
private String departureDate;
private String flightNumber;
private Boolean showMailIcon;
public ReportItem(String departureDate, String flightNumber, Boolean showMailIcon) {
this.departureDate = departureDate;
this.flightNumber = flightNumber;
this.showMailIcon = showMailIcon
}
public String getDepartureDate() {
return departureDate;
}
public String getFlightNumber() {
return flightNumber;
}
public String getShowMailIcon() {
return showMailIcon;
}
}
Then update the onBindViewHolder() method override to use this flag to show/hide the ImageView:
#Override
public void onBindViewHolder(#NonNull ReportViewHolder holder, int position) {
ReportItem currentItem = reportlist.get(position);
if (currentItem.getShowMailIcon() == true) {
holder.mailIcon.setVisibility(View.VISIBLE);
} else {
holder.mailIcon.setVisibility(View.GONE);
}
//.......
}
After adding my data to the firebase real-time database, it got updated successfully. Then I wanted to get all the data I added to show in my main activity. After writing the code which I've appended below, I was not seeing any syntax error but if I ran the app I don't seem to get my data to view on my main activity and I can't seem to figure out the error. If anyone could help me, I will be grateful. Thank you all.
This is my model.
package com.example.myapplication.Activities;
public class Posts {
public String date, description,fullName,postImage,profileImage,time,uid;
public Posts(){
}
public Posts(String date, String description, String fullName, String postImage, String profileImage, String time, String uid) {
this.date = date;
this.description = description;
this.fullName = fullName;
this.postImage = postImage;
this.profileImage = profileImage;
this.time = time;
this.uid = uid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPostImage() {
return postImage;
}
public void setPostImage(String postImage) {
this.postImage = postImage;
}
public String getProfileImage() {
return profileImage;
}
public void setProfileImage(String profileImage) {
this.profileImage = profileImage;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
This is my query
private DatabaseReference databaseReference, postRef;
databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
postRef = FirebaseDatabase.getInstance().getReference().child("posts");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.Maintoolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
displayAllUserPosts();
}
Using the FirebaseRecyclerAdapter
private void displayAllUserPosts() {
FirebaseRecyclerOptions<Posts> options =
new FirebaseRecyclerOptions.Builder<Posts>()
.setQuery(postRef, Posts.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Posts, PostViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull PostViewHolder postViewHolder, int i, #NonNull Posts posts) {
postViewHolder.setDate(posts.getDate());
postViewHolder.setDescription(posts.getDescription());
postViewHolder.setFullName(posts.getFullName());
postViewHolder.setTime(posts.getTime());
postViewHolder.setPostImage(getApplicationContext(),posts.getPostImage());
postViewHolder.setProfileImage(getApplicationContext(), posts.getProfileImage());
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.all_post_layout, parent, false);
return new PostViewHolder(view);
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
View view;
public PostViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
}
public void setFullName(String fullName){
TextView username = (TextView) view.findViewById(R.id.post_user_name);
username.setText(fullName);
}
public void setProfileImage(Context context, String profileImage){
CircleImageView profileimage = (CircleImageView) view.findViewById(R.id.post_profile_image);
Picasso.with(context).load(profileImage).into(profileimage);
}
public void setDate( String date) {
TextView Date = (TextView)view.findViewById(R.id.post_date);
Date.setText(" " + date);
}
public void setTime(String time) {
TextView Time = (TextView)view.findViewById(R.id.post_time);
Time.setText(" " + time);
}
public void setDescription(String description) {
TextView Description = (TextView)view.findViewById(R.id.post_description);
Description.setText(description);
}
public void setPostImage( Context context, String postImage){
ImageView postimage = (ImageView)view.findViewById(R.id.post_image);
Picasso.with(context).load(postImage).into(postimage);
}
}
This is my database tree
posts
gjZxz9HL4IblUAcdWz788Z9AdXu118
May
202023:44
date:
"18/May/2020"
description:
"my first"
fullName:
"emeka"
postImage:
"https://firebasestorage.googleapis.com/v0/b/soc..."
profileImage:
"https://firebasestorage.googleapis.com/v0/b/soc..."
time:
"23:44"
uid:
"gjZxz9HL4IblUAcdWz788Z9AdXu1"
gjZxz9HL4IblUAcdWz788Z9AdXu120
May
2020:00:55
date:
"20/May/2020"
description:
"I like this"
fullName:
"emeka"
postImage:
"https://firebasestorage.googleapis.com/v0/b/soc..."
profileImage:
"https://firebasestorage.googleapis.com/v0/b/soc..."
time:
":00:55"
uid:
"gjZxz9HL4IblUAcdWz788Z9AdXu1"
Please, if anyone can, help me. I will be grateful. Thank you.
this is what I get when I run the app, the image below
enter image description here
I found the answer I was using addOnCompleteListener to get the Download URL for my post image instead of addOnSuccesslistener
I need a searchview in my recycler view. The recycler view should be invisible and once we search, the results should be visible.But I m unable to do it please help me. I m working in Android 7 and using firebase as a server. I LL paste the activity. (ChatsFragment and Contacts). I already searched for this question. But they are using adapter as a separate class. But in my code adapter is in the same activity. I m new to Android. So I don't know. I m building a chat application using codes available in the internet. Thanks in advance.
public class ChatsFragment extends Fragment
{
private View PrivateChatsView;
private RecyclerView chatsList;
private DatabaseReference ChatsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID="";
public ChatsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
PrivateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
return PrivateChatsView;
}
#Override
public void onStart()
{
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ChatsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, int position, #NonNull Contacts model)
{
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.hasChild("image"))
{
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
final String retStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state"))
{
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if (state.equals("online"))
{
holder.userStatus.setText("online");
}
else if (state.equals("offline"))
{
holder.userStatus.setText("Last Seen: " + date + " " + time);
}
}
else
{
holder.userStatus.setText("offline");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
CircleImageView profileImage;
TextView userStatus, userName;
public ChatsViewHolder(#NonNull View itemView)
{
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userStatus = itemView.findViewById(R.id.user_status);
userName = itemView.findViewById(R.id.user_profile_name);
}
}
}```
This is Contacts.java
```public class Contacts {
public String name, status, image;
public Contacts()
{
}
public Contacts(String name, String status, String image) {
this.name = name;
this.status = status;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}```
![enter image description here](https://i.stack.imgur.com/XhKSc.jpg)![enter image description here](https://i.stack.imgur.com/DqgUi.jpg)![enter image description here](https://i.stack.imgur.com/nUaNK.jpg)![enter image description here](https://i.stack.imgur.com/o1nnQ.jpg)![enter image description here](https://i.stack.imgur.com/5Qfed.jpg)
you can use editText with on text change listener
`
etSearchWord.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
//here you can hide the recycleView
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if (s.toString().isNotEmpty()) {
rvAutoCompResult.visible()
autoCompleteItems(s.toString())
} else
rvAutoCompResult.gone()
}
})
`
And in you adapter, you can use Filterable to filter your data
I developed a vocabulary app that has a Recycler View in main activity and shows two column of database: unit number and Unit name.When I click on each item it goes to another activity called inner page that has 6 text views and it must show other items of that row like word definition unit number spell meaning and part of speech. But unfortunately text views are empty and it shows only one value which is unit number.Please take a look at my codes and tell me what I missed.
Here's my codes:
Main page:
public class TabWord extends Fragment {
private RecyclerView recyclerView;
private ArrayList<WordItem> items = new ArrayList<>();
private WordTab adapter;
private DatabaseHelper databaseHelper;
private Cursor cursor ;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.tab_word, container, false);
recyclerView = viewGroup.findViewById(R.id.recyclerview_word);
adapter = new WordTab(items, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
loadDatabase();
return viewGroup;
}
public void loadDatabase() {
databaseHelper = new DatabaseHelper(getActivity());
try {
databaseHelper.checkAndCopyDatabase();
databaseHelper.openDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
try {
cursor = databaseHelper.QueryData("select * from ielts");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
WordItem item = new WordItem();
item.setUnitName(cursor.getString(2));
item.setUnitNumber(cursor.getString(1));
items.add(item);
} while (cursor.moveToNext());
}
}
} catch (SQLException e) {
e.printStackTrace();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
adapter = new WordTab(items, getActivity());
adapter.setOnTapListener(new OnTapListener() {
#Override
public void OnTapView(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
}
Adapter:
public class WordTab extends RecyclerView.Adapter<WordTab.ViewHolder> {
public static List<WordItem> wordItems;
private Context context;
private OnTapListener onTapListener;
public WordTab(List<WordItem> wordItems, Context context) {
this.wordItems = wordItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample_word, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
WordItem wordItem = wordItems.get(position);
holder.unitNumber.setText(wordItem.getUnitNumber());
holder.unitName.setText(wordItem.getUnitName());
holder.cardView.setId(position);
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onTapListener != null) {
onTapListener.OnTapView(position);
int position = v.getId();
Intent intent = new Intent(context, InnerPage.class);
intent.putExtra("name", "words");
intent.putExtra("id", position + "");
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return wordItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView unitName, unitNumber;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
unitName = itemView.findViewById(R.id.unit_name);
unitNumber = itemView.findViewById(R.id.unit_number);
cardView= itemView.findViewById(R.id.card_view_word);
}
}
public void setOnTapListener(OnTapListener onTapListener) {
this.onTapListener = onTapListener;
}
}
Model:
public class WordItem {
private int id;
private String unitNumber;
private String unitName;
private String word;
private String phonetic,pos,persian,definition;
public WordItem() {
this.unitName = unitName;
this.unitNumber = unitNumber;
this.word = word;
this.phonetic = phonetic;
this.pos = pos;
this.persian = persian;
this.definition = definition;
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getPersian() {
return persian;
}
public void setPersian(String persian) {
this.persian = persian;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUnitNumber() {
return unitNumber;
}
public void setUnitNumber(String unitNumber) {
this.unitNumber = unitNumber;
}
public String getUnitName() {
return unitName;
}
public void setUnitName(String unitName) {
this.unitName = unitName;
}
}
Inner Page:
public class InnerPage extends AppCompatActivity {
private int id;
private String unitNumber,word,phonetic,pos,persian,definition;
private TextView unitTxt,wordTxt,phoneticTxt,posTxt,persianTxt,definitionTxt;
private int layoutId;
private String pageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inner_page);
Bundle extras = getIntent().getExtras();
if (extras != null) {
layoutId = Integer.parseInt(extras.getString("id"));
pageName = extras.getString("name");
if (pageName.equals("words")){
id = WordTab.wordItems.get(layoutId).getId();
unitNumber = WordTab.wordItems.get(layoutId).getUnitNumber();
word = WordTab.wordItems.get(layoutId).getWord();
phonetic = WordTab.wordItems.get(layoutId).getPhonetic();
pos = WordTab.wordItems.get(layoutId).getPos();
persian = WordTab.wordItems.get(layoutId).getPersian();
definition = WordTab.wordItems.get(layoutId).getDefinition();
}
}
unitTxt = findViewById(R.id.unit);
wordTxt = findViewById(R.id.word);
phoneticTxt = findViewById(R.id.phonetic);
posTxt = findViewById(R.id.txtSpell);
persianTxt = findViewById(R.id.farMean);
definitionTxt = findViewById(R.id.definition);
unitTxt.setText(unitNumber);
wordTxt.setText(word);
phoneticTxt.setText(phonetic);
posTxt.setText(pos);
persianTxt.setText(persian);
definitionTxt.setText(definition);
}
}
An Android newbie here. I am building a chat app. The sent and received messages are not shown in the UI. I am able to send to server, but not getting displayed. Please help.
I put breakpoints in the code where it should bind data to the Views and inflate the layout, but that code is not at all getting triggered.
Askquestion Activity
public class Askquestion extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "Chatapp";
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter ChatappChatAdapter;
private ArrayList<ChatappMsg> messages;
private ImageView img_send;
private EditText et_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_askquestion);
int messageID = 111;
recyclerView = (RecyclerView) findViewById(R.id.recycler_chat);
ChatappChatAdapter = new ChatappChatAdapter(messageID, this,messages);
recyclerView.setAdapter(ChatappChatAdapter);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
messages = new ArrayList<>();
//fetchMessages();
img_send = (ImageView) findViewById(R.id.img_send);
et_message = (EditText) findViewById(R.id.et_message);
//ChatappChatAdapter = new ChatappChatAdapter(messageID, this,messages);
img_send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == img_send)
sendMessage();
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
private void sendMessage(){
final String messageBody = et_message.getText().toString().trim();
if(messageBody.equalsIgnoreCase(""))
return;
String messageBy = "Someone";
String messageAt = "sometime";
String messageType = "type";
int messageID = Integer.parseInt("111");
//LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(ChatappChatAdapter);
ChatappChatAdapter.notifyDataSetChanged();
ScrollToBottom();
et_message.setText("");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIUrl.BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService apiService = retrofit.create(APIService.class);
final ChatappMsg ChatappMsg = new ChatappMsg(messageBody,messageAt,messageBy,messageType,messageID);
Call<ChatappMsg> call = apiService.TalktoChatapp(ChatappMsg);
Log.d(TAG, ""+ChatappMsg);
call.enqueue(new Callback<ChatappMsg>() {
#Override
public void onResponse(Call<ChatappMsg> call, Response<ChatappMsg> response) {
Toast.makeText(getApplicationContext(),"success", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ChatappMsg> call, Throwable t) {
Toast.makeText(getApplicationContext(),"Failure", Toast.LENGTH_SHORT).show();
}
});
}
//method to scroll the recyclerview to bottom
private void ScrollToBottom() {
ChatappChatAdapter.notifyDataSetChanged();
if (ChatappChatAdapter.getItemCount() > 1)
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, ChatappChatAdapter.getItemCount() - 1);
}
}
ChatappChatAdapter.java
public class ChatappChatAdapter extends RecyclerView.Adapter<ChatappChatAdapter.ViewHolder> {
private static final String TAG = "Adapter";
private String messageBy;
private int messageID;
private Context context;
private int SELF = 111;
private ArrayList<ChatappMsg> messages;
public ChatappChatAdapter(int messageID, Context context, ArrayList<ChatappMsg> messages) {
this.messageID = messageID;
// this.messageBy = messageBy;
this.context = context;
this.messages = messages;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
// if else loop to identify if the message is sent message or received message
//Creating view
// View itemView;
//if view type is self
if (viewType == SELF) {
Log.i(TAG,"ViewType Defined as Self" );
//Inflating the layout self
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_sent_message_text, parent, false);
} else {
Log.i(TAG,"ViewType Defined as Not Self" );
//else inflating the layout others
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_received_message_text, parent, false);
}
Log.i(TAG,"Retuened" );
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ChatappChatAdapter.ViewHolder holder, int position) {
ChatappMsg msg = messages.get(position);
((ViewHolder) holder).messageBody.setText(msg.getMessageBody());
((ViewHolder) holder).messageAt.setText(msg.getMessageAt());
((ViewHolder) holder).messageBy.setText(msg.getMessageBy());
}
public int getItemViewType(int position){
ChatappMsg msg = messages.get(position);
if(msg.getMessageID() == messageID ) {
return SELF;
}
return position;
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView messageBody;
public TextView messageAt;
public TextView messageBy;
public ViewHolder(View itemView)
{
super(itemView);
messageBody = (TextView) itemView.findViewById(R.id.messageBody);
messageAt = (TextView) itemView.findViewById(R.id.messageAt);
messageBy = (TextView) itemView.findViewById(R.id.messageBy);
}
}
}
Chatapp Model.
public class ChatappMsg {
private String messageBody;
private String messageAt;
private String messageBy;
private String messageType;
private int messageID;
public String getMessageBody() {
return messageBody;
}
public void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public String getMessageAt() {
return messageAt;
}
public void setMessageAt(String messageAt) {
this.messageAt = messageAt;
}
public String getMessageBy() {
return messageBy;
}
public void setMessageBy(String messageBy) {
this.messageBy = messageBy;
}
public String getMessageType() {
return messageType;
}
public void setMessageType(String messageType) {
this.messageType = messageType;
}
public int getMessageID() {
return messageID;
}
public void setMessageID(int messageID) {
this.messageID = messageID;
}
public ChatappMsg(String messageBody, String messageAt, String messageBy, String messageType, int messageID) {
this.messageBody = messageBody;
this.messageAt = messageAt;
this.messageBy = messageBy;
this.messageType = messageType;
this.messageID = messageID;
}
#Override
public String toString() {
return "ChatappMsg{" +
"messageBody='" + messageBody + '\'' +
", messageAt='" + messageAt + '\'' +
", messageBy='" + messageBy + '\'' +
", messageType='" + messageType + '\'' +
", messageID='" + messageID + '\'' +
'}';
}
}
Help me in understanding what am I missing here.
I believe it might be an issue with the viewType or the message ID. How to fix? What should be the solution?
Thank you.
You are returning 0 in getItemCount() method in adapter.
Can you change it to
#Override
public int getItemCount() {
return messages.size();
}
in your ChatappChatAdapter and try again