onCreateView方法终止,无需等待来自Web服务的响应。当然,视图返回null。其他一切都正常。我的意思如下。
private View view;
private View notExistedOwnStory;
private View existedOwnStory;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
notExistedOwnStory = inflater.inflate(R.layout.tab_writestory, container, false);
existedOwnStory = inflater.inflate(R.layout.tab_deletestory, container, false);
checkOwnStory(storyID, username);
if(view == notExistedOwnStory){
...
}
if (view == existedOwnStory) {
...
}
return view;
}
private void checkOwnStory(final String storyID,final String username) {
// Tag used to cancel the request
String tag_string_req = "req_checkOwnStory";
pDialog.setMessage("Checking Own Story ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST, AppConfig.CHECK_OWN_STORY, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Checking Own Story Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// here is the set according to the response
view = existedOwnStory;
} else {
view = notExistedOwnStory;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Checking Own Story Error: " + error.getMessage());
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params to check own story url
Map<String, String> params = new HashMap<String, String>();
params.put("storyID", storyID);
params.put("username", username);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
如果checkOwnStory方法完全结束并且onCreateView方法相应地工作,该怎么办?
答案 0 :(得分:0)
这不是正确的设计。 onCreateView()在主线程上运行,因此你不能简单地等待这种方法来膨胀视图。因此,您可以通过扩展XML(可能带进度对话框)来显示临时进度。
在成功解析JSON后,您可以使用public void onResponse(String response)
使用Handler.post()
通过Handler发布消息。
您可以实现handleMessage()
方法,并根据您从onResponse()
方法获得的消息,您可以通过编程方式(addView
)或通过ViewStub从XML文件添加您想要的任何视图并将该视图更新为View.VISIBLE
。