-1

I am working on my Android Studio project. What I want to do, is go to the id of the member, then get their name. I will attach my Firebase database picture.

I am not sure what to do. I want to sign in, then go to MenuActivity.java. When I do sign in, it crashes when going to MenuActivity.java The reason I want to get the name from the database is because on the top of the MenuActivity.java, I want it to say "Hello, name!". So I need the name for the individual that is signed in.

I have checked everything. Everything seems confusing and I am currently getting this error.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.cis436.ewalletprototype, PID: 10053
    java.lang.NullPointerException: **Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()'** on a null object reference
        at com.cis436.ewalletprototype.MenuActivity$1.onDataChange(MenuActivity.java:66)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@18.0.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@18.0.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@18.0.1:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I/Process: Sending signal. PID: 10053 SIG: 9
Application terminated.

Here is signInActivity.java

package com.cis436.ewalletprototype;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
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.AuthResult;
import com.google.firebase.auth.FirebaseAuth;




public class signInActivity extends AppCompatActivity {


    int RC_SIGN_IN = 0;


    Button btnSignIn;
    Button btnSignUp;
    Button btnSignInGoogle;
    Button btnSignInFacebook;

    EditText txtEmailInput;
    EditText txtPasswordInput;

    TextView btnForgotPassword;


    private FirebaseAuth mAuth;



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

        btnSignIn = findViewById(R.id.btnSignIn);
        btnSignUp = findViewById(R.id.sign_up);
        btnSignInGoogle = findViewById(R.id.sign_in_google);
        btnSignInFacebook = findViewById(R.id.sign_in_facebook);
        txtEmailInput = findViewById(R.id.txtEmail);
        txtPasswordInput = findViewById(R.id.txtPassword);
        btnForgotPassword = findViewById(R.id.txtForgotPassword);



        mAuth = FirebaseAuth.getInstance();


        //if (mAuth.getCurrentUser() != null) {
        //    startActivity(new Intent(signInActivity.this, MenuActivity.class));
         //   finish();
        //}
        btnSignUp.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(signInActivity.this, signUpActivity.class));
                    }
                });

        //Click Listeners for buttons
        btnSignIn.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent signUpP2 = new Intent(signInActivity.this,MenuActivity.class);
                        finish();
                        startActivity(signUpP2);
                    }
                });

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

                        String email = txtEmailInput.getText().toString();
                        final String password = txtPasswordInput.getText().toString();

                        if (TextUtils.isEmpty(email)) {
                            Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (TextUtils.isEmpty(password)) {
                            Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        //authenticate user
                        mAuth.signInWithEmailAndPassword(email, password)
                                .addOnCompleteListener(signInActivity.this,
                                        new OnCompleteListener<AuthResult>() {
                                            @Override
                                            public void onComplete(@NonNull Task<AuthResult> task) {
                                                // If sign in fails, display a message to the user. If sign in succeeds
                                                // the auth state listener will be notified and logic to handle the
                                                // signed in user can be handled in the listener.

                                                if (!task.isSuccessful())
                                                {
                                                    // there was an error
                                                    if (password.length() < 6)
                                                    {
                                                        Toast.makeText(signInActivity.this, "Password must be at least 6 characters", Toast.LENGTH_SHORT).show();
                                                        txtPasswordInput.setError(getString(R.string.minimum_password));
                                                    }
                                                    else
                                                    {
                                                        Toast.makeText(signInActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
                                                    }
                                                }
                                                else
                                                {
                                                    if(mAuth.getCurrentUser().isEmailVerified())
                                                    {

                                                        Toast.makeText(signInActivity.this, "Registered successfully. Please check your email for verification", Toast.LENGTH_SHORT).show();
                                                        Intent intent = new Intent(signInActivity.this, MenuActivity.class);
                                                        startActivity(intent);
                                                        finish();
                                                    }

                                                }
                                            }
                                        });
                    }
                });
    }

}

Here is MenuActivity.java

package com.cis436.ewalletprototype;

import android.app.Activity;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseUser;
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.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;

import java.util.ArrayList;

public class MenuActivity extends Activity {
    private static final String TAG = "ViewDatabase";

    private DrawerLayout drawer;
    private TextView txtWelcomeName;
    String mName,mID;
    Member member;
    long maxid = 0;
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;
    private  String userID;



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

