簡體   English   中英

解析json數據並顯示在listview中

[英]parse the json data and display in listview

我已經從json解析了一個數據,然后將其添加到ArrayList中。 現在,我必須在列表視圖中顯示它。 怎么做? 在執行doInBackground()時發生錯誤。 我如何設置適配器以查看此內容。 我很混亂。 提出好的解決方案

<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.制作一個空但不為空的ArrayList

2.將ArrayList傳遞給適配器

3.將適配器設置為您的ListView

4.下載數據,將它們放入ArrayList

5. 調用adapter.notifyDataSetChange()

然后ListView將刷新。

使用下面的代碼來解析您的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