如何从API解析JSON响应

时间:2017-12-14 05:23:01

标签: android json parsing

我正在尝试获取json数据并将其放入ListView中。我正在按照教程并试图实现这一点。问题是:该教程基于AppCompatActivity,我试图将其添加到Fragment(标签)中:

public class InstallsTab extends Fragment{
    ListView installs;
    String url = "http://localhost/android.php";
    ProgressBar dialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.installs_tab, container, false);

        installs = rootView.findViewById(R.id.install_list);

        dialog = new ProgressBar(getActivity().getApplicationContext());
        dialog.setVisibility(View.VISIBLE);

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String string) {
                parseJsonData(string);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity().getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
                dialog.setVisibility(View.GONE);
            }
        });

        RequestQueue rQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
        rQueue.add(request);

        return rootView;
    }

    void parseJsonData(String jsonString) {
        try {
            JSONObject object = new JSONObject(jsonString);
            JSONArray fruitsArray = object.getJSONArray("fruits");
            ArrayList al = new ArrayList();

            for(int i = 0; i < fruitsArray.length(); ++i) {
                al.add(fruitsArray.getString(i));
            }

            ArrayAdapter adapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, al);
            installs.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        dialog.setVisibility(View.GONE);
    }

}

enter image description here

该应用程序正在崩溃。

1 个答案:

答案 0 :(得分:1)

您尚未正确初始化阵列列表

使用此

ArrayList<String> al = new ArrayList<>();

而不是这个

ArrayList al = new ArrayList();

修改

也会更改此用途 i++ 而不是 ++i

for(int i = 0; i < fruitsArray.length(); i++) {

    al.add(fruitsArray.getString(i));
}