我正在使用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. exist”;如果不存在,则成功在数据库中创建子项,但它仍然显示Toast消息“Reg No. exist”,而不是“Upload successful”。由于我对这些概念比较新,如果您知道任何信息,请帮忙解决。
数据库节点: https://istack.dev59.com/Szoyt.webp
DocumentReference
上使用get
而不是addValueEventListener
。 - Hussain