首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android应用程序:从实时数据库到防火墙--将数据更新为数据库

Android应用程序:从实时数据库到防火墙--将数据更新为数据库
EN

Stack Overflow用户
提问于 2018-01-05 11:24:59
回答 1查看 869关注 0票数 0

我正在工作我的第一个应用程序,并只是设置所有的框架工作。也就是说,用户通过Google、电子邮件、Facebook注册,并将数据保存到Firebase。我开始使用实时数据库,它工作得很好,但在我的项目进行过程中,我认为FireStore云更适合。

我还没有多少数据,所以很容易就能建立起来。用户注册或登录,如果他还不存在,将根据FirebaseAuth名称+电子邮件和我定义的一些变量(“昵称”、"-")和其他几个变量来设置配置文件。目前为止一切都很好。一旦用户单击他的配置文件,信息就会被获取和显示。然后可以选择编辑一些数据,比如昵称、年龄和国籍。如果我直接在防火墙上更新数据并再次单击profile,它将正确显示。但是,如果用户输入信息并单击触发对防火墙云的更新的按钮,应用程序就会崩溃。然而,数据库也会正确地更新.我试了很多东西,但我被卡住了!非常感谢你的帮助!

我的代码

当用户登录时,将信息存储到云中的用户类=>

代码语言:javascript
复制
public class User extends AppCompatActivity {

public static final String AGE = "Age";
public static final String EMAIL = "Email";
public static final String FULLNAME = "Full name";
public static final String NATIONALITY = "Nationality";
public static final String NICKNAME = "Nickname";
public static final String STATUS = "Status";

private String userEmail = FirebaseAuth.getInstance().getCurrentUser().getEmail();
private String userFullName = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();


public User() {
    // Default constructor required for calls to DataSnapshot.getValue(User.class)
}

protected void checkFireStoreDatabase() {
    // Create a new user with a first and last name
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference usersDocRef = db.collection("Users").document(userFullName);

    if (usersDocRef != null) {
    } else {
        createNewEntry();
    }
}

public void createNewEntry() {
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference usersDocRef = db.collection("Users").document(userFullName);
    Map<String, Object> userEntry;

    userEntry = new HashMap<>();
    userEntry.put("Full name", userFullName);
    userEntry.put(EMAIL, userEmail);
    userEntry.put("Nickname", "-");
    userEntry.put("Age", "-");
    userEntry.put("Nationality", "-");
    userEntry.put("Status", "Baby monkey");
    db.document(userFullName).set(userEntry, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "Document has been saved");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d(TAG, "Document could not be saved");
        }
    });
}

用户配置文件片段=>,用户可以在其中看到存储在云中的信息

代码语言:javascript
复制
public class UserProfileFragment extends Fragment implements View.OnClickListener {
private Button btnEditProfile;

//get firestore database data
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private DocumentReference usersDocRef = db.collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getDisplayName());

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    //DATA FROM FIRESTORE
    displayFirestoreData();

    btnEditProfile = (Button) view.findViewById(R.id.edit_user_info);
    btnEditProfile.setOnClickListener(this);
}

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

@Override
public void onClick(View v) {
    Fragment fragment = null;
    //if the button representing the "train now or create workout" fragment is clicked, create this fragment
    if (v.getId() == R.id.edit_user_info) {
        fragment = new EditUserProfileFragment();
    }
    if (fragment != null) {
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .addToBackStack(null)
                .commit();
    }
}

