0

这是我的片段类。它是 BottomNavigationView 的一部分:

package com.healthapp.instacare;

        import android.net.Uri;
        import android.os.Bundle;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;
        import android.widget.TextView;

        import androidx.annotation.NonNull;
        import androidx.annotation.Nullable;
        import androidx.fragment.app.Fragment;

        import com.google.android.gms.auth.api.signin.GoogleSignIn;
        import com.google.android.gms.auth.api.signin.GoogleSignInAccount;

public class HomeFragment extends Fragment{
    GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getActivity());

    TextView name= (TextView)getView().findViewById(R.id.name);
    TextView surname= (TextView)getView().findViewById(R.id.surname);
    TextView id= (TextView)getView().findViewById(R.id.id);
    TextView email= (TextView)getView().findViewById(R.id.email);
    ImageView profimg = (ImageView)getView().findViewById(R.id.profimg);


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getinfo();
    }

    private void getinfo() {
        if (acct != null) {
            String personName = acct.getDisplayName();
            String personFamilyName = acct.getFamilyName();
            String personEmail = acct.getEmail();
            String personId = acct.getId();
            Uri personPhoto = acct.getPhotoUrl();

            name.setText(personName);
            surname.setText(personFamilyName);
            id.setText(personId);
            email.setText(personEmail);
            profimg.setImageURI(personPhoto);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile,container,false);
    }

}

这是 Google 使用文档提供的方法:

GoogleSignInAccount acct = 
GoogleSignIn.getLastSignedInAccount(getActivity());
if (acct != null) {
    String personName = acct.getDisplayName();
    String personGivenName = acct.getGivenName();
    String personFamilyName = acct.getFamilyName();
    String personEmail = acct.getEmail();
    String personId = acct.getId();
    Uri personPhoto = acct.getPhotoUrl();
} 

如何在片段中实现它?我是 android studio 编码的新手。

我已经在.xml片段的文件中创建了一些 TextViews 和 ImageViews,我希望用 Google 帐户信息中的那些文本和图像 URL 替换并显示它。

我尝试了上面的代码,但它可能因为 NullPointerException 而崩溃。

4

0 回答 0