删除和更新在Android Studio中通过ID搜索的项目,使用Java和Firebase。

huangapple go评论71阅读模式
英文:

Delete and update an Item that has be searched by ID in android studio, Java and firebase

问题

以下是你提供的Java代码的中文翻译部分:

public class MainActivity extends AppCompatActivity {

    EditText txtID, txtName, txtAdd, txtConNo, txtid;
    Button btnSave, btnShow, btnUpdate, btnDelete;
    DatabaseReference dbRef;
    Student std;

    String searchID;

    private void clearControls() {
        txtID.setText("");
        txtName.setText("");
        txtAdd.setText("");
        txtConNo.setText("");
        txtid.setText("");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtID = findViewById(R.id.EtID);
        txtName = findViewById(R.id.EtName);
        txtAdd = findViewById(R.id.EtAddress);
        txtConNo = findViewById(R.id.EtConNo);
        txtid = findViewById(R.id.search);

        btnSave = findViewById(R.id.BtnSave);
        btnShow = findViewById(R.id.BtnShow);
        btnUpdate = findViewById(R.id.BtnUpdate);
        btnDelete = findViewById(R.id.BtnDelete);

        std = new Student();
    }

    protected void onResume() {
        super.onResume();

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ...(略去了部分内容)
            }
        });

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ...(略去了部分内容)
            }
        });

        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ...(略去了部分内容)
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ...(略去了部分内容)
            }
        });
    }
}

如果你还需要关于代码的其他部分的翻译或帮助,请随时告诉我。

英文:

I implemented code in Java to retrieve data from the Firebase database by searching with an ID and show it in the form. If I add the id it will show the data correctly.

Successfully retrieved data
删除和更新在Android Studio中通过ID搜索的项目,使用Java和Firebase。

Data in firebase
删除和更新在Android Studio中通过ID搜索的项目,使用Java和Firebase。

But when I try to delete or update this data it is always showing as "No data resource". I tried to implement code but it is not working. How can I delete and update a specific data( Searched by ID),

The whole code I have tried..

public class MainActivity extends AppCompatActivity {
EditText txtID,txtName,txtAdd,txtConNo,txtid;
Button btnSave,btnShow,btnUpdate,btnDelete;
DatabaseReference dbRef;
Student std;
String searchID;
private void clearControls(){
txtID.setText("");
txtName.setText("");
txtAdd.setText("");
txtConNo.setText("");
txtid.setText("");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtID = findViewById(R.id.EtID);
txtName = findViewById(R.id.EtName);
txtAdd = findViewById(R.id.EtAddress);
txtConNo = findViewById(R.id.EtConNo);
txtid = findViewById(R.id.search);
btnSave = findViewById(R.id.BtnSave);
btnShow = findViewById(R.id.BtnShow);
btnUpdate = findViewById(R.id.BtnUpdate);
btnDelete = findViewById(R.id.BtnDelete);
std = new Student();
}
protected void onResume(){
super.onResume();
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dbRef = FirebaseDatabase.getInstance().getReference().child("Student");
try{
if(TextUtils.isEmpty(txtID.getText().toString()))
Toast.makeText(getApplicationContext(),"Please enter an ID",Toast.LENGTH_SHORT).show();
else if(TextUtils.isEmpty(txtName.getText().toString()))
Toast.makeText(getApplicationContext(),"Please enter a Name",Toast.LENGTH_SHORT).show();
else if (TextUtils.isEmpty(txtAdd.getText().toString()))
Toast.makeText(getApplicationContext(),"Please enter an Address",Toast.LENGTH_SHORT).show();
else {
std.setID(txtID.getText().toString().trim());
std.setName(txtName.getText().toString().trim());
std.setAddress(txtAdd.getText().toString().trim());
std.setConNo(txtConNo.getText().toString().trim());
dbRef.push().setValue(std);
Toast.makeText(getApplicationContext(),"Data Saved Successfully",Toast.LENGTH_SHORT).show();
clearControls();
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(),"Invalid Contact Number",Toast.LENGTH_SHORT).show();
}
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchID = txtid.getText().toString().trim();
DatabaseReference readRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference dref = readRef.child("Student");
Query query = dref.orderByChild("id").equalTo(searchID);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
txtID.setText((ds.child("id").getValue().toString()));
txtName.setText((ds.child("name").getValue().toString()));
txtAdd.setText((ds.child("address").getValue().toString()));
txtConNo.setText((ds.child("conNo").getValue().toString()));
}
}
else
Toast.makeText(getApplicationContext(),"No Source to Display",Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
});
}
});
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatabaseReference updf = FirebaseDatabase.getInstance().getReference().child("Student");
updf.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild("Student")){
try{
std.setID(txtID.getText().toString().trim());
std.setName(txtName.getText().toString().trim());
std.setAddress(txtAdd.getText().toString().trim());
std.setConNo(txtConNo.getText().toString().trim());
dbRef = FirebaseDatabase.getInstance().getReference().child("Student");
dbRef.setValue(std);
clearControls();
Toast.makeText(getApplicationContext(),"Data updated successfully",Toast.LENGTH_SHORT).show();
}catch(NumberFormatException e){
Toast.makeText(getApplicationContext(),"Invalid data",Toast.LENGTH_SHORT).show();
}
}else
Toast.makeText(getApplicationContext(),"Nothing to show",Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage());
}
});
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatabaseReference deldf = FirebaseDatabase.getInstance().getReference().child("Student");
deldf.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild("Student")){
dbRef = FirebaseDatabase.getInstance().getReference().child("Student");
dbRef.removeValue();
clearControls();
Toast.makeText(getApplicationContext(),"Data Deleted successfully",Toast.LENGTH_SHORT).show();
}else
Toast.makeText(getApplicationContext(),"Nothing to show",Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage());
}
});
}
});
}
}

答案1

得分: 1

要删除具有 ID001 的元素,请使用以下代码行:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentRef = rootRef.child("Student");
Query queryById = studentRef.orderByChild("id").equalTo(idToBeRemoved);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            ds.getRef().removeValue();
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); // 不要忽略潜在的错误!
    }
};
studentRef.addListenerForSingleValueEvent(valueEventListener);

上述代码的结果将是删除具有 ID001 的元素。如果您需要更新相同的元素,只需使用 updateChildren()

英文:

To remove the element with ID001, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studentRef = rootRef.child("Student");
Query queryById = studentRef.orderByChild("id").equalTo(idToBeRemoved);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ds.getRef().removeValue();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
studentRef.addListenerForSingleValueEvent(valueEventListener);

The result of the above code will be the deletion of the element with ID001. If you need to update the same element, simply use updateChildren().

huangapple
  • 本文由 发表于 2020年9月23日 23:42:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/64031599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定