简体   繁体   English

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

[英]Error when i try to update data from firebase

i want to update some data from firebase using my app, but when i submit it, the data only gets duplicated, not changed, and don't know why.我想使用我的应用程序从 firebase 更新一些数据,但是当我提交它时,数据只会重复,没有改变,也不知道为什么。 I put my code below:我把我的代码放在下面:

My class userPojo我的 class 用户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;
}

} }

Class Adapter: Class 适配器:

 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();
}
}

Class Archivos: Class 档案:

   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();
            });
        }
    });


}
    }

class DAOUserPojo class 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;
}
}

And this is the nodes of my database when i try to update.这是我尝试更新时数据库的节点。 It should be like first node, but it get duplicate: firebase Sry for my bad english.它应该像第一个节点,但它会重复: firebase 对不起,我的英语不好。 If someone can help, would be amazing, Thanks!如果有人可以提供帮助,那就太棒了,谢谢!

let's start with uploading New:让我们从上传新的开始:

I would suggest adding aditional child lets name is id for example and the value of this child would be same as the value of firebase push id.例如,我建议添加额外的child让名称为id ,这个孩子的值将与 firebase 推送 id 的值相同。

let's get with Editing:让我们开始编辑:

pass a (String) textId variable for adapter so that when you click on edit from the menu it would set the textId value to be the push id from the firebase, which would be the child that have data you need to edit.为适配器传递一个(字符串) textId变量,这样当您从菜单中单击编辑时,它会将 textId 值设置为来自 firebase 的推送 id,这将是具有您需要编辑的数据的子节点。

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

and it would work.它会起作用的。

Example of my usage:我的用法示例:

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);

It would look like this:它看起来像这样: 火力基地

have you notice the id is the same as the Child Name你有没有注意到 id 和 Child Name 一样

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试将数据从Firebase数据库添加到firebaseViewHolder时,Android App不断停止 - Android App keeps stopping when i try to add data from firebase database to a firebaseViewHolder 当我尝试从git更新项目时,我收到此错误:无法保存未提交的更改 - When I try to update project from git I get this error: Couldn't save uncommitted changes 当我尝试在子表中插入多个数据时发生错误无法执行JDBC批更新 - When I try to insert multiple data into child table then error occurs Could not execute JDBC batch update 当我尝试用数据填充表时出现错误 - error when I try to fill table with data 当我尝试mvn appengine时发生409冲突错误:更新 - 409 conflict error when i try mvn appengine:update 为什么我在尝试读取 excel 文件时收到数据提供程序不匹配错误? - Why I am getting Data Provider MisMatch error when I try to read from excel file? 当我尝试将数据从sqlite传递到新活动时遇到错误,抛出recyclerview(Android) - Getting an error when i try to pass data from sqlite to new activity throw recyclerview (Android) 当我尝试从数据库Derby DB中选择数据时出现奇怪的错误 - Strange error when I try to select data from database Derby DB 尝试显示来自 Firebase 的数据,但没有显示 - Try to display data from Firebase but nothing displays 为什么当我尝试将一些数据发布到 firebase 数据库时,网络不可用,正在休眠? - Why I'm getting network unavailable, sleeping when I try to post some data to a firebase database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM