gpt4 book ai didi

java - 如何检索当前用户 ID 并将其放入 fragment 中

转载 作者:行者123 更新时间:2023-12-02 10:36:05 29 4
gpt4 key购买 nike

我正在创建一个帐户 fragment ,因此我想检索名称图像数据,但这使我的应用程序强制关闭:

这是我的帐户 fragment :

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: FATAL EXCEPTION: main Process: com.example.hpprobook.blogapp, PID: 15465 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hpprobook.blogapp/com.example.hpprobook.blogapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2744) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2805) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1538) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:165) at android.app.ActivityThread.main(ActivityThread.java:6354) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference at com.example.hpprobook.blogapp.AccountFragment.getUser(AccountFragment.java:68) at com.example.hpprobook.blogapp.AccountFragment.onCreateView(AccountFragment.java:62) at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428) at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759) at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:792) at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596) at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383) at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245) at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248) at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200) at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195) at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597) at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177) at com.example.hpprobook.blogapp.MainActivity.onStart(MainActivity.java:116) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1249) at android.app.Activity.performStart(Activity.java:6874) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2707) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2805)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1538)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:165)  at android.app.ActivityThread.main(ActivityThread.java:6354)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)

在这里

getUser();

这里

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

这是我的主要 Activity

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

很抱歉,我的英语不好,而且我也是这个论坛的新用户,我想我需要指导。

最佳答案

显然您正在使用未实例化的变量来获取数据。尝试将其更改为:

protected void getUser() {

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

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

关于java - 如何检索当前用户 ID 并将其放入 fragment 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283129/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com