Android中的Listview中未显示数据

时间:2017-06-26 04:44:04

标签: java android listview android-adapter

我正在尝试谷歌从谷歌api放置数据并显示在列表视图中。我成功获取数据并设置为适配器,但无法在listview中显示。

  

MainActivity。 java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv=(ListView)findViewById(R.id.listView);

    StringBuilder sbValue = new StringBuilder(sbMethod());
    PlacesTask placesTask = new PlacesTask();
    placesTask.execute(sbValue.toString());

    MyAdapter adapter=new MyAdapter(MainActivity.this,R.layout.my_adapter_item,arr);
    lv.setAdapter(adapter);
}

public StringBuilder sbMethod() {

    //use your current location here
    double mLatitude =-33.8670522;
    double mLongitude =151.1957362;

    StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
    sb.append("location=" + mLatitude + "," + mLongitude);
    sb.append("&radius=5000");
    sb.append("&types=" + "restaurant");
    sb.append("&sensor=true");
    sb.append("&key=AIzaSyC2SaN5I5u2eWw3zr4OZoLwD0qvCU-_uUw");

    Log.d("Map", "api: " + sb.toString());

    return sb;
}

private class PlacesTask extends AsyncTask<String, Integer, String> {

    String data = null;

    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(String result) {
        ParserTask parserTask = new ParserTask();

        // Start parsing the Google places in JSON format
        // Invokes the "doInBackground()" method of the class ParserTask
        parserTask.execute(result);
    }
}

private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb = new StringBuffer();

        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    } catch (Exception e) {
        Log.d("Exception downloading", e.toString());
    } finally {
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}


private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

    JSONObject jObject;

    // Invoked by execute() method of this object
    @Override
    protected List<HashMap<String, String>> doInBackground(String... jsonData) {

        List<HashMap<String, String>> places = null;
        Place_JSON placeJson = new Place_JSON();

        try {
            jObject = new JSONObject(jsonData[0]);

            places = placeJson.parse(jObject);

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        }
        return places;
    }

    // Executed after the complete execution of doInBackground() method
    @Override
    protected void onPostExecute(List<HashMap<String, String>> list) {



        for (int i = 0; i < list.size(); i++) {
            HashMap<String, String> hmPlace = list.get(i);
            double lat = Double.parseDouble(hmPlace.get("lat"));
            double lng = Double.parseDouble(hmPlace.get("lng"));

        }
    }
}

public class Place_JSON {

    /**
     * Receives a JSONObject and returns a list
     */
    public List<HashMap<String, String>> parse(JSONObject jObject) {

        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("results");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }

    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> place = null;

        /** Taking each place, parses and adds to list object */
        for (int i = 0; i < placesCount; i++) {
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject) jPlaces.get(i));
                placesList.add(place);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return placesList;
    }

    /**
     * Parsing the Place JSON object
     */
    private HashMap<String, String> getPlace(JSONObject jPlace) {

        HashMap<String, String> place = new HashMap<String, String>();
        String placeName = "-NA-";
        String vicinity = "-NA-";
        String latitude = "";
        String longitude = "";
        String reference = "";

        try {
            // Extracting Place name, if available
            if (!jPlace.isNull("name")) {
                placeName = jPlace.getString("name");
            }

            // Extracting Place Vicinity, if available
            if (!jPlace.isNull("vicinity")) {
                vicinity = jPlace.getString("vicinity");
            }

            latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
            reference = jPlace.getString("reference");

            place.put("place_name", placeName);
            place.put("vicinity", vicinity);
            place.put("lat", latitude);
            place.put("lng", longitude);
            place.put("reference", reference);

            map1=new HashMap<String, String>();
            map1.put("Name",placeName);
            map1.put("Vicinity",vicinity);
            arr.add(map1);

            Log.w("MainActivity",placeName+";"+vicinity);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return place;
    }
}

这里我从HashMap<String, String> getPlace(JSONObject jPlace)获取数据并设置为适配器。

这个适配器我在Oncreate中设置为listview。

  

适配器类

public class MyAdapter extends BaseAdapter {
    ArrayList<HashMap<String, String>> names;
    int data;
    Context ctxt;
    LayoutInflater inflater;

    public MyAdapter (Context c, int nes, ArrayList<HashMap<String, String>> enj){
        this.ctxt = c;
        this.data = nes;
        this.names = enj;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return names.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return names.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        // TODO Create the cell (View) and populate it with an element of the array
        ViewHolder holder = new ViewHolder();
        if (convertView == null) {
            convertView = LayoutInflater.from(ctxt).inflate(data, viewGroup);
            holder.nam = (TextView) convertView . findViewById (R.id.name);
            holder.vic = (TextView) convertView . findViewById (R.id.vicinity);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView . getTag ();
        }

        holder.nam.setText(names.get(position).get("Name"));
        holder.vic.setText(names.get(position).get("Vicinity"));
        return convertView;
    }
    class ViewHolder {
        TextView nam,vic;
    }
}

这里我无法在listview中显示数据。请帮助我。

2 个答案:

答案 0 :(得分:1)

一旦“arr”发生变化,我们需要通知适配器数据集已更改。在ParserTask的onPostExecute中,添加以下行

adapter.notifyDataSetChanged();

答案 1 :(得分:0)

尝试使用:

而不是

  @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return names.get(arg0);
    }

使用

@Override

    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }