在使用Fragment用法调用我的活动时,我遇到了一个奇怪的问题。我收到错误,
java.lang.IllegalStateException:Fragment ScoreFragment {ee2b833 id = 0x7f0e0198}未附加到活动
在第146行。我的片段代码有错误,如下所示
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
我的完整代码如下,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPageFlag = getArguments().getString(ARG_PAGE_FLAG);
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && !mIsPageLoaded){
mContext = getActivity();
mIsPageLoaded = true;
if(mPageFlag.equalsIgnoreCase(getString(R.string.winners))){
new getcontestscorewinners(mContext).execute();
}else{ //
new getcontestscorewinnersNew(mContext).execute();
}
}
}
public class getcontestscorewinners extends AsyncTask<String, Void, String> {
boolean response = false;
private Context mContext;
public getcontestscorewinners(Context context) {
mContext = context;
}
@Override
protected void onPreExecute() {
progress = ProgressDialog.show(mContext, "Processing...",
"Please wait....");
}
@Override
protected String doInBackground(String... params) {
NetworkTask.getContestScoreWinners(winnerHandler);
return "";
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
如果有人可以帮助我摆脱它,请告诉我。感谢。
答案 0 :(得分:5)
尝试使用isAdded():
如果片段当前已添加到其活动中,则返回true。
所以你的代码应该是这样的:
if(isAdded() && mPageFlag.equalsIgnoreCase(getString(R.string.winners))){