英文:
Unable to show random data from Firebase Realtime Database in Android
问题
public class UsersFragment extends Fragment {
// ... (other code)
private void RandomUsers() {
mUserAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productIdsRef = rootRef.child("UserIds");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> UserList = new ArrayList<>();
List<String> UserIdsList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String productId = ds.getKey();
UserIdsList.add(productId);
}
int UserListSize = UserList.size();
List<String> randomProductList = new ArrayList<>();
DatabaseReference productIdRef = rootRef.child("Users").child(UserIdsList.get(new Random().nextInt(UserListSize)));
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("First").getValue(String.class);
Log.d("TAG", name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException());
}
};
productIdRef.addListenerForSingleValueEvent(eventListener);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.getMessage());
}
};
productIdsRef.addListenerForSingleValueEvent(valueEventListener);
}
}
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
// ... (other code)
@Override
public void onBindViewHolder(@NonNull UserAdapter.ViewHolder holder, int position) {
final User user = mUsers.get(position);
holder.username.setText(user.getFirst());
// ... (other code)
if (ischat) {
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
// ... (other code)
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, MessageActivity.class);
intent.putExtra("UserName", user.getFirst());
intent.putExtra("userid", user.getId());
intent.putExtra("ImageURL", user.getImageURL());
mContext.startActivity(intent);
}
});
}
// ... (other code)
private void lastMessage(final String userid, final TextView last_msg) {
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if ((chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid)) ||
(chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid()))) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage) {
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
英文:
I am trying to random users from Firebase on to my RecyclerView.I have tried creating a random id for the user on the time of registration and adding queries with respect to that but uses a lot of memory to download all the available data from the Firebase the second method which i tried shows me error in the following line
DatabaseReference productIdRef = rootRef.child("Users").child(UserIdsList.get(new Random().nextInt(UserListSize)));//Line149
Stack Trace
2020-04-06 23:39:33.277 29631-29631/com.shivam.chatapp2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.shivam.chatapp2, PID: 29631
java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at com.shivam.chatapp2.Fragments.UsersFragment$1.onDataChange(UsersFragment.java:90)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.2.1:179)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
and the error is
code
> UserFragment.java
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
ValueEventListener mValueEventListener;
public UsersFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
//readUser();
RandomUsers();
return view;
}
private void RandomUsers() {
mUserAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productIdsRef = rootRef.child("UserIds");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> UserList = new ArrayList<>();
List<String> UserIdsList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String productId = ds.getKey();
UserIdsList.add(productId);
}
int UserListSize = UserList.size();
List<String> randomProductList = new ArrayList<>();
DatabaseReference productIdRef = rootRef.child("Users").child(UserIdsList.get(new Random().nextInt(UserListSize)));
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Firs").getValue(String.class);
Log.d("TAG", name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException()); //Don't ignore errors!
}
};
productIdRef.addListenerForSingleValueEvent(eventListener);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.getMessage()); //Don't ignore errors!
}
};
productIdsRef.addListenerForSingleValueEvent(valueEventListener);
}
}
> UserAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private boolean ischat;
String theLastMessage;
public UserAdapter(Context mContext, List<User> mUsers,boolean ischat) {
this.mContext = mContext;
this.mUsers = mUsers;
this.ischat=ischat;
}
@NonNull
@Override
public UserAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
if (user.getImageURL().equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat){
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat){
if (user.getStatus().equals("online")){
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(mContext, MessageActivity.class);
intent.putExtra("UserName",user.getFirst());
intent.putExtra("userid", user.getId());
intent.putExtra("ImageURL",user.getImageURL());
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
public ViewHolder(@NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.username);
profile_image=itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg=itemView.findViewById(R.id.last_msg);
}
}
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
答案1
得分: 2
因为您已经创建了一个新的UserList实例
List<String> UserList = new ArrayList<>();
但是您完全没有使用它,并且获取UserList.size()
始终为零,这导致了new Random().nextInt(UserListSize))
得到无效的消息
java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
因此,通过获取UserIdsList
的大小来简单修复此问题,这可以在列表内获取随机用户。移除List<String> UserList = new ArrayList<>();
的所有使用
List<String> UserIdsList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String productId = ds.getKey();
UserIdsList.add(productId);
}
int UserListSize = UserIdsList.size();
英文:
Because you have created a new instance of UserList
List<String> UserList = new ArrayList<>();
But then you have no using at all and get UserList.size()
that always zero and it leads to new Random().nextInt(UserListSize))
got invalid message
> java.lang.IllegalArgumentException: bound must be positive
> at java.util.Random.nextInt(Random.java:388)
So it's simple fixing by getting the size of UserIdsList
that could get random user within list. Remove of of using of List<String> UserList = new ArrayList<>();
List<String> UserIdsList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String productId = ds.getKey();
UserIdsList.add(productId);
}
int UserListSize = UserIdsList.size();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论