Здесь у меня есть вид переработчика, показывающий список документов, извлеченных из ОДНОЙ конкретной коллекции.
По щелчку любого элемента списка, как получить его идентификатор документа и, следовательно, выполнить операции обновления и удаления, тем самым обновляя его в модуле аутентификации FIREBASE AND FIRESTORE ..
public class AllUsers extends AppCompatActivity implements CustomItemClickListener {
FirebaseAuth auth;
FirebaseFirestore db_fr;
ArrayList<RegisterUser> users;
RecyclerView view;
UserRecyclerAdapter adapter;
RegisterUser user;
String docID;
UserId uid;
ArrayList<UserId> idList;
void initViews(){
auth = FirebaseAuth.getInstance();
db_fr = FirebaseFirestore.getInstance();
view = findViewById(R.id.user_recyler);
LinearLayoutManager linear = new LinearLayoutManager(AllUsers.this);
view.setLayoutManager(linear);
users = new ArrayList<>();
user = new RegisterUser();
uid = new UserId();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_users);
initViews();
fetchAllUsersFromFireStore();
}
void fetchAllUsersFromFireStore(){
users = new ArrayList<>();
idList = new ArrayList<>();
db_fr.collection("Users").get().addOnCompleteListener(this, new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for (QueryDocumentSnapshot document : task.getResult()){
docID = document.getId();
user = document.toObject(RegisterUser.class);
for(DocumentSnapshot doc : task.getResult()) {
uid = doc.toObject(UserId.class);
uid.doc_ID = doc.getId();
idList.add(uid);
Log.i("qwe",""+idList);
}
users.add(user);
Toast.makeText(AllUsers.this,"Data Retrieved",Toast.LENGTH_LONG).show();
adapter = new UserRecyclerAdapter(AllUsers.this,R.layout.user_list_view,users);
view.setAdapter(adapter);
adapter.registerCustomItemClickListner(AllUsers.this);
}
}else {
Toast.makeText(AllUsers.this,"Some Error",Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onItemClick(View v, int position) {
user = users.get(position);
uid = idList.get(position);
Log.i("idwe",""+uid);
Log.i("ewdi",""+user.Name);
showOptions();
Toast.makeText(AllUsers.this,"--Clickable--"+position,Toast.LENGTH_LONG).show();
}
void showOptions(){
String[] options = {"View","Delete","Update","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
showInfo();
break;
case 1:
askForDeletion();
break;
case 2:
Intent intent = new Intent(AllUsers.this,RegistrationActivity.class);
intent.putExtra("keyUser",user);
intent.putExtra("keyID",uid);
startActivityForResult(intent,101);
break;
case 3:
//finish();
break;
}
}
});
builder.create().show();
}
void showInfo(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Details of "+user.Name);
builder.setMessage(user.toString());
builder.setPositiveButton("Done",null);
builder.create().show();
}
void askForDeletion(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete "+user.Name+" ?");
builder.setMessage("Are You Sure to delete record?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteUserFromFireStore();
}
});
builder.setNegativeButton("Cancel",null);
builder.create().show();
}
void deleteUserFromFireStore()
{
String id = uid.doc_ID;
Log.i("oli",""+id);
db_fr.collection("Users").document(id).delete()
.addOnCompleteListener(AllUsers.this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Log.i("TASK 1",""+ task.getResult());
Toast.makeText(AllUsers.this,"User Deleted",Toast.LENGTH_LONG).show();
users.remove(user);
adapter.notifyDataSetChanged();
}else {
Toast.makeText(AllUsers.this,"Some Error, Deletion Unsuccessfull !",Toast.LENGTH_LONG).show();
}
}
});
}
}
Я использовал разные объектные бины: один с данными пользователя, а другой только для получения идентификатора документа
(в чем я не уверен)
Моя регистрационная активность выглядит следующим образом
public class RegistrationActivity extends AppCompatActivity implements View.OnClickListener{
EditText name,contact,email,password;
Button register;
RegisterUser user;
FirebaseAuth auth;
ProgressDialog pd;
FirebaseFirestore db_Firestore;
boolean updateMode;
UserId uid;
String uid1;
Intent rcv;
void initViews(){
name = findViewById(R.id.textName);
contact = findViewById(R.id.textContact);
email = findViewById(R.id.textEmail);
password = findViewById(R.id.textPassword);
register = findViewById(R.id.registerBtn);
register.setOnClickListener(this);
getSupportActionBar().setTitle("Register");
pd = new ProgressDialog(this);
pd.setMessage("Please Wait ..");
uid = new UserId();
auth = FirebaseAuth.getInstance();
db_Firestore = FirebaseFirestore.getInstance();
rcv = getIntent();
updateMode = rcv.hasExtra("keyUser");
if (updateMode) {
user = (RegisterUser) rcv.getSerializableExtra("keyUser");
uid = (UserId) rcv.getSerializableExtra("keyID");
uid1 = uid.doc_ID;
name.setText(user.Name);
contact.setText(user.Contact);
email.setText(user.Email);
register.setText("Update User");
register.setOnClickListener(this);
}
}
void saveUserInFireStore()
{
String userid = auth.getCurrentUser().getUid();
Log.i("userId",""+userid.toString());
db_Firestore.collection("Users").document(userid)
.set(user).addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
pd.dismiss();
Toast.makeText(RegistrationActivity.this,"Registration Successfull",Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegistrationActivity.this,MainActivity.class);
startActivity(intent);
finish();
}else {
pd.dismiss();
Toast.makeText(RegistrationActivity.this,"Some Error",Toast.LENGTH_LONG).show();
}
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
initViews();
if (isNetworkConnected()){
Toast.makeText(this,"Connection Succesfull",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this,"No Internet Connection",Toast.LENGTH_LONG).show();
}
}
@Override
public void onClick(View v) {
if (updateMode){
uid = (UserId)rcv.getSerializableExtra("keyID");
uid1 = uid.doc_ID;
user = new RegisterUser();
user.Name = name.getText().toString().trim();
user.Contact = contact.getText().toString().trim();
user.Email = email.getText().toString().trim();
user.Password = password.getText().toString().trim();
db_Firestore.collection("Users").document(uid1).set(user);
Toast.makeText(RegistrationActivity.this,"Updated Successfully ..",Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegistrationActivity.this,MainActivity.class);
intent.putExtra("did",uid);
startActivity(intent);
finish();
}else {
user = new RegisterUser();
user.Name = name.getText().toString().trim();
user.Contact = contact.getText().toString().trim();
user.Email = email.getText().toString().trim();
user.Password = password.getText().toString().trim();
pd.show():
auth.createUserWithEmailAndPassword(user.Email,user.Password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(RegistrationActivity.this,"Signed In Successfully ..",Toast.LENGTH_LONG).show();
saveUserInFireStore();
}else {
Toast.makeText(RegistrationActivity.this,"Some Error, Try Again ..",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
});
}
}
public boolean isNetworkConnected(){
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm !=null){
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return (activeNetwork!=null && activeNetwork.isConnectedOrConnecting());
}else {
return false;
}
}
}
Кроме того, в виде списка при нажатии элемента списка,
я перехожу к основной деятельности с выбранными данными пользователя,
auth.getCurrentUser (). getUid () возвращает null, и мне нужно получить идентификатор документа, а затем выполнить пересылку, почему это так?
Пожалуйста, помогите!