在我的应用程序中,每个用户都有一个唯一的用户名,我保留这样的用户数据:
root:
+users:
+ricksanchez:
+name:"Rick Sanchez";
+email:"rick@sanchez.com";
+bio:"I'm super smart";
+followers:
+follower1:morty;
+follower2:summer;
当我想更改用户名时,我必须更改数据库密钥,但是firebase没有任何方法可以做到这一点,因此我使用以下代码:
private void copyRecord(DatabaseReference fromPath, final DatabaseReference toPath) {
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isComplete()) {
Log.d(TAG, "Success!");
} else {
Log.d(TAG, "Copy failed!");
}
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
fromPath.addListenerForSingleValueEvent(valueEventListener);
}
此代码在第一次运行时很完美,但是当我第二次运行此代码而不关闭应用程序时,应用程序崩溃了,但是当我在崩溃后再次运行应用程序时,它运行正常,但是第二次崩溃了
我也在片段中使用此代码,我在此代码中加载了片段:
public void pushFragment(Fragment fragment){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.mainframe,fragment).hide(getCurrentFragment()).addToBackStack(null).commit();
}
我的错误日志:
java.lang.IllegalStateException: Fragment UsernameChangeFragment{2a2928de} not attached to a context.
at android.support.v4.app.Fragment.requireContext(Fragment.java:693)
at android.support.v4.app.Fragment.getResources(Fragment.java:757)
at android.support.v4.app.Fragment.getString(Fragment.java:779)
at sonata.com.sonata.Util.UsernameChangeFragment$2$1.onDataChange(UsernameChangeFragment.java:90)
at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
你知道为什么吗?
编辑:我崩溃的片段代码:
usernameedittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
if(text.length()>0){
if(!text.toString().equals(username)){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(text.toString());
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
/* this is my error line*/ uyarıtext.setText(getString(R.string.youcantakethisusername));
uyarıtext.setTextColor(Color.parseColor("#00ff00"));
uyarıtext.setVisibility(View.VISIBLE);
}
else{
uyarıtext.setText(getString(R.string.usernametaken));
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
uyarıtext.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
else{
uyarıtext.setVisibility(View.INVISIBLE);
}
}
else{
uyarıtext.setVisibility(View.INVISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
savebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("1","butona tıklandı");
if (usernameedittext.getText().toString().length() > 0 && !usernameedittext.getText().toString().equals(username)) {
Log.i("2","yeni username kriterleri uygun");
yeni.child(usernameedittext.getText().toString()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Log.i("3","kullanıcı adı uygun");
copyRecord(eski, yeni.child(usernameedittext.getText().toString()));
Log.i("15","copyrecord bitti");
} else {
uyarıtext.setText(getString(R.string.usernametaken));
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
uyarıtext.setVisibility(View.VISIBLE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
});
我的寄存器片段也因相同的错误而崩溃;
username.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence text, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence text, int start, int before, int count) {
if (text.length()>0) {
database.child("users").child(text.toString()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
uyarıtext.setVisibility(View.VISIBLE);
uyarıtext.setText(getResources().getString(R.string.youcantakethisusername));
uyarıtext.setTextColor(Color.parseColor("#00ff00"));
} else {
uyarıtext.setVisibility(View.VISIBLE);
/ *这是我的错误行* /
uyarıtext.setText(getResources()。getString(R.string.usernametaken));
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
else{
uyarıtext.setVisibility(View.INVISIBLE);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("1","butona tıklandı");
if(namesurname.getText().toString()!=null&&email.getText().toString()!=null&&password.getText().toString()!=null){
Log.i("2","edittextler boş değil");
progressDialog.show();
Log.i("3","propgres gösterildi");
database.child("users").child(username.getText().toString()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Log.i("4","girilen kullanıcı adı alınabilir");
if (isValidEmail(email.getText().toString())) {
Log.i("5","e posta geçerli");
auth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
try {
throw task.getException();
} catch (FirebaseAuthWeakPasswordException e) {
uyarıtext.setVisibility(View.VISIBLE);
progressDialog.hide();
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
uyarıtext.setText(getResources().getString(R.string.weakpassword));
} catch (FirebaseAuthInvalidCredentialsException e) {
uyarıtext.setVisibility(View.VISIBLE);
progressDialog.hide();
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
uyarıtext.setText(getResources().getString(R.string.invalidemail));
} catch (FirebaseAuthUserCollisionException e) {
uyarıtext.setVisibility(View.VISIBLE);
progressDialog.hide();
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
uyarıtext.setText(getResources().getString(R.string.emailtaken));
} catch (Exception e) {
}
} else {
Log.i("6","kullanıcı oluşturudu");
DatabaseReference ref = database.child("users").child(username.getText().toString());
Log.i("7","username'e refereans oluşturuldu");
DatabaseReference refuidusername = database.child("uidusername").child(auth.getUid());
Log.i("8","uid refereansı oluşturuldu");
refuidusername.setValue(username.getText().toString());
Log.i("9","uidusername değeri yazıldı");
User user = new User();
Log.i("10","yeni user oluşturuldu");
user.setUId(auth.getUid());
Log.i("11","yeni useruid değeri yazıldı");
user.setNamesurname(namesurname.getText().toString());
Log.i("12","yeni user adsoyad değeri yazıldı");
user.setEmail(email.getText().toString());
Log.i("13","yeni user email değeri yazıldı");
ref.setValue(user);
Log.i("14","databse bu yser verileri yüklendi");
progressDialog.hide();
Log.i("15","progresdialog gizlendi");
FragmentTransaction ft = getFragmentManager().beginTransaction();
Log.i("16","gragmenttransaction.getfragmentmanager.begintransaction");
for (int i = 0; i < getFragmentManager().getBackStackEntryCount(); i++) {
getFragmentManager().popBackStack();
}
Log.i("17","backstack temizlendi");
ft.replace(R.id.mainframe, new MainFragment()).commit();
}
}
});
} else {
toast(getResources().getString(R.string.invalidemail));
progressDialog.hide();
}
} else {
uyarıtext.setVisibility(View.VISIBLE);
uyarıtext.setText(getResources().getString(R.string.usernametaken));
uyarıtext.setTextColor(Color.parseColor("#ff0000"));
progressDialog.hide();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
});
答案 0 :(得分:0)
这绝对是不是 Firebase问题。该错误表明您的UsernameChangeFragment
未附加到上下文,这意味着您的片段不属于活动。为了解决这个问题,每次您需要使用context
时,只需检查活动是否为空:
Activity activity = getActivity();
if(activity != null) {
//Your logic
}
还有另一个选项暗示使用isAdded()方法,这是一种片段方法,可以帮助您识别当前片段是否附加到其活动上。
if(isAdded()) {
//Your logic
}