当我尝试从 firebase 更新数据时出错

Posted

技术标签:

【中文标题】当我尝试从 firebase 更新数据时出错【英文标题】:Error when i try to update data from firebase 【发布时间】:2022-01-08 04:44:38 【问题描述】:

我想使用我的应用程序从 firebase 更新一些数据,但是当我提交它时,数据只会重复,没有更改,也不知道为什么。我把我的代码放在下面:

我的班级用户Pojo

 package com.example.proyectofinaldanielsanchez;

import java.io.Serializable;

public class userPojo implements Serializable 

private String Tipo;
private String Titulo;
private String Avance;
private String Plataforma;
private String Key;

public userPojo() 


public userPojo(String Tipo, String Titulo, String Avance, String Plataforma)
    this.Tipo=Tipo;
    this.Titulo=Titulo;
    this.Avance=Avance;
    this.Plataforma=Plataforma;


public String getTipo() 
    return Tipo;


public void setTipo(String Tipo) 
    this.Tipo = Tipo;


public String getKey() 
    return Key;


public void setKey(String Key) 
    this.Key = Key;


public String getTitulo() 

    return Titulo;


public void setTitulo(String Titulo) 
    this.Titulo = Titulo;


public String getAvance() 
    return Avance;


public void setAvance (String Avance) 
    this.Avance = Avance;




public String getPlataforma() 
    return Plataforma;


public void setPlataforma(String Plataforma) 
    this.Plataforma = Plataforma;

类适配器:

 package com.hellokh.sovary.firetest;

  import android.content.Context; 
  import android.content.Intent;
   import android.view.LayoutInflater;
    import android.view.View;
   import android.view.ViewGroup;
 import android.widget.PopupMenu;
 import android.widget.Toast;

  import androidx.annotation.NonNull;
 import androidx.recyclerview.widget.RecyclerView;

  import java.util.ArrayList;

  public class RVAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>

private Context context;
ArrayList<Employee> list = new ArrayList<>();
public RVAdapter(Context ctx)

    this.context = ctx;

public void setItems(ArrayList<Employee> emp)

    list.addAll(emp);


@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)

    View view = LayoutInflater.from(context).inflate(R.layout.layout_item,parent,false);
    return new EmployeeVH(view);

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position)

    Employee e = null;
    this.onBindViewHolder(holder,position,e);


public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, Employee e)

    EmployeeVH vh = (EmployeeVH) holder;
    Employee emp = e==null? list.get(position):e;
    vh.txt_name.setText(emp.getName());
    vh.txt_position.setText(emp.getPosition());
    vh.txt_option.setOnClickListener(v->
    
        PopupMenu popupMenu =new PopupMenu(context,vh.txt_option);
        popupMenu.inflate(R.menu.option_menu);
        popupMenu.setOnMenuItemClickListener(item->
        
            switch (item.getItemId())
            
                case R.id.menu_edit:
                    Intent intent=new Intent(context,MainActivity.class);
                    intent.putExtra("EDIT",emp);
                    context.startActivity(intent);
                    break;
                case R.id.menu_remove:
                    DAOEmployee dao=new DAOEmployee();
                    dao.remove(emp.getKey()).addOnSuccessListener(suc->
                    
                        Toast.makeText(context, "Record is removed", Toast.LENGTH_SHORT).show();
                        notifyItemRemoved(position);
                        list.remove(emp);
                    ).addOnFailureListener(er->
                    
                        Toast.makeText(context, ""+er.getMessage(), Toast.LENGTH_SHORT).show();
                    );

                    break;
            
            return false;
        );
        popupMenu.show();
    );


@Override
public int getItemCount()

    return list.size();


类档案:

   package com.example.proyectofinaldanielsanchez;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

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;

import java.util.HashMap;
import java.util.Map;

public class Archivos extends AppCompatActivity  


