FirebaseUser ID在片段中为null

时间:2019-07-10 18:29:48

标签: android firebase-authentication

我试图让用户登录,如果他在我不能登录之前登录,但是使用片段时却无法工作,它给了我空指针异常

MainActivity

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";


private FirebaseAuth auth;


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

    auth = FirebaseAuth.getInstance();

    if(auth != null) {

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(navListener);


        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new LeadsFragment()).commit();

    }

}

private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

        Fragment selectedFragment = null;

        switch (menuItem.getItemId()) {
            case R.id.main_leads:
                selectedFragment = new LeadsFragment();
                break;

            case R.id.main_bank_details:
                selectedFragment = new BankDetailsFragment();
                break;

            case R.id.main_payment:
                selectedFragment = new PaymentFragment();
                break;
        }

        // Update Ui
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();


        return true;

        }

};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.lead_logout:
            logOut();

        case R.id.lead_add_lead:
            Intent addNewLeadIntent = new Intent(this, AddLeadActivity.class);
            startActivity(addNewLeadIntent);


        default:

            return super.onOptionsItemSelected(item);

    }
}

private void logOut() {

    auth.signOut();

    // Update UI
    Intent loginIntent = new Intent(this, LoginActivity.class);
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(loginIntent);

}

@Override
public void onStart() {
    super.onStart();

    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();

    if (currentUser == null) {
       sendToLogin();
    } else {
        Log.d(TAG, "onStart: signed in");
    }

}
private void sendToLogin(){
    Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(loginIntent);
    finish();

}

LoginActivity

public class LoginActivity extends AppCompatActivity {

private FirebaseAuth auth;
private EditText emailPhoneEd, passwordEd;
private Button loginBtn;
private TextView goToRegister;

private ProgressBar progressBar;
private Toolbar toolbar;
private TextView forgotPassword;

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

    auth = FirebaseAuth.getInstance();

    toolbar = findViewById(R.id.login_toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Login");

    emailPhoneEd = findViewById(R.id.login_email_phone_ed);
    passwordEd = findViewById(R.id.login_password);

    progressBar = findViewById(R.id.login_progress);

    loginBtn = findViewById(R.id.login_btn);

    forgotPassword = findViewById(R.id.login_forgot_password);

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

            showRecoverPasswordDialoge();

        }
    });

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

            String email = emailPhoneEd.getText().toString();
            String password = passwordEd.getText().toString();

            signInUser(email, password);

        }
    });

    goToRegister = findViewById(R.id.login_go_to_register);

    goToRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendToRegister();
        }
    });
}

@Override
protected void onStart() {
    super.onStart();

    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();

    if(currentUser != null){
        Intent mainIntent = new Intent(LoginActivity.this , MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mainIntent);
        finish();
    }

}


private void beginRecovery(String email) {

    auth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if (task.isSuccessful()) {

                Toast.makeText(LoginActivity.this, "Email Sent", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
            }

        }
    });
}

private void signInUser(String email, String passwrod) {

    enableProgressBar();

    if (TextUtils.isEmpty(email) || TextUtils.isEmpty(passwrod)) {
        Toast.makeText(this, "Please fill all the fileds", Toast.LENGTH_SHORT).show();
        disableProgressBar();
    } else {
        auth.signInWithEmailAndPassword(email, passwrod).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                if (task.isSuccessful()) {

                    Toast.makeText(LoginActivity.this, "Sign in complete", Toast.LENGTH_SHORT).show();

                    Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
                    mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(mainIntent);
                    finish();

                } else {
                    Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                }

                disableProgressBar();

            }
        });
    }

}

private void sendToRegister() {

    Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
    startActivity(registerIntent);
    finish();

}

private void enableProgressBar() {

    progressBar.setVisibility(View.VISIBLE);
    loginBtn.setVisibility(View.INVISIBLE);

}

private void disableProgressBar() {
    progressBar.setVisibility(View.INVISIBLE);
    loginBtn.setVisibility(View.VISIBLE);
}

}

Logcat注释(LeadFragment是片段中的第一个活动或主要活动)

