无法在Android中从Firebase实时数据库中显示随机数据。

huangapple go评论77阅读模式
英文:

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(&quot;Users&quot;).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)

无法在Android中从Firebase实时数据库中显示随机数据。

and the error is

code

> UserFragment.java

public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List&lt;User&gt; mUsers;
String TAG = &quot;MyTag&quot;;
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&lt;&gt;();
//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(&quot;UserIds&quot;);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List&lt;String&gt; UserList = new ArrayList&lt;&gt;();
List&lt;String&gt; UserIdsList = new ArrayList&lt;&gt;();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String productId = ds.getKey();
UserIdsList.add(productId);
}
int UserListSize = UserList.size();
List&lt;String&gt; randomProductList = new ArrayList&lt;&gt;();
DatabaseReference productIdRef = rootRef.child(&quot;Users&quot;).child(UserIdsList.get(new Random().nextInt(UserListSize)));
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child(&quot;Firs&quot;).getValue(String.class);
Log.d(&quot;TAG&quot;, name);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, &quot;Error: &quot; + databaseError.toException()); //Don&#39;t ignore errors!
}
};
productIdRef.addListenerForSingleValueEvent(eventListener);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, &quot;Error: &quot; + databaseError.getMessage()); //Don&#39;t ignore errors!
}
};
productIdsRef.addListenerForSingleValueEvent(valueEventListener);
}
}

> UserAdapter

    public class UserAdapter extends RecyclerView.Adapter&lt;UserAdapter.ViewHolder&gt; {
private Context mContext;
private List&lt;User&gt; mUsers;
private boolean ischat;
String theLastMessage;
public UserAdapter(Context mContext, List&lt;User&gt; 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(&quot;default&quot;)){
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(&quot;online&quot;)){
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(&quot;UserName&quot;,user.getFirst());
intent.putExtra(&quot;userid&quot;, user.getId());
intent.putExtra(&quot;ImageURL&quot;,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 = &quot;default&quot;;
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(&quot;Chats&quot;);
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 &amp;&amp; chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) &amp;&amp; chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) &amp;&amp; chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case  &quot;default&quot;:
last_msg.setText(&quot;No Message&quot;);
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = &quot;default&quot;;
}
@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&lt;String&gt; UserList = new ArrayList&lt;&gt;();

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&lt;String&gt; UserList = new ArrayList&lt;&gt;();

List&lt;String&gt; UserIdsList = new ArrayList&lt;&gt;();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String productId = ds.getKey();
UserIdsList.add(productId);
}
int UserListSize = UserIdsList.size();

huangapple
  • 本文由 发表于 2020年4月7日 00:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/61064312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定