protected void onCreate(Bundle savedInstanceState)

    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_archivos2);
    final EditText edit_tipo = findViewById(R.id.edit_tipo);
    final EditText edit_titulo = findViewById(R.id.edit_titulo);
    final EditText edit_avance=findViewById(R.id.edit_avance);
    final EditText edit_plataforma=findViewById(R.id.edit_plataforma);
    Button btn = findViewById(R.id.btn_submit);
    Button btn_open = findViewById(R.id.btn_open);
    btn_open.setOnClickListener(v->
    
        Intent intent =new Intent(Archivos.this, Visualizar.class);
        startActivity(intent);
    );
    DAOUserPojo dao =new DAOUserPojo();
    userPojo user_edit = (userPojo) getIntent().getSerializableExtra("EDIT");
    if(user_edit !=null)
    
        btn.setText("UPDATE");
        edit_tipo.setText(user_edit.getTipo());
        edit_titulo.setText(user_edit.getTitulo());
        edit_avance.setText(user_edit.getAvance());
        edit_plataforma.setText(user_edit.getPlataforma());

        btn_open.setVisibility(View.GONE);
    
    else
    
        btn.setText("SUBMIT");
        btn_open.setVisibility(View.VISIBLE);
    
    btn.setOnClickListener(v->
    
        userPojo user = new userPojo(edit_tipo.getText().toString(), edit_titulo.getText().toString(),edit_avance.getText().toString(),edit_plataforma.getText().toString());
        if(user_edit==null)
        
            dao.add(user).addOnSuccessListener(suc ->
            
                Toast.makeText(this, "Record is inserted", Toast.LENGTH_SHORT).show();
            ).addOnFailureListener(er ->
            
                Toast.makeText(this, "" + er.getMessage(), Toast.LENGTH_SHORT).show();
            );
        
        else
        
          
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("tipo", edit_tipo.getText().toString());
            hashMap.put("titulo", edit_titulo.getText().toString());
            hashMap.put("avance", edit_avance.getText().toString());
            hashMap.put("plataforma", edit_plataforma.getText().toString());
            dao.update(user_edit.getKey(), hashMap).addOnSuccessListener(suc ->
            
                Toast.makeText(this, "Record is updated", Toast.LENGTH_SHORT).show();
                finish();
            ).addOnFailureListener(er ->
            
                Toast.makeText(this, "" + er.getMessage(), Toast.LENGTH_SHORT).show();
            );
        
    );



    

类 DAOUserPojo

     public class DAOUserPojo 

private DatabaseReference databaseReference;
private FirebaseAuth userid;

public DAOUserPojo() 
    FirebaseDatabase db =FirebaseDatabase.getInstance("https://proyecto-daniel-sanchez-default-rtdb.europe-west1.firebasedatabase.app");
    databaseReference = db.getReference();
    userid = FirebaseAuth.getInstance();


   // userid=FirebaseAuth.getInstance().getCurrentUser();

public Task<Void> add(userPojo user)

    return databaseReference.child(userid.getUid()).push().setValue(user);


public Task<Void> update(String Key, HashMap<String ,Object> hashMap)

    return databaseReference.child(userid.getUid()).child(Key).updateChildren(hashMap);

public Task<Void> remove(String Key)

    return databaseReference.child(userid.getUid()).child(Key).removeValue();


public Query get(String Key)

    if(Key == null)
    
        return databaseReference.child(userid.getUid()).orderByKey().limitToFirst(8);
    
    return databaseReference.child(userid.getUid()).orderByKey().startAfter(Key).limitToFirst(8);


public Query get()

    return databaseReference;


这是我尝试更新时数据库的节点。它应该像第一个节点,但它会重复:firebase 对不起我的英语不好。如果有人可以提供帮助,那就太棒了,谢谢!

【问题讨论】:

【参考方案1】:

让我们开始上传新的:

我建议添加额外的 child 让名称为 id 例如,此子项的值将与 firebase 推送 id 的值相同。

让我们开始编辑吧:

为适配器传递一个(字符串)textId 变量,这样当您从菜单中单击编辑时,它会将 textId 值设置为来自 firebase 的推送 id,这将是具有您需要的数据的子项编辑。

现在使用child(textId).updateChildren(//Your hashmap);

它会起作用的。

我的用法示例:

String textId= productRef.child(UID).child("images").push().getKey();


HashMap<String ,Object> hashMap = new HashMap<>();
        hashMap.put("image", url);
        hashMap.put("id", textId);

 productRef.child(UID).child("images").child(textId).updateChildren(hashMap);

看起来像这样:

你有没有注意到 id 和 Child Name 一样

【讨论】:

我不明白所有,所以,我必须创建一个新的孩子,称为 id,所以我有我的用户,push,id,然后,我的数据或如何?。 我解决了,我只是添加了一个字符串,就像你所说的我保存密钥的位置,然后,在更新之前,我删除了该节点及其上的项目,然后,我更新,再次创建它有了新数据,谢谢 如果有效,请采纳答案 请采纳答案

以上是关于当我尝试从 firebase 更新数据时出错的主要内容,如果未能解决你的问题,请参考以下文章

将数据从 FireBase 检索到颤振项目时出错

连接值更改时 Firebase 数据未更新

尝试自我更新作曲家时出错

当我的颤振应用关闭时,如何更新我的 Firebase 数据?

更新 WAMP 后尝试访问数据库时出错

尝试使用 RETURNING 和更新/插入从 plpgsql 函数返回时出错