TheLegandOf9gag
TheLegandOf9gag

Reputation: 41

issues connecting with the firebase database (app keeps crashing whenever i attempt to save to the database)

so i am making a diary application where users log in and then start writing on a diary app that anyone who has the application can access , the application was working fine but after integrating a second layout (the login layout) and the firebase authentication, the application crashes whenever i try to save or view anything from the database. moreover nothing seems to be saved in the database

the second issue is that i would like the userId under which the notes will be saved to be the email the user entered when signing up not the key that firebase can generate

I have tried checking both build gradles and they seem to be working just fine, i also tried just setting the user ID to be 123 to make sure it isn't null i also tried different versions of android to test it but nothing seems to be working

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

            }

        }
    });

and below the the class that has the diaryclass constructor

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;
}
}

this is what the data base looked like before when it worked the firebase view of the data saved

please feel free to ask any questions as i would appreciate any kind of help below is a link to the entire project if that would help click here for the android studio project in zip format

for those intrested in the entire code

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


    }

and this is the part that the user uses to save and view the diary

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


                }
            });


        }
    });
}
}

and the gradle is working just fine so i dont think it is needed and the other class is already available up there

logcat below

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

Upvotes: 0

Views: 849

Answers (2)

Reymand
Reymand

Reputation: 61

Sorry but symbols like @ cannot be use as a name for a firebase database path that's why they generate unique key.

Upvotes: 0

Husnain Qasim
Husnain Qasim

Reputation: 199

I did not download your complete code but try to save data on firebase like this First change DatabaseReference mDatabase = database.getReference("diary"); if diary is the direct child of your database to DatabaseReference mDatabase = database.getReference().child("diary"); 2nd you have to get the id of the current user for that

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

3rd to save data on Firebase DataBase make sure current user is loged in

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

4th be sure in your diaryclass make GETTER and SETTER for all your variabels.

Upvotes: 1

Related Questions