如何获取当前用户ID并将其放入片段

时间:2018-11-13 14:21:52

标签: java android firebase nullpointerexception firebase-authentication

我要创建一个帐户片段,所以我想检索nameimage数据,但这会使我的应用强制关闭:

这是我的帐户片段:

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.support.constraint.Constraints.TAG;


/**
 * A simple {@link Fragment} subclass.
 */
public class AccountFragment extends Fragment {

  private StorageReference storageReference;
  private FirebaseAuth firebaseAuth;
  private FirebaseFirestore firebaseFirestore;
  private Uri mainImageURI = null;
  private String user_id;
  private TextView accountName;
  private CircleImageView accountImage;

  public AccountFragment() {
    // Required empty public constructor
  }


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_account, container, false);

    getUser();

    return view;
  }

  protected void getUser() {

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

    user_id = firebaseAuth.getCurrentUser().getUid();
    accountName = getView().findViewById(R.id.account_name);
    accountImage = getView().findViewById(R.id.account_image);

    firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener < DocumentSnapshot > () {
      @Override
      public void onComplete(@NonNull Task < DocumentSnapshot > task) {

        if (task.isSuccessful()) {

          if (task.getResult().exists()) {

            String name = task.getResult().getString("name");
            String image = task.getResult().getString("image");

            mainImageURI = Uri.parse(image);

            accountName.setText(name);

            RequestOptions placeholderRequest = new RequestOptions();
            placeholderRequest.placeholder(R.drawable.person);

            Glide.with(AccountFragment.this).setDefaultRequestOptions(placeholderRequest).load(image).into(accountImage);
          }

        } else {

          String error = task.getException().getMessage();
          Toast.makeText(getContext(), "(FIRESTORE Retrieve Error) : " + error, Toast.LENGTH_LONG).show();

        }


      }
    });

  }
}

这是我的错误日志

  

11-13 21:35:56.045 15465-15465 /? E / AndroidRuntime:致命异常:   主要       进程:com.example.hpprobook.blogapp,PID:15465       java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.hpprobook.blogapp / com.example.hpprobook.blogapp.MainActivity}:   java.lang.NullPointerException:尝试调用虚拟方法   'com.google.firebase.auth.FirebaseUser   com.google.firebase.auth.FirebaseAuth.getCurrentUser()”为null   对象参考           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2744)           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2805)           在android.app.ActivityThread.-wrap12(ActivityThread.java)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1538)           在android.os.Handler.dispatchMessage(Handler.java:102)           在android.os.Looper.loop(Looper.java:165)           在android.app.ActivityThread.main(ActivityThread.java:6354)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:883)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)        引起原因:java.lang.NullPointerException:尝试调用虚拟方法'com.google.firebase.auth.FirebaseUser   com.google.firebase.auth.FirebaseAuth.getCurrentUser()”为null   对象参考           在com.example.hpprobook.blogapp.AccountFragment.getUser(AccountFragment.java:68)           在com.example.hpprobook.blogapp.AccountFragment.onCreateView(AccountFragment.java:62)           在android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)           在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)           在android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)           在android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:792)           在android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)           在android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)           在android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)           在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)           在android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)           在android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)           在android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)           在android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)           在android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)           在com.example.hpprobook.blogapp.MainActivity.onStart(MainActivity.java:116)           在android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249)           在android.app.Activity.performStart(Activity.java:6874)           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2707)           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2805)           在android.app.ActivityThread.-wrap12(ActivityThread.java)           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1538)           在android.os.Handler.dispatchMessage(Handler.java:102)           在android.os.Looper.loop(Looper.java:165)           在android.app.ActivityThread.main(ActivityThread.java:6354)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:883)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)

在这里

getUser();

在这里

user_id = firebaseAuth.getCurrentUser().getUid();

这是我的mainActivity

import android.content.Intent;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
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.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

public class MainActivity extends AppCompatActivity {

  private Toolbar mainToolbar;
  private FirebaseAuth mAuth;
  private FirebaseFirestore firebaseFirestore;

  private String current_user_id;

  private FloatingActionButton addPostBtn;

  private BottomNavigationView mainbottomNav;

  private HomeFragment homeFragment;
  private NotificationFragment notificationFragment;
  private AccountFragment accountFragment;

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

    mAuth = FirebaseAuth.getInstance();
    firebaseFirestore = FirebaseFirestore.getInstance();

    mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
    setSupportActionBar(mainToolbar);

    getSupportActionBar().setTitle("PhotoGram");

