这是我写的代码:
public class ResultsFragment extends Fragment implements RequestHandler {
FragmentNameFactory nameFactory = new FragmentNameFactory();
String status = "1" ;
public ResultsFragment(){
//Fragment needs a constructor, can be empty
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
((MainActivity) getActivity()).setFragmentName(nameFactory.getNameNL(5));
final View view = inflater.inflate(R.layout.fresults, container, false);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://grwn.ddns.net:1337/results";
final String body = "{\"id\":1}";
RequestHandler requestHandler = this;
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body, requestHandler);
rq.add(volleyStringRequest.createStringRequest());
Log.e("CreateView status", status);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstance){
super.onViewCreated(view, savedInstance);
}
@Override
public void onActivityCreated(Bundle savedInstance){
super.onActivityCreated(savedInstance);
}
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray values= jsonObject.getJSONArray("response");
Log.e("RESPONSE", values.toString());
Log.e("STATUS", jsonObject.get("status").toString());
setStatus(jsonObject.get("status").toString());
Log.e("status variable", status);
}
catch (JSONException e){
e.printStackTrace();
}
}
public void setStatus(String value){
status += value;
Log.e("setStatus", status);
}
}
界面:
public interface RequestHandler {
void onResponse(String response);
}
VolleyClass:
public class VolleyStringRequest {
String url;
String body;
String value;
RequestHandler requestHandler;
public VolleyStringRequest(String url, String body, RequestHandler requestHandler){
this.url = url;
this.body = body;
this.requestHandler = requestHandler;
value= "";
}
public StringRequest createStringRequest(){
return new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
Log.e("Response", response);
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("response");
value += o;
if(requestHandler != null){
requestHandler.onResponse(value);
}
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
return body.getBytes();
};
@Override
public String getBodyContentType() {
return "application/json";
}
};
}
}
我想将响应中的对象分配给ResultsFragment
中的全局变量,并在onCreateView
内使用它,但不知怎的,我无法将值赋给onCreateView
内的变量。稍后在运行期间,该值将分配给状态变量。谁能帮我解决这个问题?
答案 0 :(得分:0)
一般来说,在onCreateView
中,您会在布局中显示进度微调器或其他内容,然后在onResponse
处理程序中更新布局并设置变量等,基于您从请求响应中获得的数据。
因此,不要求onCreateView
中的数据,而是推迟到响应回来并处理它。