07-10 14:03:16.885 7243-7243/com.best.karem.mycareassociates E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.best.karem.mycareassociates, PID: 7243
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.best.karem.mycareassociates/com.best.karem.mycareassociates.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
    at com.best.karem.mycareassociates.Fragments.LeadsFragment.onCreateView(LeadsFragment.java:103)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
    at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
    at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
    at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
    at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
    at com.best.karem.mycareassociates.MainActivity.onStart(MainActivity.java:123)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
    at android.app.Activity.performStart(Activity.java:6253)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我尝试将这段代码放在LeadFragment中,但是它不起作用,并试图使主活动成为登录活动,并且它也行不通。我需要帮助,因为这是我第一次将其作为片段

铅碎片

public class LeadsFragment extends Fragment {

private RecyclerView recyclerView;
private Toolbar toolbar;
private FirebaseAuth auth;
private Context context;
private DatabaseReference leadRef;
private FirebaseRecyclerAdapter<Lead, LeadViewHolder> adapter;
private ProgressBar progressBar;


private Lead currentLead;

private String name;
private String contactPhone;
private String amount;
private String info;
private String purpose;
private String status;
private long actionDate;
private String paymentSanctioned;
private String current_user;
private String payoutAmount;


//   @RequiresApi(api = Build.VERSION_CODES.N)
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.leads_activity, container, false);

    toolbar = view.findViewById(R.id.leads_toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Leads");
    toolbar.getOverflowIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
    setHasOptionsMenu(true);


    auth = FirebaseAuth.getInstance();
    current_user = auth.getCurrentUser().getUid();


    // current_user = auth.getCurrentUser().getUid();

    recyclerView = view.findViewById(R.id.leads_recyclerview);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));


    progressBar = view.findViewById(R.id.leads_progress);

    leadRef = FirebaseDatabase.getInstance().getReference().child("Leads");


    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {

            progressBar.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);

        }
    }, 1000);


    adapter = new FirebaseRecyclerAdapter<Lead, LeadViewHolder>(
            Lead.class,
            R.layout.lead_item,
            LeadViewHolder.class,
            leadRef.orderByChild("userId").equalTo(current_user)
    ) {
        @Override
        protected void populateViewHolder(LeadViewHolder viewHolder, Lead model, final int position) {


            viewHolder.leadName.setText(model.getName());

            final String key = adapter.getRef(position).getKey();


            leadRef.child(key).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    currentLead = dataSnapshot.getValue(Lead.class);

                    name = currentLead.getName();
                    contactPhone = currentLead.getContactPhone();
                    amount = currentLead.getAmount();
                    info = currentLead.getInfo();
                    purpose = currentLead.getPurpose();
                    status = currentLead.getStatus();
                    actionDate = currentLead.getActionDate();
                    paymentSanctioned = currentLead.getSanctionedPayment();
                    payoutAmount = currentLead.getPayoutAmount();


                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });


            viewHolder.leadCardView.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public void onClick(View view) {

                    Toast.makeText(getContext(), key, Toast.LENGTH_SHORT).show();

                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    builder.setTitle("Lead Information");
                    builder.setMessage(
                            "Name: " + name + "\n\n" +
                                    "Contact Phone: " + contactPhone + "\n\n" +
                                    "Amount: " + amount + "\n\n" +
                                    "Info: " + info + "\n\n" +
                                    "Purpose: " + purpose + "\n\n" +
                                    "Status: " + status + "\n\n" +
                                    "Action Date: " + getDate(actionDate) + "\n\n" +
                                    "Payment Sanctioned: " + paymentSanctioned + "\n\n" +
                                    "PayOut Amount: " + payoutAmount + "\n\n"

                    );
                    builder.setCancelable(true);
                    builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.cancel();
                        }
                    });
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                }
            });

        }
    };

    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();


    return view;

}



@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.leads_menu, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.lead_logout:
            logOut();

        case R.id.lead_add_lead:
            Intent addNewLeadIntent = new Intent(getContext(), AddLeadActivity.class);
            startActivity(addNewLeadIntent);


        default:

            return super.onOptionsItemSelected(item);

    }
}

private String getDate(long actionDate) {

    SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

    return sfd.format(new Date(actionDate));

}

private void logOut() {

    auth.signOut();

    // Update UI
    Intent loginIntent = new Intent(getContext(), LoginActivity.class);
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(loginIntent);

}

0 个答案:

没有答案