@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_home, container, false);
return myFragmentView;
}
我通常执行此onCreateView
并且我的所有代码都在其中,因为我提出了建议并将我的其余代码插入onViewCreated
。我没有抱怨,但发生了同样的事情。我打开片段活动时ASyncTask
没有执行。这是我的onViewCreated
:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Requ connReq = new Requ();
connReq.execute(); //go go power rangers
}
毕竟这并不复杂,但由于某种原因它不会启动我的asynctask。它会显示ProgressDialog
从onPreExecute
开始并在onPostExecute
中解散。所以你可以说它不会执行我的doInBackground
这件事我做错了什么?我只想在打开片段并加载数据时执行ASyncTask。
我非常感谢你的帮助,提前谢谢。我搜遍了整个地方,但我真的找不到合适的解决方案,我以为会有一个。
PS:当我将执行添加到onClickListener
我的asynctask:
private class Requ extends AsyncTask<String, String[], String[]> {
final String pdMessage = getString(R.string.pd_wait);
ProgressDialog pd = new ProgressDialog(getActivity());
@Override
protected void onPreExecute () {
pd.setMessage(pdMessage);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
@Override
protected String[] doInBackground(String... params) {
String[] connResult;
final String SipUrlStr = getString(R.string.sip_url);
String bsm = "";
String bst= "";
String hs= "";
String as= "";
try {
JSONTokener SipTokener = new JSONTokener(Sources.httpConnGet(SipUrlStr).toString());
JSONArray SipArray=new JSONArray(SipTokener);
for(int i=0; i<(SipArray.length()); i++)
{
JSONObject json_obj_sip = yeniSipArray.getJSONObject(i);
bsm = json_obj_sip.getString("mt");
bst = json_obj_sip.getString("tt");
hs = json_obj_sip.getString("pta");
as = json_obj_sip.getString("pta2");
}
} catch (Exception e) {
bsm = getString(R.string.def_sip);
bst = getString(R.string.def_sip);
hs = getString(R.string.has);
as = getString(R.string.ass);
}
connRes = new String[]{bsm, bst, hs, as};
return connRes;
}
@Override
protected void onPostExecute(String[] connRes) {
super.onPostExecute(connRes);
res[0] = connRes[0];
res[1] = connRes[1];
res[2] = connRes[2];
res[3] = connRes[3];
res[4] = connRes[4];
res[5] = connRes[5];
res[6] = connRes[6];
res[7] = connRes[7];
res[8] = connRes[8];
res[9] = connRes[9];
res[10] = connRes[10];
res[11] = connRes[11];
pd.dismiss();
}
}
答案 0 :(得分:0)
尝试在
中启动异步任务onActivityCreated
功能
public void onActivityCreated(Bundle b){
super.onActivityCreated(b);
// Execute here
//Get views
getView().findViewById(<ID>);
}
答案 1 :(得分:0)
事实证明这是关于周期的。由于我试图在AsyncTask
上启动MainThread
,因此代码飞过,AsyncTask
没有足够的时间来完成其工作。绝对不应该让线程等待AsyncTask
。这违反了AsyncTask
的第一条规则。 “不这样做。”好的,所以我将AsyncTask
的执行移动到onCreate()
,这样就会有更多的时间,每次打开片段都不会执行...
@Override
public void onCreate(Bundle savedInstanceState) {
Requ connReq = new Requ();
connReq.execute(); //go go power rangers
super.onCreate(savedInstanceState);
}
然后,这很重要,我将所有代码移到onPostExecute()
AsyncTask
方法中。如果您想更改变量或更改视图,您应该onPostExecute()
。