public void displayFirestoreData() {
    if (usersDocRef != null) {
    }
        //this.getActivity makes sure the listener only works when in this FragmentActivity
    usersDocRef.addSnapshotListener(this.getActivity(), new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
            if (documentSnapshot.exists()) {
                String name = documentSnapshot.getString(FULLNAME);
                String email = documentSnapshot.getString(EMAIL);
                String nickname = documentSnapshot.getString(NICKNAME);
                String age = documentSnapshot.getString(AGE);
                String nationality = documentSnapshot.getString(NATIONALITY);
                String status = documentSnapshot.getString(STATUS);

                //setting all the text views in the user profile
                TextView txtProfileName = (TextView) getView().findViewById(R.id.profile_section_fullname);
                txtProfileName.setText(name);
                TextView txtProfileEmail = (TextView) getView().findViewById(R.id.profile_section_email);
                txtProfileEmail.setText(email);
                TextView txtProfileNickname = (TextView) getView().findViewById(R.id.profile_section_nickname);
                txtProfileNickname.setText(nickname);
                TextView txtProfileAge = (TextView) getView().findViewById(R.id.profile_section_age);
                txtProfileAge.setText(age);
                TextView txtProfileNationality = (TextView) getView().findViewById(R.id.profile_section_nationality);
                txtProfileNationality.setText(nationality);
                TextView txtProfileStatus = (TextView) getView().findViewById(R.id.profile_section_status);
                txtProfileStatus.setText(status);
            } else if (e != null) {
                Log.w(TAG, "An exception occured", e);
            }
        }
    });

}

编辑用户配置文件片段=>,其中用户可以输入新的昵称、年龄或国籍

代码语言:javascript
复制
    public class EditUserProfileFragment extends Fragment implements View.OnClickListener {
    private Button btnSaveProfile;

    private EditText editUsername;
    private EditText editAge;
    private EditText editNationality;

    private String username_input;
    private String age_input;
    private String nationality_input;


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //Button to save the profile
        btnSaveProfile = (Button) view.findViewById(R.id.save_user_info);
        btnSaveProfile.setOnClickListener(this);

        //field that allows changes on the nick name
        editUsername = (EditText) view.findViewById(R.id.profile_section_edit_nickname);

        //field that allows you to enter the correct age
        editAge = (EditText) view.findViewById(R.id.profile_section_edit_age);

        //field that allows you to enter your nationality
        editNationality = (EditText) view.findViewById(R.id.profile_section_edit_nationality);

    }

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

    @Override
    public void onClick(View v) {
        username_input=  editUsername.getText().toString().trim();
        age_input = editAge.getText().toString().trim();
        nationality_input = editNationality.getText().toString().trim();

        //update Firestore data
        updateFireStoreData(username_input, age_input, nationality_input);
       }

    //update the user entered information to the database, if the strings arent empty
    public void updateFireStoreData(String nicknameUpdate, String ageUpdate, String nationalityUpdate) {
       FirebaseFirestore db = FirebaseFirestore.getInstance();
       FirebaseUser currUser = FirebaseAuth.getInstance().getCurrentUser();
       DocumentReference userDocRef = db.collection("Users").document(currUser.getDisplayName());

        if (!nicknameUpdate.matches("")) {
            Map<String, Object> dataUpdate = new HashMap<String, Object>();
            dataUpdate.put(NICKNAME, nicknameUpdate);
            userDocRef
                    .set(dataUpdate, SetOptions.merge()).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    Log.d(TAG, "Document has been saved");
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d(TAG, "Document could not be saved");
                }
            });
        }
}

错误日志:

E/AndroidRuntime:致命异常:主要进程: MYAPP,PID: 3992 java.lang.NullPointerException:尝试在MYAPP.UserProfileFragment$1.onEvent(UserProfileFragment.java:91) at com.google.firebase.firestore.DocumentReference.的MYAPP.UserProfileFragment$1.onEvent(UserProfileFragment.java:91)上调用空对象引用上的虚拟方法'android.view.View android.view.View.findViewById(int)‘com.google.firebase.firestore.zzd.onEvent(Unknown来源:6)在com.google.android.gms.internal.zzevc.zza(Unknown来源:6)在com.google.android.gms.internal.zzevd.run(Unknown来源:6)在android.os.Handler。android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:251) at android.app.ActivityThread.main(ActivityThread.java:6563) at java.lang.reflect.Method.invoke(原生方法)在com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-05 11:36:51

这不是Firebase数据库异常,也不是CloudFi还原异常。你的例外清楚地告诉你发生了什么。因此,您正在尝试使用findViewById()方法on a null object reference。这意味着getView()返回null。之所以会发生这种情况,是因为在返回fragmnet视图之后调用该方法。

为了解决这个问题,先调用这些方法,然后在视图上直接使用findViewById()方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48112652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档