与Firebase数据库相关的问题(每当我尝试保存到数据库时,应用程序都会崩溃)

时间:2019-04-14 21:09:48

标签: java android firebase firebase-realtime-database

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

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

我尝试检查两个构建等级,它们似乎都正常工作,我还尝试将用户ID设置为123,以确保它不为null 我还尝试了不同版本的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 /存储:getDiskStats失败,结果为NOT_SUPPORTED,大小为0

     

2019-04-15 04:00:57.777 1869-1869 /? E / netmgr:无法打开QEMU管道'qemud:network':参数无效

     

2019-04-15 04:00:57.777 1869-1869 /? E / netmgr:WifiForwarder无法打开QEMU管道:无效的参数

     

2019-04-15 04:01:00.007 1926-1940 /? E / memtrack:无法加载memtrack模块

     

2019-04-15 04:01:00.032 1926-1940 /? E / memtrack:无法加载memtrack模块

     

2019-04-15 04:01:00.049 1926-1940 /? E / memtrack:无法加载memtrack模块

     

2019-04-15 04:01:01.687 1778-1803 /? E /存储:getDiskStats失败,结果为NOT_SUPPORTED,大小为0

2 个答案:

答案 0 :(得分:1)

我没有下载完整的代码,但尝试将数据保存在Firebase中,如下所示 如果日记是数据库的直接子级,请首先将DatabaseReference mDatabase = database.getReference("diary");更改为DatabaseReference mDatabase = database.getReference().child("diary"); 第二,您必须为此获取当前用户的ID

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

第3次将数据保存在Firebase DataBase上,请确保当前用户已登录

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

第四,确保在diaryclassGETTER中分别放置所有变量。

答案 1 :(得分:0)

对不起,但是@之类的符号不能用作firebase数据库路径的名称,这就是它们生成唯一密钥的原因。