Left is Mary and right is Bill , the speaker's textView will show on the right side , the situation is that Mary says 1 and 2 , it looks fine , just like the photo:
next step : the right side device is Bill who says a and b , it looks fine that is just what i want.
when they type words more and more , my issue is happen like this:
But when i leave the ChatGroup1 and enter it again , it looks fine
So my issue is that it has something wrong with realtime on display recyclerView
How can i fix this issue , i try to add listData.clear(); , it's not working
Any help would be appreciated , thanks in advance .
It's my chat channel layout:
<?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="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerChat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button2">
</android.support.v7.widget.RecyclerView>
<Button
android:id="#+id/button2"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#drawable/ic_send" />
<EditText
android:gravity="center"
android:hint="Type your message..."
android:background="#drawable/edit_corner"
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2" />
</RelativeLayout>
it's my chat class for Firebase and recyclerView:
//global variable
private RecyclerView recyclerChat;
private ArrayList<ChatItem> listData = new ArrayList<>();
private RecyclerChatItemAdapter adapter;
private DatabaseReference root;
About FirebaseDatabase:
root = FirebaseDatabase.getInstance().getReference().child(room_name);
//send message to FirebaseDatabase
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Map<String, Object> map = new HashMap<>();
temp_key = root.push().getKey();
root.updateChildren(map);
DatabaseReference message_root = root.child(temp_key);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", user_name);
map2.put("msg", editText2.getText().toString());
message_root.updateChildren(map2);
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken() , InputMethodManager.HIDE_NOT_ALWAYS);//just hide the keyboard when send message
editText2.setText("");
}
});
I think that may be my issue is just right here , about my recyclerView:
root.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ChatItem chatItem = dataSnapshot.getValue(ChatItem.class);//put the data to my javabean from Firebase
Log.d("Contacts: ", chatItem.toString());
listData.add(chatItem);
recyclerChat.scrollToPosition(adapter.getItemCount() - 1);//just let the latest data below
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//append_right_chat_conversation(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
LinearLayoutManager manager = new LinearLayoutManager(this);
// GridLayoutManager gridLayoutManager=new GridLayoutManager(this,2);
manager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerChat.setLayoutManager(manager);
adapter = new RecyclerChatItemAdapter(this, listData);
recyclerChat.setAdapter(adapter);
adapter.notifyDataSetChanged();//when i leave the chat group and enter again , it looks fine because this.
It's my recyclerView adapter:
public class RecyclerChatItemAdapter extends RecyclerView.Adapter<RecyclerChatItemAdapter.MyViewHolder>{
private Context context;
private List<ChatItem> mDatas;
public RecyclerChatItemAdapter(Context context, List<ChatItem> mDatas) {
this.context = context;
this.mDatas = mDatas;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=View.inflate(parent.getContext(),R.layout.for_chat_item_layout,null);
MyViewHolder myViewHolder=new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
String myName=mDatas.get(position).getName();
Contacts contacts=Contacts.getContacts();
String createName=contacts.getName();
if (myName.equals(createName)){
holder.textRight.setText(mDatas.get(position).getMsg()+"("+mDatas.get(position).getName()+")");
holder.textRight.setTextColor(Color.BLUE);
holder.textRight.setBackground(context.getResources().getDrawable(R.drawable.chat_green));
}else {
holder.textLeft.setText(mDatas.get(position).getMsg()+"("+mDatas.get(position).getName()+")");
holder.textLeft.setTextColor(Color.RED);
holder.textLeft.setBackground(context.getResources().getDrawable(R.drawable.chat_blue));
}
}
#Override
public int getItemCount() {
return mDatas.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView textLeft,textRight;
public MyViewHolder(View itemView) {
super(itemView);
textLeft=(TextView)itemView.findViewById(R.id.textLeft);
textRight=(TextView)itemView.findViewById(R.id.textRight);
}
}
}
You don't have shown Adapter layout and adapter code... It can be visibility problem of view.
You may be set visibility for view.. So for that please ensure that you have written something like this..
if (myName.equals(createName)){
holder.textRight.setVisibility(VISIBLE);
holder.textLeft.setVisibility(GONE);
holder.textRight.setText(mDatas.get(position).getMsg()+"("+mDatas.get(position).getName()+")");
holder.textRight.setTextColor(Color.BLUE);
holder.textRight.setBackground(context.getResources().getDrawable(R.drawable.chat_green));
}else {
holder.textRight.setVisibility(GONE);
holder.textLeft.setVisibility(VISIBLE);
holder.textLeft.setText(mDatas.get(position).getMsg()+"("+mDatas.get(position).getName()+")");
holder.textLeft.setTextColor(Color.RED);
holder.textLeft.setBackground(context.getResources().getDrawable(R.drawable.chat_blue));
}
Related
I trying to show firebase data by using recyclerview.
retrieving data is well, I can check it in logcat.
Sometimes recyclerview show data, but Usually show nothing.
When recycleview show data, it is reflectled firebase data well.
Who can tell me What the problem?? Is there mistake in my xml code?
Java code
artistData.child(starList[i]).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot starDataSnap) {
int fanNums = (int) starDataSnap.child("fanNums").getValue(Integer.class);
int placeNums = (int) starDataSnap.child("placeNums").getValue(Integer.class);
Log.d("####", finalStarName + fanNums + placeNums);
drawerStarImage = getResources().getIdentifier(finalStarImgName, "drawable", getActivity().getPackageName());
ItemStarData itemStarData = new ItemStarData();
itemStarData.setStarImage(drawerStarImage);
itemStarData.setStarName(finalStarName);
itemStarData.setFanNums(fanNums);
itemStarData.setPlaceNums(placeNums);
drawerStarList.add(itemStarData);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Adapter class code
public class AdapterStarlist extends RecyclerView.Adapter<AdapterStarlist.ViewHolder>{
ArrayList<ItemStarData> array;
Context context;
public AdapterStarlist(ArrayList<ItemStarData> array, Context context) {
this.array = array;
this.context =context;
}
#NonNull
#Override
public AdapterStarlist.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.item_home_starlist,parent,false);
return new AdapterStarlist.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AdapterStarlist.ViewHolder holder, int position) {
Log.d("####", array.get(position).getStarName());
holder.Imgstarlist.setImageResource(array.get(position).getStarImage());
holder.followStarName.setText(String.valueOf(array.get(position).getStarName()));
holder.starlistfanNum.setText(String.valueOf(array.get(position).getFanNums()));
holder.starlistPlaceNum.setText(String.valueOf(array.get(position).getPlaceNums()));
}
#Override
public int getItemCount() {
return array.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView Imgstarlist;
TextView followStarName;
TextView starlistfanNum;
TextView starlistPlaceNum;
public ViewHolder(#NonNull View itemView) {
super(itemView);
Imgstarlist =itemView.findViewById(R.id.Imgstarlist);
followStarName =itemView.findViewById(R.id.followStarName);
starlistfanNum =itemView.findViewById(R.id.starlistfanNum);
starlistPlaceNum =itemView.findViewById(R.id.starlistPlaceNum);
Imgstarlist.setBackground(new ShapeDrawable(new OvalShape()));
Imgstarlist.setClipToOutline(true);
}
}
}
Part of xml code
<ScrollView
android:layout_width="match_parent"
android:layout_height="480dp"
android:layout_marginTop="24dp"
android:fillViewport="true"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/DrawerStarlist"
>
<RelativeLayout
android:id="#+id/rlDrawerStarlist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/DrawerStarlist">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvDrawerStarlist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
/>
</RelativeLayout>
</ScrollView>
It looks like you're adding the data to the drawerStarList list, but not telling the adapter that you've done so. Until you tell the adapter of the change (by calling notifyDataSetChanged() on it), it won't repaint the UI for the list.
So typically this would look something like:
artistData.child(starList[i]).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot starDataSnap) {
...
drawerStarList.add(itemStarData);
adapter.notifyDataSetChanged(); // tell the adapter to repaint its views
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
With adapter being a reference to the adapter that you use to manage drawerStarList.
I'm just trying to display all images uploaded to Firebase Storage using a recyclerview. Every time I run my app to test out everything my app crashes and when I check the Logcat it keeps telling me Attempt to invoke interface method 'int java.util.List.size()' on a null object reference at com.myapp.yoody.AdapterOne.getItemCount. I'm just wondering what is the null object its referring to. Is it talking about the fact that it's not connecting to firebase? or what is it? I've been trying for days to get this thing to work and I've got nothing. Please help me out here. I hope my question doesn't sound confusing. Here's my code below. Thanks in advance
//Profilepage (The page where the images are supposed to display)
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
TextView name;
DatabaseReference databaseReference;
StorageReference storageReference;
private Context mccontext=ProfileActivity.this;
RecyclerView recyclerView;
AdapterOne adapter1;
String uid;
// Folder path for Firebase Storage.
ImageView imageView;
//List<ImageUploadInfo> list=new ArrayList<>();
ArrayList<ImageUploadInfo> imagesList;
// Folder path for Firebase Storage.
String Storage_Path = "Images/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "Images";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
recyclerView=findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
recyclerView.setHasFixedSize(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
adapter1=new AdapterOne(mccontext,imagesList);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter1);
imagesList=new ArrayList<>();
adapter1.notifyDataSetChanged();
//databaseReference=FirebaseDatabase.getInstance().getReference("Users");
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
// Assign FirebaseStorage instance to storageReference.
storageReference = FirebaseStorage.getInstance().getReference();
// Assign FirebaseDatabase instance with root database name.
databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
// Adding Add Value Event Listener to databaseReference.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren() ){
ImageUploadInfo imageUploadInfo=postSnapshot.getValue(ImageUploadInfo.class);
imagesList.add(imageUploadInfo);
}
adapter1 = new AdapterOne(getApplicationContext(), imagesList);
recyclerView.setAdapter(adapter1);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
//My Adapter class
public class AdapterOne extends RecyclerView.Adapter<AdapterOne.ViewHolder> {
Context context;
List<ImageUploadInfo> imagesList;
public AdapterOne(Context c, List<ImageUploadInfo> TempList) {
imagesList = TempList;
context = c;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ImageUploadInfo imageUploadInfo = imagesList.get(position);
Glide.with(context).load(imageUploadInfo.getImageUrl()).into(holder.imageView);
}
#Override
public int getItemCount() {
return imagesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView=(ImageView) itemView.findViewById(R.id.imageview);
}
}
}
//UploadInfo class
public class ImageUploadInfo {
// public String imageName;
public String imageURL;
public ImageUploadInfo() {} // default constructor that takes no arguments
public ImageUploadInfo( String url) {
this.imageURL= url;
}
public String getImageUrl() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
}
//CardView class
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:orientation="vertical"
>
<GridLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginTop="0dp"
android:alignmentMode="alignMargins"
android:columnCount="1"
android:paddingTop="20dp"
android:columnOrderPreserved="false"
android:rowCount="3">
<!-- 3 -->
<!-- 4 -->
<androidx.cardview.widget.CardView
android:layout_width="350dp"
android:layout_height="320dp"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_marginLeft="6dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="10dp"
app:cardCornerRadius="0dp"
app:cardElevation="0dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:id="#+id/imageview"
/>
<!--
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imagename"
android:text="Image Name"
/>
-->
</androidx.cardview.widget.CardView>
</GridLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
The problem is that you initialize the list AFTER you send it to adapter. So adapter trying to execute its method on the list which is not exist. Move init lane BEFORE send it in adapter
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to fetch data from firebase and put it into a recycler view through adapter. But, no data is being displayed.
My code in Main Activity:
DatabaseReference databaseReference;
RecyclerView recyclerView;
ArrayList<Menu> menuList;
EditMenuAdapter editMenuAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_menu);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
menuList = new ArrayList<Menu>();
databaseReference = FirebaseDatabase.getInstance().getReference().child("menu");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Menu menu = dataSnapshot1.getValue(Menu.class);
menuList.add(menu);
}
editMenuAdapter = new EditMenuAdapter(EditMenuActivity.this, menuList);
recyclerView.setAdapter(editMenuAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(EditMenuActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
});
My adapter class:
public class EditMenuAdapter extends RecyclerView.Adapter<EditMenuAdapter.MyViewHolder> {
Context context;
ArrayList<Menu> menuArrayList;
public EditMenuAdapter(Context c, ArrayList<Menu> menus) {
context = c;
menuArrayList = menus;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.menu_list_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.dishNameTextView.setText(menuArrayList.get(position).getDishName());
holder.dishPriceTextView.setText(menuArrayList.get(position).getDishPrice());
}
#Override
public int getItemCount() {
return menuArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView dishNameTextView;
TextView dishPriceTextView;
Switch dishActiveSwitch;
public MyViewHolder(View view) {
super(view);
dishNameTextView = (TextView) view.findViewById(R.id.dishNameTextView);
dishPriceTextView = (TextView) view.findViewById(R.id.dishPriceTextView);
dishActiveSwitch = (Switch) view.findViewById(R.id.dishActiveSwitch);
}
}
}
The layout resource file is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditMenuActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="397dp"
android:layout_height="599dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/doneButton"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:text="Done"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/recyclerView" />
The log shows: E/RecyclerView: No adapter attached; skipping layout. No data is displayed.
Only the switch is being displayed on the screen. Please help!
Create instance of adapter in onCreate and attach it to RV:
protected void onCreate(Bundle savedInstanceState) {
...
editMenuAdapter = new EditMenuAdapter(this, new ArrayList<>());
recyclerView.setAdapter(adapter);
...
}
In the response of Firebase onDataChange:
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
...
editMenuAdapter.setItems(menuList);
runOnUiThread(() -> editMenuAdapter.notifyDataSetChanged());
}
I am working on printing all users based on the UID, but I only get one user printed.
This is the result I am getting now.
Here is what the printingUserList(), this is a small function to retrieve all user information based on UID.
RecyclerView rv;
UserAdapter usrAdapter;
ArrayList<User> mUsrsList;
private void readUsrs(){
LinearLayoutManager LayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(LayoutManager);
mUsrsList = new ArrayList<>();
final FirebaseUser me = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUsrsList.clear();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
Log.d("TAG_", "A++" + dataSnapshot.getChildrenCount()); //prints 5, which exactly has five users in the database.
User all_usr = ds.getValue(User.class);
if (!all_usr.getUid().equals(me.getUid())) { //won't print itself
mUsrsList.add(all_usr);
}
}
System.out.println(mUsrsList.toString());
usrAdapter = new UserAdapter(RoomUser_Activity.this, mUsrsList);
rv.setAdapter(usrAdapter);
usrAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
and this is the recyclerview, should be correct otherwise it prints nothing
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserViewHolder> {
private Context m_context;
private ArrayList<User> all_users;
public static final String EXTRA_HISUID = "NoHisUID";
public UserAdapter(Context context, ArrayList<User> all_users) {
this.m_context = context;
this.all_users = all_users;
}
#NonNull
#Override
public UserAdapter.UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(m_context);
View itemv = inflater.inflate(R.layout.layout_item_user, parent, false); //xml provide below
return new UserViewHolder(itemv);
}
public class UserViewHolder extends RecyclerView.ViewHolder{
public ImageView UserIcon; //default icon provided in xml
public TextView Username;
public UserViewHolder (View itemView){
super(itemView);
UserIcon = (ImageView)itemView.findViewById(R.id.usr_icon);
Username = (TextView)itemView.findViewById(R.id.tv_username);
}
}
public void onBindViewHolder(#NonNull UserAdapter.UserViewHolder holder, int position) {
User usr = all_users.get(position);
final String hisUID = usr.getUid();
holder.Username.setText(usr.getUsername());
if(usr.getIcon().equals("default_icon")){
holder.UserIcon.setImageResource(R.drawable.default_icon);
}
else{
Glide.with(m_context).load(usr.getIcon()).into(holder.UserIcon);
}
}
public int getItemCount() {
return all_users.size();
}
layout_item_user.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="match_parent">
<ImageView
android:id="#+id/usr_icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="13dp"
android:layout_toEndOf="#+id/usr_icon"
android:layout_toRightOf="#+id/usr_icon"
android:text="username"
android:textSize="18sp" />
<TextView
android:id="#+id/lastMessageTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="The last message"
android:layout_marginStart="4dp"
android:maxLines="2"
android:layout_marginTop="3dp"
android:layout_toRightOf="#id/usr_icon"
android:layout_below="#id/tv_username"
android:layout_marginLeft="13dp" />
</RelativeLayout>
database:
users:
|-2NUPkQuHFRS49ZHDZzEtWiErIiv1
|-address: "920 West 4th Ave apt231"
|-city: "blank"
|-donut: 0
|-email: "not_busy#gmail.com"
|-full_name: "blank"
|-icon: "default_icon"
|-phone: "253353309"
|-state: "blank"
|-uid: "2NUPkQuHFRS49ZHDZzEtWiErIiv1"
|-username: "not_busy"
|-F0NRthr8uJPYMz2o129w2PAf30i1
|-GRJPA5hKA6aRgNl68sSxv3xruww1
|-W0PIUjUwRHXTkooztYFuhKuLItE3
|-cBzUNHceM2T47cr0zWX1tqgB2wA3
It must be a small bug, but I still cannot figure what problem is.. thank you in advance.
I have a ListView with 3 TextViews and a radio button in each row. I retrieve a certain state from my firebase database and show it in the radio button. I just don't know how to access the radio button to change its state. I know i should use a custom adapter but i don't how to. Can someone help ?
This is my code for the time being :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grille);
listView = (ListView) findViewById(R.id._afficher);
bus = new Bus(ThreadEnforcer.MAIN);
bus.register(this);
listView.addHeaderView(getLayoutInflater().inflate(R.layout.header, null, false));
loadData();
}
private void loadData(){
DatabaseReference mDB = FirebaseDatabase.getInstance().getReference("VFL");
mDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
MatrixCursor matrixCursor= new MatrixCursor(columns);
startManagingCursor(matrixCursor);
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapsht : snapshot.getChildren()){
String s = snapsht.child("visiteur").getValue().toString();
if(s.equals(visiteur) || s.equals(visiteur1)){
matrixCursor.addRow(new Object[] {count.incrementAndGet(), snapsht.child("date").getValue().toString(),
snapsht.child("zone").getValue().toString(),snapsht.child("visité").getValue().toString() });
}
}
}
bus.post(matrixCursor);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Subscribe public void answerAvailable( MatrixCursor matrixCursor) {
// TODO: React to the event somehow!
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.ligne_afficher, matrixCursor, from, to, 0);
listView.setAdapter(adapter);
}
See this example using CustomAdapter extending BaseAdapter class:
1. listview activity layout
<?xml version="1.0" encoding="utf-8"?>
<ListView 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="in.oxyzen.loc.YourActivity"
android:id="#+id/listView">
</ListView>
2. listview's single_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="tv1"
android:id="#+id/tv1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="tv2"
android:id="#+id/tv2"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="tv3"
android:id="#+id/tv3"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"
android:id="#+id/radioButton"/>
</LinearLayout>
3. (listview's activity) YourActivity.java
public class YourActivity extends AppCompatActivity implements ChildEventListener {
ListView listView;
CustomAdapter adapter;
DatabaseReference yourReference;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yourReference =FirebaseDatabase.getInstance().getReference().child("your_reference");
dialog = new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
setContentView(R.layout.activity_your);
listView = (ListView)findViewById(R.id.listView);
adapter = new CustomAdapter();
listView.setAdapter(adapter);
dialog.show();
yourReference.addChildEventListener(this);
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
dialog.dismiss();
adapter.addItem(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
}
4. CustomAdapter.java class for listview
public class CustomAdapter extends BaseAdapter {
ArrayList<DataSnapshot> values;
CustomAdapter(){
values = new ArrayList<>();
}
#Override
public int getCount() {
return values.size();
}
#Override
public Object getItem(int position) {
return values.get(position);
//you can get the dataSnapshot by interacting your listview items as per position for use in listview's activity.
//You can return null also here.
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
DataSnapshot snapshot = values.get(position);//use this snapshot to retrieve values for textviews and radiobutton.
OurViewHolder holder =new OurViewHolder(parent.getContext(),parent);
holder.tv1.setText(snapshot.getKey());
holder.tv2.setText("Text for textView 2");
holder.tv3.setText("Text for textView 3");
holder.button.setChecked(true);// manipulate your radio button as per your wish here. I just checked it for example.
return holder.itemView;
}
//Custom method: to notify and update adapter automatically if new child adds in firebase database.
void addItem(DataSnapshot snapshot){
values.add(snapshot);
notifyDataSetChanged();
}
//Custom class: Using OurViewHolder pattern keeps alive java's OOP concept i.e. one object per listview item.
//Inflate your single item's layout in here and find all components of item.
private class OurViewHolder {
View itemView;
TextView tv1,tv2,tv3;
RadioButton button;
OurViewHolder(Context context, ViewGroup parent){
itemView = LayoutInflater.from(context).inflate(R.layout.single_item_layout,parent,false);
tv1=(TextView)itemView.findViewById(R.id.tv1);
tv2=(TextView)itemView.findViewById(R.id.tv2);
tv3=(TextView)itemView.findViewById(R.id.tv3);
button=(RadioButton)itemView.findViewById(R.id.radioButton);
}
}
}