我想從我的片段之一中使用Volley從下面的url解析json。問題是「onResponse」沒有激活。我嘗試用Log和Toast Notification來捕獲異常。沒有任何異常。看起來OnResponse在片段中不起作用。從url中解析json與在Android中的片段排球
這是我的片段。
public class PlacesToVisitFragment extends Fragment {
public PlacesToVisitFragment() {
// Required empty public constructor
}
StringBuilder sb = new StringBuilder();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_places_to_visit, container, false);
final TextView txt= (TextView)view.findViewById(R.id.textView8);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://www.flightradar24.com/AirportInfoService.php?airport=ORY&type=in";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("flights");
for (int i=0; i< values.length(); i++) {
JSONObject sonuc = values.getJSONObject(i);
sb.append("Flight: " + sonuc.getString("flight") + "\n");
sb.append("name: " + sonuc.getString("name") + "\n\n");
}
txt.setText(sb.toString());
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
// Inflate the layout for this fragment
return view;
}
}
這是我如何定位從主要活動的片段。
if (id == R.id.nav_camera) {
PlacesToVisitFragment fragment = new PlacesToVisitFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.addToBackStack(null);
ft.commit();
}
我正在使用Android Navigation Drawer基本模板。感謝您的幫助提前。
非常感謝您的快速回復。它像一個魅力。 – oneNiceFriend
很高興我可以幫助:) –