ListView在每次单击Button时重复相同的JSON项

时间:2016-11-04 16:45:28

标签: android json listview listadapter

我的主Activity上有一个ListView,还有一个获取JSON的按钮 如果我重复按钮单击,则会向ListView添加相同的JSON元素。

如果再次单击按钮,如何清除ListView?

CustomListAdapter

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Vehicle> vehicleItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Vehicle> vehicleItems) {
        this.activity = activity;
        this.vehicleItems = vehicleItems;
    }

    @Override
    public int getCount() {
        return vehicleItems.size();
    }

    @Override
    public Object getItem(int location) {
        return vehicleItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView rating = (TextView) convertView.findViewById(R.id.rating);
        TextView genre = (TextView) convertView.findViewById(R.id.genre);
        TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        Vehicle m = vehicleItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

        // title
        title.setText(m.getTitle());

        // rating
        rating.setText("Rating: " + String.valueOf(m.getRating()));

        // genre
        String genreStr = "";
        for (String str : m.getGenre()) {
            genreStr += str + ", ";
        }
        genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
        year.setText(String.valueOf(m.getYear()));

        return convertView;
    }
}

SearchActivity

public class SearchActivity extends Activity implements View.OnClickListener {

    // Log tag
    private static final String TAG = SearchActivity.class.getSimpleName();

    // Vehicles json url
    private static final String url = "https://api.myjson.com/bins/3u7ty";
    private SweetAlertDialog pDialog;
    private List<Vehicle> vehicleList = new ArrayList<Vehicle>();
    private ListView listView;
    private CustomListAdapter adapter;
    private Button buttonGet2;


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


        buttonGet2 = (Button) findViewById(R.id.buttonGet2);
        buttonGet2.setOnClickListener(this);



    }

    private void getData() {
        listView=(ListView) findViewById(R.id.list2);
        adapter=new CustomListAdapter(this,vehicleList);
        listView.setAdapter(adapter);
        final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(true);

        // Showing progress dialog before making http request
        pDialog.show();

        // changing action bar color
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest vehicleReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        pDialog.dismissWithAnimation();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Vehicle vehicle = new Vehicle();
                                vehicle.setTitle(obj.getString("title"));
                                vehicle.setThumbnailUrl(obj.getString("image"));
                                vehicle.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                vehicle.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                vehicle.setGenre(genre);

                                // adding vehicle to vehicles array
                                vehicleList.add(vehicle);

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

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                pDialog.dismissWithAnimation();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(vehicleReq);

    }

    @Override
    public void onClick(View v) {
        getData();
    }
}

2 个答案:

答案 0 :(得分:1)

您一次又一次地将Json object的内容添加到vehicleListvehicleList仍保留旧值。然后再次从Json对象捕获值并再次将其添加到vehicleList。要摆脱这个,请清除列表:

    private void getData() {
    vehicleList.clear();
    listView=(ListView) findViewById(R.id.list2);
    adapter=new CustomListAdapter(this,vehicleList);

//rest of your code
}

答案 1 :(得分:1)

除了清除数据外,只需使该方法仅负责获取数据,而不是重复初始化适配器和列表。

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

    buttonGet2 = (Button) findViewById(R.id.buttonGet2);
    buttonGet2.setOnClickListener(this);

    // Moved these lines
    listView = (ListView) findViewById(R.id.list2);
    adapter = new CustomListAdapter(this,vehicleList);
    listView.setAdapter(adapter);


}


private void getData() {

    vehicleList.clear();  // Added this

    final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
    pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
    pDialog.setTitleText("Loading");
    pDialog.setCancelable(true);