gpt4 book ai didi

java - 与 firebase 数据库连接的问题(每当我尝试保存到数据库时,应用程序都会崩溃)

转载 作者:行者123 更新时间:2023-12-02 10:00:21 25 4
gpt4 key购买 nike

所以我正在制作一个日记应用程序,用户登录然后开始在任何拥有该应用程序的人都可以访问的日记应用程序上书写,该应用程序运行良好,但在集成了第二个布局(登录布局)和 firebase 之后身份验证,每当我尝试保存或查看数据库中的任何内容时,应用程序都会崩溃。而且数据库中似乎没有保存任何内容

第二个问题是我希望保存注释的 userId 是用户注册时输入的电子邮件,而不是 firebase 可以生成的 key

我尝试检查两个构建 gradle,它们似乎工作得很好,我还尝试将用户 ID 设置为 123 以确保它不为空我还尝试了不同版本的 android 来测试它,但似乎没有任何效果

 FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = database.getReference("diary");






saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


String diaryTitle = titleText.getText().toString();
String diaryContent = diaryText.getText().toString();
if(diaryTitle.length()==0||diaryContent.length()==0)

{
Toast.makeText(getApplication().getBaseContext(), "FIELD(S) CANNOT BE EMPTY", Toast.LENGTH_SHORT).show();

}
else {
String userId = "123";
diaryclass userDiary = new diaryclass(diaryTitle, diaryContent);
mDatabase.child(userId).setValue(userDiary);
titleText.setText("");
diaryText.setText("");
Toast.makeText(getApplication().getBaseContext(), "text saved", Toast.LENGTH_SHORT).show();

}

}
});

以及具有 diaryclass 构造函数的类下方

public class diaryclass extends diary{

public String Title;
public String Diary;

public diaryclass(){

}

public diaryclass(String Title,String Diary){
this.Title=Title;
this.Diary=Diary;
}
}

这是数据库以前工作时的样子 the firebase view of the data saved

请随时提出任何问题,我将不胜感激任何形式的帮助如果有帮助的话,下面是整个项目的链接 click here for the android studio project in zip format

对于那些对整个代码感兴趣的人

package ir.mhkz.loginandsignup;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {


EditText password, reg_password,
reg_email, reg_confirmemail;
Button login, signUp, reg_register;
TextInputLayout txtInLayoutUsername, txtInLayoutPassword, txtInLayoutRegPassword;
CheckBox rememberMe;
private FirebaseAuth mAuth;

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

reg_email = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
signUp = findViewById(R.id.signUp);
txtInLayoutUsername = findViewById(R.id.txtInLayoutUsername);
txtInLayoutPassword = findViewById(R.id.txtInLayoutPassword);
rememberMe = findViewById(R.id.rememberMe);
mAuth = FirebaseAuth.getInstance();


ClickLogin();


//SignUp's Button for showing registration page
signUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ClickSignUp();
}
});


}

//This is method for doing operation of check login
private void ClickLogin() {

login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if (reg_email.getText().toString().trim().isEmpty()) {

Snackbar snackbar = Snackbar.make(view, "Please fill out these fields",
Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(getResources().getColor(R.color.red));
snackbar.show();
txtInLayoutUsername.setError("Username should not be empty");
} else {
//Here you can write the codes for checking username
}
if (password.getText().toString().trim().isEmpty()) {
Snackbar snackbar = Snackbar.make(view, "Please fill out these fields",
Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(getResources().getColor(R.color.red));
snackbar.show();
txtInLayoutPassword.setError("Password should not be empty");
} else {
//Here you can write the codes for checking password
}

if (rememberMe.isChecked()) {
//Here you can write the codes if box is checked
} else {
//Here you can write the codes if box is not checked
}

mAuth.signInWithEmailAndPassword(reg_email.getText().toString(),password.getText().toString());

}

});

}

//The method for opening the registration page and another processes or checks for registering
private void ClickSignUp() {
final Intent intent;
intent = new Intent(this,diary.class);


AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.register, null);
dialog.setView(dialogView);

reg_password = dialogView.findViewById(R.id.reg_password);
reg_email = dialogView.findViewById(R.id.reg_email);
reg_confirmemail = dialogView.findViewById(R.id.reg_confirmemail);
reg_register = dialogView.findViewById(R.id.reg_register);
txtInLayoutRegPassword = dialogView.findViewById(R.id.txtInLayoutRegPassword);

reg_register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

if (reg_password.getText().toString().trim().isEmpty()) {
txtInLayoutRegPassword.setPasswordVisibilityToggleEnabled(false);
reg_password.setError("Please fill out this field");
} else {
txtInLayoutRegPassword.setPasswordVisibilityToggleEnabled(true);
startActivity(intent);
}
if (reg_email.getText().toString().trim().isEmpty()) {

reg_email.setError("Please fill out this field");
} else {
//Here you can write the codes for checking email
}
if (reg_confirmemail.getText().toString().trim().isEmpty()) {

reg_confirmemail.setError("Please fill out this field");
} else {
//Here you can write the codes for checking confirmemail
}
mAuth.createUserWithEmailAndPassword(reg_email.getText().toString(),reg_password.getText().toString());

}
});
dialog.show();
}


}

这是用户用来保存和查看日记的部分

package ir.mhkz.loginandsignup;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.solver.widgets.Snapshot;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
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.ArrayList;
import java.util.List;

public class diary extends MainActivity {
EditText titleText;
EditText diaryText;
Button saveBtn;
Button viewdata;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = database.getReference().child("diary");
TextView dtitle;
TextView ddiary;
Button clear;
@Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.diary_layout);
titleText=findViewById(R.id.editTextTitle);
diaryText=findViewById(R.id.editTextDiary);
saveBtn = findViewById(R.id.buttonSaveDiary);
viewdata= findViewById(R.id.viewbutton);
dtitle = findViewById(R.id.displaytitle);
ddiary = findViewById(R.id.displaydiary);
clear = findViewById(R.id.buttoncln);
dtitle.setMovementMethod(new ScrollingMovementMethod());
ddiary.setMovementMethod(new ScrollingMovementMethod());

final FirebaseAuth mAuth = null;
final String userId;
if (mAuth.getCurrentUser() != null){
userId = mAuth.getCurrentUser().getUid();
}

viewdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dtitle.setText("");
ddiary.setText("");
Toast.makeText(getApplication().getBaseContext(), "text updated", Toast.LENGTH_SHORT).show();
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<diaryclass> DiaryList = new ArrayList<diaryclass>();
dtitle.setText("");
ddiary.setText("");

for (DataSnapshot diarySnapshot: dataSnapshot.getChildren()) {
diaryclass thediary = diarySnapshot.getValue(diaryclass.class);
DiaryList.add(thediary);
}
for (int i=0 ; i<DiaryList.size();i++) {
diaryclass listofstuff = DiaryList.get(i);
String titlelist=listofstuff.Title;
String diarylist = listofstuff.Diary;
dtitle.append(i+ "\n" ) ;
dtitle.append(titlelist + "\n" ) ;
dtitle.append("\n" ) ;
dtitle.append("\n" ) ;
dtitle.append(diarylist + "\n" ) ;
dtitle.append("\n" ) ;

}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}

});

}

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


String diaryTitle = titleText.getText().toString();
String diaryContent = diaryText.getText().toString();
if (mAuth.getCurrentUser() != null) {
mDatabase.child(userId).setValue(diaryTitle, diaryContent)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplication().getBaseContext(), "Saved...", Toast.LENGTH_SHORT).show();
titleText.setText("");
diaryText.setText("");
}
}
});
}

clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

titleText.setText("");
diaryText.setText("");
dtitle.setText("");
ddiary.setText("");
Toast.makeText(getApplication().getBaseContext(), "text cleared ", Toast.LENGTH_SHORT).show();


}
});


}
});
}
}

并且 gradle 工作得很好,所以我认为不需要它,并且另一个类已经在那里可用

下面的logcat

2019-04-15 04:00:01.684 1778-1803/? E/storaged: getDiskStats failed with result NOT_SUPPORTED and size 0

2019-04-15 04:00:57.777 1869-1869/? E/netmgr: Failed to open QEMU pipe 'qemud:network': Invalid argument

2019-04-15 04:00:57.777 1869-1869/? E/netmgr: WifiForwarder unable to open QEMU pipe: Invalid argument

2019-04-15 04:01:00.007 1926-1940/? E/memtrack: Couldn't load memtrack module

2019-04-15 04:01:00.032 1926-1940/? E/memtrack: Couldn't load memtrack module

2019-04-15 04:01:00.049 1926-1940/? E/memtrack: Couldn't load memtrack module

2019-04-15 04:01:01.687 1778-1803/? E/storaged: getDiskStats failed with result NOT_SUPPORTED and size 0

最佳答案

我没有下载您的完整代码,但尝试像这样在 firebase 上保存数据首先将 DatabaseReference mDatabase = database.getReference("diary"); 如果 diary 是数据库的直接子级更改为 DatabaseReference mDatabase = database.getReference().child("diary"); 第二,你必须获取当前用户的 id

FirebaseAuth mAuth;
String userId;
if (mAuth.getCurrentUser() != null){
userId = mAuth.getCurrentUser().getUid();
}

第三步在 Firebase 数据库上保存数据,确保当前用户已登录

if (mAuth.getCurrentUser() != null){
mDatabase.child(userId).setValue(userDiary)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Toast.makeText(getActivity(),"Saved...",Toast.LENGTH_SHORT).show();
titleText.setText("");
diaryText.setText("");
}
});
}

第四,请确保在您的 diaryclass 中为所有变量创建 GETTERSETTER

关于java - 与 firebase 数据库连接的问题(每当我尝试保存到数据库时,应用程序都会崩溃),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680054/

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