简体   繁体   English

解析json数据并显示在listview中

[英]parse the json data and display in listview

I have parsed a data from a json, then add that in ArrayList. 我已经从json解析了一个数据,然后将其添加到ArrayList中。 Now I have to display it in a listview. 现在,我必须在列表视图中显示它。 How to do it? 怎么做? I've got an error occured while doInBackground() was executing. 在执行doInBackground()时发生错误。 How i set adapter to view this. 我如何设置适配器以查看此内容。 I'm so confused. 我很混乱。 Suggest good solution 提出好的解决方案

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@android:id/list">
</ListView>

public class MainActivity extends ListActivity {
String url="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaSyD7c1IID7zDCdcfpC69fC7CUqLjz50mcls";
ArrayList<HashMap<String, String>> cList;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new googleplaces().execute();
}

private class googleplaces extends AsyncTask<Void, Void, Void> {


    @Override
    protected Void doInBackground(Void... arg0) {

        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
        HashMap<String, String> parse = new HashMap<>();
        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray jsonArray = jsonObj.getJSONArray("results");
                for (int i=0;i<jsonArray.length();i++) {
                    JSONObject object = jsonArray.getJSONObject(i);
                    String name = object.optString("name").toString();
                    if (object.has("opening_hours")) {
                        if (object.has("open_now")) {
                            if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").getString("open_now").equals("true")) {
                                //
                            } else {
                                //
                            }
                        }
                    } else {
                        //
                    }
                    JSONArray typesarray = object.getJSONArray("types");
                    for (i = 0; i < typesarray.length(); i++) {
                        String type = typesarray.getString(i);

                        String vicinity = object.optString("vicinity").toString();
                        Log.d("test",vicinity);

                        parse.put("name", name);
                        parse.put("type", type);
                        parse.put("vicinity", vicinity);
                        cList.add(parse);


                    }

                }



            }  catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
        }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);


    }
    }

}

1.make a empty but not null ArrayList 1.制作一个空但不为空的ArrayList

2.pass the ArrayList to your Adapter 2.将ArrayList传递给适配器

3.set the Adapter to your ListView 3.将适配器设置为您的ListView

4.download the data, put them into the ArrayList 4.下载数据,将它们放入ArrayList

5.call adapter.notifyDataSetChange() 5. 调用adapter.notifyDataSetChange()

then the ListView will refresh. 然后ListView将刷新。

Use below code to parse you json data, then set adapter in onPostExecute(): 使用下面的代码来解析您的json数据,然后在onPostExecute()中设置适配器:

    private class googleplaces extends AsyncTask<Void, Void, List<Result>> {


    @Override
    protected List<Result> doInBackground(Void... arg0) {

        //Create list to save list of result objects
        List<Result> list = new ArrayList<>();

        StringBuffer mBuffer = new StringBuffer();
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse response = client.execute(get);
            InputStream inputStream = response.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = br.readLine()) != null) {
                mBuffer.append(line);
            }
            Log.d("Response: ", "> " + mBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String jsonResult = mBuffer.toString();

        if (jsonResult != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonResult);

                JSONArray jsonArray = jsonObj.getJSONArray("results");
                for (int i = 0; i < jsonArray.length(); i++) {
                    //Creating Result model class object to store details
                    Result result = new Result();

                    JSONObject object = jsonArray.getJSONObject(i);
                    String name = object.optString("name").toString();
                    if (object.has("id")) {
                        result.setId(object.getString("id"));
                    } else {
                        result.setId("");
                    }
                    if (object.has("name")) {
                        result.setName(object.getString("name"));
                    } else {
                        result.setName("");
                    }
                    if (object.has("vicinity")) {
                        result.setName(object.getString("vicinity"));
                    } else {
                        result.setVicinity("");
                    }
                    if (object.has("opening_hours")) {
                        if (object.getJSONObject("opening_hours").has("open_now")) {
                            result.setOpening_now(object.getJSONObject("opening_hours").getString("open_now"));
                        } else {
                            result.setOpening_now("");
                        }
                    }
                    list.add(result);
                }
                for (int i = 0; i < list.size(); i++) {
                    CustomLog.d("List = " + list.get(i));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return list;
    }

    protected void onPostExecute(List<Result> result) {
        super.onPostExecute(result);

        //Here update result on UI
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM