【问题标题】:How can I get the key of an item populated from firebase database clicked in the recyclerview如何获取从在 recyclerview 中单击的 firebase 数据库填充的项目的密钥
【发布时间】:2018-05-23 22:35:11
【问题描述】:

我有一个非常严重的问题。我正在使用 RecyclerView 将 Firebase 中的数据(用户列表)填充到我的应用程序中。现在的问题是当用户单击它们中的任何一个时如何引用它们各自的 userId,以便可以使用它来设置将打开的活动操作栏的标题。我尝试使用 getRef() 方法,但无法解决。下面是我的代码。

我的学生列表

package com.dreamlazerstudios.gtuconline;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.content.ContentValues.TAG;

public class StudentsList extends AppCompatActivity {

DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<Students> listData;
RecyclerView recyclerView;
StudentsList.MyAdapter adapter;

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private FirebaseDatabase mFirebaseDatabase;
private String userID;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_students_list);
    setTitle("List of Students");
    recyclerView = findViewById(R.id.students_list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setHasFixedSize(true);

    listData = new ArrayList<>();
    adapter = new StudentsList.MyAdapter(listData);
    adapter.setHasStableIds(true);

    GetDataFirebase();

    progressDialog = new ProgressDialog(this);
    progressDialog.setMessage("Loading Data...");
    progressDialog.show();

    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    final FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in

                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };

}

void GetDataFirebase() {

    databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("Students");

    databaseReference.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            Students students = dataSnapshot.getValue(Students.class);

            listData.add(students);

            recyclerView.setAdapter(adapter);

            progressDialog.dismiss();
        }

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

        }
    });


}

@Override
public void onStart() {
    super.onStart();

    mAuth.addAuthStateListener(mAuthListener);

}

public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {

    List<Students> list;

    public MyAdapter(List<Students> List) {
        this.list = List;
    }

    @Override
    public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {

        Students students = list.get(position);

        String list_user_id = getRef(position).getKey();

        holder.news_topic.setText(students.getName());
        holder.news_body.setText(students.getProgramme());

        if (students.getOnline() == true) {
            holder.online.setVisibility(View.VISIBLE);
        } else {
            holder.online.setVisibility(View.INVISIBLE);
        }

        Picasso.with(holder.news_image.getContext()).load(students.getThumb_image()).placeholder(R.drawable.student_icon_17870).into(holder.news_image);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent chat_intent = new Intent(StudentsList.this, ChatActivity.class);
                chat_intent.putExtra("user_id", list_user_id );
                startActivity(chat_intent);
            }
        });

    }

    @NonNull
    @Override
    public StudentsList.MyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_layout, parent, false);

        return new StudentsList.MyAdapter.ViewHolder(view);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView news_topic, news_body;
        CircleImageView news_image;
        ImageView online;

        public ViewHolder(View itemView) {
            super(itemView);

            news_topic = itemView.findViewById(R.id.user_single_name);
            news_body = itemView.findViewById(R.id.user_single_status);
            news_image = itemView.findViewById(R.id.user_single_image);
            online = itemView.findViewById(R.id.online_status_icon);
        }

    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}

}

我的模型课

package com.dreamlazerstudios.gtuconline;

/**
 * Created by Gabriel Hagan on 16/05/2018 at 23:10.
*/
public class Students {

String name;
String programme;
String thumb_image;
Boolean online;

public Boolean getOnline() {
    return online;
}

public void setOnline(Boolean online) {
    this.online = online;
}

public Students() {
}

public Students(String name, String programme, String thumb_image, Boolean online) {
    this.name = name;
    this.programme = programme;
    this.thumb_image = thumb_image;
    this.online = online;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getProgramme() {
    return programme;
}

public void setProgramme(String programme) {
    this.programme = programme;
}

public String getThumb_image() {
    return thumb_image;
}

public void setThumb_image(String thumb_image) {
    this.thumb_image = thumb_image;
}

}

我的聊天活动

package com.dreamlazerstudios.gtuconline;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ChatActivity extends AppCompatActivity {

private DatabaseReference rootRef;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;
private String mChatUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    rootRef = FirebaseDatabase.getInstance().getReference();
    mAuth = FirebaseAuth.getInstance();
    final FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();

    mChatUser = getIntent().getStringExtra("user_id");

    rootRef.child("Users").child("Students").child(mChatUser).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            String chat_user_name = dataSnapshot.child("name").getValue().toString();
            setTitle(chat_user_name);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    rootRef.child("Chat").child(userID).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
}

My database snapshot

【问题讨论】:

    标签: java android firebase firebase-realtime-database android-recyclerview


    【解决方案1】:

    您可以从您在 onChildAdded 中获取的 DataSnapshot 中获取密钥。您可以保留 DataSnapshots 列表,而不是在适配器中包含学生列表。然后你可以这样做:

    在学生列表中,更改:

    List<Students> listData;
    

    收件人:

    List<DataSnapshot> listData;
    

    另外,更改 onChildAdded:

        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    
            listData.add(dataSnapshot);
            //Should probably move these since they don't need to get called for every item.
            recyclerView.setAdapter(adapter);  
            progressDialog.dismiss();
        }
    

    然后在你的适配器中:

    public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
    
        List<DataSnapshot> list;
    
        public MyAdapter(List<DataSnapshot> List) {
            this.list = List;
        }
        @Override
        public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
    
            DataSnapshot studentSnapshot = list.get(position);
    
            String list_user_id = studentSnapshot.getKey();
    
            Students students = studentSnapshot.getValue(Students.class)
    
            //The rest unchanged
    

    【讨论】:

    • 你遇到了什么错误?您是否将 listData 类型更改为 DataSnapshot 并在 onChildAdded 中添加快照而不是学生?
    • 我该怎么做?我是初学者,请帮忙
    • 谢谢科迪。那么现在我如何获取名称、程序和在线节点的数据。你强加给我的错误更多。
    • 您是否添加了我在 onBindViewHolder 中放入的最后一行? Students students = studentSnapshot.getValue(Students.class)
    • 现在 listdata 变量返回错误。适配器 = new StudentsList.MyAdapter(listData);
    【解决方案2】:

    onBindViewHolder 方法中,您可以使用以下代码行获取您正在寻找的用户的密钥:

    String list_user_id = getItem(position);
    

    getRef() 用于获取对快照源位置的引用。所以你只能在快照对象上使用这个方法。它返回一个 DatabaseReference 并且不接受任何参数。下面是一个例子:

    DatabaseReference ref = dataSnapshot.child("users").getRef();
    

    【讨论】:

    • onBindViewHolder 中没有类似“getItem”的方法。它返回了一个错误。
    • 我宁愿这样做。 chat_intent.putExtra("user_name", students.getName());而且我能够获得被点击的相应用户的名称。但我需要获取被点击的那个用户的用户 ID 并将其存储在数据库中。我该怎么做?
    • 是的,它是一个类似于 onBindViewHolder 中的“getItem”的方法。错误是什么?
    • 您使用的是最新版本的 Firebase-UI 库吗?
    • 我一定会的
    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多