gpt4 book ai didi

java - 检查 Firebase 数据库中是否存在特定值

转载 作者:行者123 更新时间:2023-12-01 13:09:58 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Checking if a particular value exists in the Firebase database

(6 个回答)


2年前关闭。




我正在使用 java 和 Firebase 开发一个 android 应用程序。这是我用于创建用户配置文件并将数据存储在 firebase 数据库中的代码。

package com.eNotification.getnotify;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.eNotification.getnotify.utils.Utils;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
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 com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;
import com.mikhaellopez.circularimageview.CircularImageView;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.util.ArrayList;
import java.util.List;

public class MainActivityCreateProfile extends AppCompatActivity {

private static final int STORAGE_PERMISSION_CODE=1;

private TextInputLayout dUsername,dRegNo;
private TextInputEditText dEditUsername,dEditRegNo;
private CircularImageView dProfileImage;
private Spinner dCourse;
private TextView selected;
private Button dDoneBtn;

private String uid,email;
private String select="Select course",maxid,s;
private Uri selectedImage=null,uri;

private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private StorageReference storageReference;
private FirebaseStorage firebaseStorage;

private StorageTask mUploadTask;

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

firebaseDatabase = FirebaseDatabase.getInstance();
firebaseStorage = FirebaseStorage.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("USERS");
storageReference = firebaseStorage.getReference("Profile images");

uid = getIntent().getStringExtra("uid");
email = getIntent().getStringExtra("email");

dProfileImage = findViewById(R.id.dProfileImg);
dUsername = findViewById(R.id.dUsername);
dRegNo = findViewById(R.id.dRegNo);
dEditUsername = findViewById(R.id.dEditUsername);
dEditRegNo = findViewById(R.id.dEditReg);
selected = findViewById(R.id.course);
dCourse = findViewById(R.id.dCourse);

List<String> categories = new ArrayList<>();
categories.add(0,"Select course");
categories.add("BCA");
categories.add("BBA");
categories.add("BCOM");
categories.add("BA");

ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,categories);

dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dCourse.setAdapter(dataAdapter);
dCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// if (parent.getItemAtPosition(position).equals("Select course")){
// Toast.makeText(MainActivityCreateProfile.this, "Select the course", Toast.LENGTH_SHORT).show();
//} else {
selected.setText(parent.getSelectedItem().toString());
//}
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivityCreateProfile.this, "Select a course", Toast.LENGTH_SHORT).show();
}
});

dDoneBtn = findViewById(R.id.dDoneBtn);

dDoneBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
inputValidation();
}
});

dProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivityCreateProfile.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivityCreateProfile.this, "You have already granted permission", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
requestStoragePermission();
}
}
});
}

private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivityCreateProfile.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This Permission is needed for uploading the Image")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivityCreateProfile.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
SelectImage();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();

}
}
}

public void SelectImage() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
selectedImage = result.getUri();
Picasso.get().load(selectedImage).into(dProfileImage);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}

private void inputValidation() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
//Username validation
if (!Utils.inputValidation(dEditUsername)) {
Toast.makeText(this, "Enter the username", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.usernameVerify(dEditUsername)) {
Toast.makeText(this, "A Username should not exceed 15 characters", Toast.LENGTH_SHORT).show();
return;
} else {
dUsername.setErrorEnabled(false);
}

//Reg no Validation
if (!Utils.inputValidation(dEditRegNo)) {
Toast.makeText(this, "Enter the Register No", Toast.LENGTH_SHORT).show();
return;
} else if (!Utils.regNoVerify(dEditRegNo)) {
Toast.makeText(this, "Enter correct Register No", Toast.LENGTH_SHORT).show();
return;
}
createProfile();
}else {
Toast.makeText(this, "Check internet connection", Toast.LENGTH_SHORT).show();
}
}

public String GetFileExtension(Uri uri) {

ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri)) ;

}

private void createProfile(){
final String username = dEditUsername.getText().toString();
final String regNo = dEditRegNo.getText().toString();
final String course = dCourse.getSelectedItem().toString();
maxid = databaseReference.push().getKey();

if (!TextUtils.isEmpty(username) && (!TextUtils.isEmpty(regNo))) {
if (!course.equals(select)) {
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}


@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Select a course", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Enter username and Register No.", Toast.LENGTH_SHORT).show();
}
}
}


我遇到了一个问题,我想检查数据库中是否已经存在注册号
这是检查的代码。
databaseReference.orderByChild("regNo").equalTo(regNo).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

if (dataSnapshot.exists()){
Toast.makeText(MainActivityCreateProfile.this, "Reg no. exist", Toast.LENGTH_SHORT).show();
} else {
s = "https://firebasestorage.googleapis.com/v0/b/getnotify-da5c1.appspot.com/o/Permanent%2Fuser.png?alt=media&token=017d9013-ede2-49c7-b53b-6e96d90e3398";
UserDetails userDetails = new UserDetails(s, username, regNo, course, email);
databaseReference.child(maxid).setValue(userDetails);
Toast.makeText(MainActivityCreateProfile.this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
}


@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityCreateProfile.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});


代码正常工作。它检测数据库中是否存在该值并显示 Toast 消息 Reg No. 存在。如果该值不存在,它会成功在数据库中创建子项,但它也会显示 Toast 消息 Reg No. 存在而不是上传成功。我对这些概念很陌生,所以如果您知道任何事情,请提供帮助。

Database node

最佳答案

根据侯赛因的回答。 addValueEventListener()每次您的数据库发生更改时都会调用以克服这种情况,您可以调用 addListenerForSingleValueEvent() .哪个会调用一次。

除此之外,实时数据库中没有 Get 选项

databaseReference.orderByChild("regNo").equalTo(regNo)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do what you want to try
}else{
//Create New Node in Database
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

关于java - 检查 Firebase 数据库中是否存在特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61284939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com