gpt4 book ai didi

java - 无法在 Android 中显示来自 Firebase 实时数据库的随机数据

转载 作者:行者123 更新时间:2023-12-02 00:58:06 25 4
gpt4 key购买 nike

我正在尝试将 Firebase 中的用户随机分配到我的 RecyclerView。我尝试在注册时为用户创建一个随机 ID,并添加相关查询,但会使用大量内存来下载所有可用数据从 Firebase 中,我尝试的第二种方法在以下行中显示错误

 DatabaseReference productIdRef = rootRef.child("Users").child(UserIdsList.get(new Random().nextInt(UserListSize)));//Line149

堆栈跟踪

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)

错误是

代码

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) {

}
});
}

}

最佳答案

因为您已经创建了 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();

关于java - 无法在 Android 中显示来自 Firebase 实时数据库的随机数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61064312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com