如何从recyclerview中单击firebase数据库中获取填充项的键

时间:2018-05-22 12:13:16

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

我有一个非常严重的问题。我使用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;
}

}

我的ChatActivity

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

2 个答案:

答案 0 :(得分:1)

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

在StudentsList中,更改:

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

答案 1 :(得分:0)

onBindViewHolder方法内,您可以使用以下代码行获取您要查找的用户的密钥:

String list_user_id = getItem(position);

getRef()用于获取对快照源位置的引用。因此,您只能在快照对象上使用此方法。它返回DatabaseReference并且不带参数。下面是一个例子:

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