简体   繁体   中英

parse the json data and display in listview

I have parsed a data from a json, then add that in ArrayList. Now I have to display it in a listview. How to do it? I've got an error occured while doInBackground() was executing. 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

2.pass the ArrayList to your Adapter

3.set the Adapter to your ListView

4.download the data, put them into the ArrayList

5.call adapter.notifyDataSetChange()

then the ListView will refresh.

Use below code to parse you json data, then set adapter in 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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