我在我的应用上使用 Firebase 数据库,有时当数据更改应用崩溃时:
Exception java.lang.IllegalStateException: Fragment Fragmento_Medios_FB{e0076f1} not attached to Activity
android.support.v4.app.Fragment.getResources (Fragment.java:646)
info.blacktrail.catedralapp.Fragmento_Medios_FB$2.onDataChange (Fragmento_Medios_FB.java:614)
com.google.android.gms.internal.zzbpx.zza ()
com.google.android.gms.internal.zzbqx.zzZT ()
com.google.android.gms.internal.zzbra$1.run ()
android.os.Handler.handleCallback (Handler.java:751)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:154)
android.app.ActivityThread.main (ActivityThread.java:6682)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)
我检查每一件事,没有什么不对劲。有什么帮助吗?
这是我的片段
public class Fragmento_Medios_FB extends Fragment {
public Fragmento_Medios_FB() {
}
FragmentManager mFragmentManager;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
LinearLayout somelayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_medios_fb, container, false);
somelayout=(LinearLayout)view.findviewById.(R.id.somelayout);
return view;
}
@Override
public void onStart() {
super.onStart();
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String someString = dataSnapshot.child("medios").getValue
int Idsomeid = getResources().getIdentifier(edo_medios_sector_sur_01S, "drawable", getActivity().getPackageName());
somelayout.setBackgroundResource(Idsomeid);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
drawable是正确的,并且还检查了数据库项,有时不是每次数据库更改时都会发生崩溃
答案 0 :(得分:2)
他们是非常棘手的解决方案:
Activity activity = getActivity();
if(activity != null && isAdded()) {
int Idsomeid = getResources().getIdentifier(edo_medios_sector_sur_01S, "drawable", getActivity().getPackageName());
}
这种情况很明显,因为您的片段已创建,但当数据来自Firebase时,并未附加到Activity。
许多情况都可以返回此异常,例如Fragment MyFragment not attached to Activity和java.lang.IllegalStateException: Fragment not attached to Activity
答案 1 :(得分:1)
由于异常说“Fragmento_Medios_FB未附加到Activity”,这意味着当您的数据发生更改并通过“addValueEventListener”通知您时,Fragmento_Medios_FB未附加。为防止崩溃,您必须在生命周期的onStop方法中取消注册侦听器。