        txtWelcomeName = findViewById(R.id.tb_welcomeMessage);

        //declare the database reference object. This is what we use to access the database.
        //NOTE: Unless you are signed in, this will not be useable.
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();

        FirebaseUser user = mAuth.getCurrentUser();
        userID = user.getUid();


        myRef = FirebaseDatabase.getInstance().getReference().child("Member").child(userID);
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String name = dataSnapshot.child("name").getValue().toString();

                txtWelcomeName.setText(name);
            }

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

            }
        });




        //Bottom Navigation
        BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bottom_bar);
        bottomNavigationViewEx.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.hamburgerAction:
                        drawer.openDrawer(GravityCompat.START);
                        break;

                    case R.id.reportAction:
                        Intent report = new Intent(MenuActivity.this, ContactActivity.class);
                        startActivity(report);
                        break;

                    case R.id.notificationsAction:
                        Intent notifications = new Intent(MenuActivity.this, NotificationsActivity.class);
                        startActivity(notifications);
                        break;

                    case R.id.settingsAction:
                        Intent settings = new Intent(MenuActivity.this, SettingsActivity.class);
                        startActivity(settings);
                        break;
                }
                return true;
            }
        });

        //Drawer Navigation
        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch(menuItem.getItemId()) {
                    case R.id.dm_profile:
                        Intent profile = new Intent(MenuActivity.this, ProfileActivity.class);
                        drawer.closeDrawer(GravityCompat.START);
                        startActivity(profile);
                        break;

                    case R.id.dm_settings:
                        Intent settings = new Intent(MenuActivity.this, ContactActivity.class);
                        drawer.closeDrawer(GravityCompat.START);
                        startActivity(settings);
                        break;


                    case R.id.dm_help:
                        Intent help = new Intent(MenuActivity.this, HelpActivity.class);
                        drawer.closeDrawer(GravityCompat.START);
                        startActivity(help);
                        break;

                    case R.id.dm_logout:

                        //Logout of account
                        break;
                }

                return true;
            }
        });

        //Main Menu Buttons
        Button btnMakePayment = findViewById(R.id.btnMakePayment);
        Button btnSendMoney = findViewById(R.id.btnSendMoney);
        Button btnContact = findViewById(R.id.btnReport);
        Button btnSettings = findViewById(R.id.btnSettings);
        Button btnCalendar = findViewById(R.id.btnCalendar);

        btnMakePayment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent makePayment = new Intent(MenuActivity.this, MakePaymentActivity.class);
                startActivity(makePayment);
            }
        });



        btnContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent contact = new Intent(MenuActivity.this, ContactActivity.class);
                startActivity(contact);
            }
        });

        btnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent settings = new Intent(MenuActivity.this, SettingsActivity.class);
                startActivity(settings);
            }
        });

        btnCalendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent calendar = new Intent(MenuActivity.this, CalendarActivity.class);
                startActivity(calendar);
            }
        });
/////////////////////////////////////////////////////////////////////////////////////////////////////////
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    toastMessage("Successfully signed in with: " + user.getEmail());
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                    toastMessage("Successfully signed out.");
                }
                // ...
            }
        };

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                showData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        txtWelcomeName.setText(mName);
    }
