【发布时间】:2017-12-13 20:13:12
【问题描述】:
我在 Google Play 上有应用程序,在大多数设备上都可以正常工作,但在某些三星(SM-G531H、SM-G530BT)、华为、联想设备上似乎在getSharedPreferences 调用时崩溃。
我在片段方法中从onAttach(Context context) 引用上下文(我没有在onAttach 之前调用getSharedPreferences)
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
//init firebase analytics
mFirebaseAnalytics = FirebaseAnalytics.getInstance(context);
}
我有 sharedPreference 带有构造函数的辅助类
public UserStats(Context mContext) {
CRASH HERE
sharedPreferences = mContext.getSharedPreferences(PREF_USER,Context.MODE_PRIVATE);
}
这是fragment中调用sharedPreference的方法
private void setGoal(int calories){
new UserStats(mContext).setNewGoal(calories);
tvGoal.setText("Goal\n" + calories + " Cal");
}
知道为什么会这样吗?以及如何避免它? (我无法调试它,我在 Firebase 控制台中收到崩溃)
【问题讨论】:
-
请贴出所有相关代码。
-
嘿,我看到
onAtttach()调用中提到的here 不一致。你检查了吗?我会说寻找替代品。 -
有趣,但我之前使用过 getActivity() 并且结果相同
-
你在哪里调用
setGoal()方法?如果它是某些异步操作的结果,则片段可能已经与其活动分离,活动可能已经消失,剩下的只是一个过时的上下文引用。 -
你从哪里给
setGoal()打电话?还有一个小建议,在UserStats的构造函数中,不要在参数名称前加上m。那是反对code-style-guide。
标签: android android-fragments android-context