    if (mAuth.getCurrentUser() != null) {

      mainbottomNav = findViewById(R.id.mainbottom_nav);

      // FRAGMENTS
      homeFragment = new HomeFragment();
      notificationFragment = new NotificationFragment();
      accountFragment = new AccountFragment();

      initializeFragment();

      mainbottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

          Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.main_container);

          switch (item.getItemId()) {

            case R.id.bottom_home_btn:

              replaceFragment(homeFragment, currentFragment);
              return true;

            case R.id.bottom_account_btn:

              replaceFragment(accountFragment, currentFragment);
              return true;

            case R.id.bottom_notification_btn:

              replaceFragment(notificationFragment, currentFragment);
              return true;

            default:
              return false;


          }

        }
      });


      addPostBtn = findViewById(R.id.add_post_btn);
      addPostBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Intent newPostIntent = new Intent(MainActivity.this, NewPostActivity.class);
          startActivity(newPostIntent);

        }
      });
    }
  }

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

    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
    if (currentUser == null) {

      sendToLogin();

    } else {

      current_user_id = mAuth.getCurrentUser().getUid();

      firebaseFirestore.collection("Users").document(current_user_id).get().addOnCompleteListener(new OnCompleteListener < DocumentSnapshot > () {
        @Override
        public void onComplete(@NonNull Task < DocumentSnapshot > task) {

          if (task.isSuccessful()) {

            if (!task.getResult().exists()) {

              Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
              startActivity(setupIntent);
              finish();

            }

          } else {

            String errorMessage = task.getException().getMessage();
            Toast.makeText(MainActivity.this, "Error : " + errorMessage, Toast.LENGTH_LONG).show();
          }
        }
      });
    }
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main_menu, menu);
    return true;

  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

      case R.id.action_logout_btn:
        logOut();
        return true;

      case R.id.action_setting_btn:

        Intent settingsIntent = new Intent(MainActivity.this, SetupActivity.class);
        startActivity(settingsIntent);

        return true;


      default:
        return false;


    }

  }

  private void logOut() {


    mAuth.signOut();
    sendToLogin();
  }

  private void sendToLogin() {

    Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
    startActivity(loginIntent);
    finish();

  }

  private void initializeFragment() {

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

    fragmentTransaction.add(R.id.main_container, homeFragment);
    fragmentTransaction.add(R.id.main_container, notificationFragment);
    fragmentTransaction.add(R.id.main_container, accountFragment);

    fragmentTransaction.hide(notificationFragment);
    fragmentTransaction.hide(accountFragment);

    fragmentTransaction.commit();

  }

  private void replaceFragment(Fragment fragment, Fragment currentFragment) {

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    if (fragment == homeFragment) {

      fragmentTransaction.hide(accountFragment);
      fragmentTransaction.hide(notificationFragment);

    }

    if (fragment == accountFragment) {

      fragmentTransaction.hide(homeFragment);
      fragmentTransaction.hide(notificationFragment);

    }

    if (fragment == notificationFragment) {

      fragmentTransaction.hide(homeFragment);
      fragmentTransaction.hide(accountFragment);

    }
    fragmentTransaction.show(fragment);

    //fragmentTransaction.replace(R.id.main_container, fragment);
    fragmentTransaction.commit();

  }

}

这里也显示了一些错误

super.onStart();

很抱歉,因为我的英语不好,而且我也是该论坛的新用户,我认为我需要得到指导。

3 个答案:

答案 0 :(得分:1)

显然,您使用的是非即时变量来获取数据。 尝试将其更改为:

protected void getUser() {

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

user_id = currentUser.getUid();
....
}

答案 1 :(得分:1)

这对我有用:

//in Class definition.
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private FirebaseUser currentUser;

//Declareation in Oncreate()
currentUser = firebaseAuth.getCurrentUser();
userId = currentUser.getUid();
private void setUserName() {
    /*
        Assign the value of profile_name_of field in the document of the current user
        under Users collection.
        pre:---.
        post: changes the value of the instance variable of username.
     */

    firebaseFirestore.collection("Users").document(userId)
            .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            DocumentSnapshot documentSnapshot = task.getResult();

            if(documentSnapshot.exists()){

                List<String> list = new ArrayList<>();
                Map<String, Object> map = documentSnapshot.getData();

                if(map != null){

                    for(Map.Entry<String, Object> entry : map.entrySet()){
                        list.add(entry.getValue().toString());
                    }

                    username = list.get(0);
                    Toast.makeText(context,
                          "username"+username,
                          Toast.LENGTH_LONG).show();
                }
            }
        }
    });
}

答案 2 :(得分:0)

要获取用户的uid,只需使用以下代码行:

FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
    String uid = firebaseUser.getUid(); //Do what you need to do with your uid
}

检查firebaseUser是否无效也很重要。