////////////////////////////////
    /////////////////////////////////////
    private void showData(DataSnapshot dataSnapshot) {

            Member member = dataSnapshot.getValue(Member.class);
            mName = member.getName();
            txtWelcomeName.setText(mName);
            //display all the information
            //Log.d(TAG, "showData: name: " + member.getName());
            //txtWelcomeName.setText(member.getName());

            ArrayList<String> array  = new ArrayList<>();
            array.add(member.getName());
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    private void toastMessage(String message){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

Here is my Member.class

package com.cis436.ewalletprototype;

public class Member {

    private String name="";
    private String email="";
    private String date="";
    private String homeAddress="";
    private String country="";
    private String companyName="";
    private String companyAddress="";
    private String zipcode="";
    private String memberId="";
    private String paypalEmail="";


    public Member()
    {

    }

    public Member(String memberId, String email, String date, String homeAddress, String country, String companyName, String companyAddress, String zipcode, String paypalEmail, String name)
    {
        this.memberId = memberId;
        this.email = email;
        this.name = name;
        this.date = date;
        this.homeAddress = homeAddress;
        this.country = country;
        this.companyName = companyName;
        this.companyAddress = companyAddress;
        this.zipcode = zipcode;
        this.paypalEmail = paypalEmail;
    }

    public String getMemberId() { return memberId; }
    public void setMemberId(String memberId) { this.memberId = memberId; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    public String getDate() { return date; }
    public void setDate(String date) { this.date = date; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getHomeAddress() { return homeAddress; }
    public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; }

    public String getCountry() { return country; }
    public void setCountry(String country) { this.email = country; }

    public String getCompanyName() { return companyName; }
    public void setCompanyName(String companyName) { this.companyName = companyName; }

    public String getCompanyAddress() { return companyAddress; }
    public void setCompanyAddress(String companyAddress) { this.companyAddress = companyAddress; }

    public String  getZipcode() { return zipcode; }
    public void setZipcode(String zipcode) { this.zipcode = zipcode; }

    public String getPaypalEmail() { return paypalEmail; }
    public void setPaypalEmail(String paypalEmail) { this.paypalEmail = paypalEmail; }

}

Here is the picture of my current database:

My Database Picture

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • I understand you are a beginner but this question could have been avoided If you had red the documentation. The document name given automatically to documents you add to firebase are just random strings and this has nothing to do with the actual User ID of the currently logged-in user. I suggest you rename all the user related documents now so that you don't have to deal with them in the future. – Rohit Aug 04 '19 at 10:10
  • @Rohit Could you please give me the exact document to read so I could check it out? – Ibrahim Munaser Aug 04 '19 at 20:43
  • https://firebase.google.com/docs/firestore/manage-data/add-data – Rohit Aug 10 '19 at 14:05

3 Answers3

1

When using the following lines of code:

FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();

The getUid() method will return the id of the authenticated user. When passing that userID to following line:

myRef = FirebaseDatabase.getInstance().getReference().child("Member").child(userID);

It means that you are setting the reference to the user object that has its key the uid that it comes from the authentication process. As I see in your database, the key of the user is not the one above is a random key generated by the push() method, see it is starting with - (minus) sign.

To solve this, you either change that pushed key with the actual user id, which is the recommend solution and which also means that you need to add the user object again to the database or you can use the following query:

Query query = myRef = FirebaseDatabase.getInstance().getReference()
    .child("Member")
    .orderByChild("memberId")
    .equalTo("-LlGrtcsbW6jLWKoLhLw");

And everything else will work perfectly fine.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

You can try below.

myRef = FirebaseDatabase.getInstance().getReference().child("Member").child(userID);
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                Member member = dataSnapshot.getValue(Member.class);
                String name = member.getName();
                txtWelcomeName.setText(name);
            }

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

            }
        });
Anjana
  • 903
  • 1
  • 5
  • 13
  • I got this error – Ibrahim Munaser Aug 04 '19 at 08:46
  • E/AndroidRuntime: FATAL EXCEPTION: main Process: com.cis436.ewalletprototype, PID: 11681 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.cis436.ewalletprototype.Member.getName()' on a null object reference at com.cis436.ewalletprototype.MenuActivity$1.onDataChange(MenuActivity.java:68) at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@18.0.1:75) at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@18.0.1:63) – Ibrahim Munaser Aug 04 '19 at 08:46
  • That means your dataSnapshot is also null. Therefore there is no value come in via addValueListner(). you might have to check whether myRef is pointing to the correct node in firebase database. Check the userId is same as the one in firebase database. – Anjana Aug 04 '19 at 08:51
0

When you use getvalue() function you must pass the class name of the object you want to retrieve the value of. Try the following.

Instead of:

String name = dataSnapshot.child("name").getValue().toString();

You must use:

String name = dataSnapshot.child("name").getValue(String.class);

You can read the firebase documentation for more information. https://firebase.google.com/docs/database/android/read-and-write

  • Thank you! It allowed me to bypass the error, and now allowing me to MenuActivity.java. But the name of the individual is not popping up in the TextView. – Ibrahim Munaser Aug 04 '19 at 09:14
  • @IbrahimMunaser Have you checked whether the current userId actually exists (is a node) in the Firebase database, and that userId -> name has some value stored in it? –  Aug 04 '19 at 09:32