【问题标题】:How to Change order of List view's Items according to some Specific input如何根据某些特定输入更改列表视图项目的顺序
【发布时间】:2017-01-31 07:32:05
【问题描述】:

我想根据与任何列表视图项目内容匹配的特定输入字符串更改列表视图项目的顺序,并且该项目位于列表视图的顶部。我已经很努力了,但到现在都没有成功。如果有其他问题请询问。

这是从服务器获取数据的代码:

这里 date2 是我要比较的字符串输入

    private void caladata() {

        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(false);

        // Volley's json array request object
        StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
                new Response.Listener < String > () {
                    @Override
                    public void onResponse(String response) {
                        //                        Log.d(TAG, response.toString());
                        //                        hidePDialog();
                        JSONObject object = null;
                        try {
                            object = new JSONObject(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        JSONArray jsonarray = null;

                        try {
                            jsonarray = object.getJSONArray("Table");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Calenndar_Model movie = new Calenndar_Model();
                        for (int i = 0; i < jsonarray.length(); i++) {
                            try {
                                JSONObject obj = jsonarray.getJSONObject(i);

                                movie.setUserid(obj.getString("userid"));
                                movie.setHost(obj.getString("eventname"));

                                String str = obj.getString("eventdate").replaceAll("\\D+","");
                                String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
                                DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                                timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));

                                Date time = new Date(Long.parseLong(upToNCharacters));
//                                System.out.println(time);
                                movie.setDate(String.valueOf(timeZoneFormat.format(time)));
                                movie.setColor(obj.getString("eventcolor"));
                                movie.setAutoid(obj.getString("autoid"));

//                                Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
                                int index=calList.indexOf(date2);
                                calList.add(movie);
                                calList.remove(date2);
                                calList.add(0, movie);


                            }  catch (JSONException e) {
                                // Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                            }

                        }



                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
//                        listView.smoothScrollToPositionFromTop(selectedPos,0,300);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //                VolleyLog.d(TAG, "Error: " + error.getMessage());
                //                hidePDialog();

            }
        }) {
            @Override
            protected Map < String, String > getParams() {
                Map < String, String > params = new HashMap < String, String > ();
                params.put("clientid", get1);
                return params;
            }
        };
        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }

这是我的适配器类:

public class CalendarListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Calenndar_Model> movieList;

    public CalendarListAdapter(Activity activity, List<Calenndar_Model> movieList) {
        this.activity = activity;
        this.movieList = movieList;
    }

    public void swapList(List<Calenndar_Model> movieList) {
        this.movieList = movieList;
        notifyDataSetChanged();
    }

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

    @Override
    public Object getItem(int location) {
        return movieList.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.calendar_listrow, null);

        ImageView serial = (ImageView) convertView.findViewById(R.id.serial);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView date1 = (TextView) convertView.findViewById(R.id.date1);

        title.setText(movieList.get(position).getHost());
        date1.setText(movieList.get(position).getDate());


        return convertView;
    }

}

模型类:

public class Calenndar_Model {
    private String host, date,userid,color,autoid;

    //private double rating;

public Calenndar_Model() {
}

public Calenndar_Model(String host,String date,String userid,String color,String autoid) {
    this.host = host;
    this.date = date;
    this.userid = userid;
    this.color = color;
    this.autoid = autoid;

}

public String getHost() {
    return host;
}

public void setHost(String host) {
    this.host = host;
}

public String getDate() {

    return date;
}
public void setDate(String date) {

        this.date = date;
}

public String getUserid() {
    return userid;
}

public void setUserid(String userid) {
    this.userid = userid;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

public String getAutoid() {
    return autoid;
}

public void setAutoid(String autoid) {
    this.autoid = autoid;
}

}

【问题讨论】:

    标签: java android listview android-adapter android-json


    【解决方案1】:

    更新:我发现date2 的用法(变量的真实名称,而不是您在描述中提到的data2)。 您只需对您的List&lt;Calenndar_Model&gt; 进行排序:

    private void caladata() {
    
        // showing refresh animation before making http call
        swipeRefreshLayout.setRefreshing(false);
    
        // Volley's json array request object
        StringRequest stringRequest = new StringRequest(Request.Method.POST, CALENDAR_DATA,
                new Response.Listener < String > () {
                    @Override
                    public void onResponse(String response) {
                        //                        Log.d(TAG, response.toString());
                        //                        hidePDialog();
                        JSONObject object = null;
                        try {
                            object = new JSONObject(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        JSONArray jsonarray = null;
    
                        try {
                            jsonarray = object.getJSONArray("Table");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
    
                        calList = new ArrayList<>();
    
                        for (int i = 0; i < jsonarray.length(); i++) {
                            try {
                                JSONObject obj = jsonarray.getJSONObject(i);
    
                                Calenndar_Model movie = new Calenndar_Model();
                                movie.setUserid(obj.getString("userid"));
                                movie.setHost(obj.getString("eventname"));
    
                                String str = obj.getString("eventdate").replaceAll("\\D+","");
                                String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
                                DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                                timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
    
                                Date time = new Date(Long.parseLong(upToNCharacters));
                                //System.out.println(time);
                                movie.setDate(String.valueOf(timeZoneFormat.format(time)));
                                movie.setColor(obj.getString("eventcolor"));
                                movie.setAutoid(obj.getString("autoid"));
    
                                //Toast.makeText(getApplicationContext(), "server data respone", Toast.LENGTH_LONG).show();
                                calList.add(movie);
    
                            }  catch (JSONException e) {
                                // Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                            }
    
                        }
    
                        //sort calList list 
                        Comparator<Calenndar_Model> calendarModelComparator = new Comparator<Calenndar_Model>() {
                            @Override
                            public int compare(Calenndar_Model cm1, Calenndar_Model cm2) {
                                boolean firstContainsData2 = calendarModelContainsData2(cm1);
                                boolean secondContainsData2 = calendarModelContainsData2(cm2);
                                if (firstContainsData2 && secondContainsData2) {
                                    return 0;
                                } else if (firstContainsData2) {
                                    return -1;
                                } else if (secondContainsData2) {
                                    return 1;
                                } else return cm2.getData().compareTo(cm1.getData());
                            }
    
                            private boolean calendarModelContainsData2(Calenndar_Model cm) {
                                 return cm.getData().contains(data2);
                            }
                        };
                        Collections.sort(calList, calendarModelComparator);
    
    
                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.swapList(calList);
                        //listView.smoothScrollToPositionFromTop(selectedPos,0,300);
    
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //                VolleyLog.d(TAG, "Error: " + error.getMessage());
                //                hidePDialog();
    
            }
        }) {
            @Override
            protected Map < String, String > getParams() {
                Map < String, String > params = new HashMap < String, String > ();
                params.put("clientid", get1);
                return params;
            }
        };
        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(stringRequest);
    }
    

    【讨论】:

    • 它返回每个列表视图中的最后一个 json 值 @Max.i.e.它在整个列表中显示相同和错误的值。
    • 您的原始代码有错误。这行Calenndar_Model movie = new Calenndar_Model(); 必须在循环内,因为您必须为每一行创建新实例,否则您只需多次修改具有不同值的同一对象的字段。我在回答中修正了这个错误。
    • 现在我粘贴这一行 Calenndar_Model movie = new Calenndar_Model(); JSONObject 下 obj = jsonarray.getJSONObject(i);(for 循环下)
    • 好的,它可以工作,但需要的项目在底部,但我需要它在顶部
    • 我再次修改了我的答案。看看吧。
    【解决方案2】:
    Suppose date2 is eventname you want to compare.
    if(date2.equals(movie.getHost())
    {
        // store Movie object on index 0, if it equals date2
        calList.add(0, movie);
    }
    else
    {
        calList.add(movie);
    }
    
    Remove the Following Lines from caladata().
    int index=calList.indexOf(date2);
    calList.add(movie);
    calList.remove(date2);
    calList.add(0, movie);
    

    【讨论】:

    • 必需值在底部,但我需要它在顶部
    猜你喜欢
    • 2014-07-08
    • 1970-01-01
    • 2021-12-15
    • 2015-05-24
    • 2020-08-07
    • 1970-01-01
    • 2013-07-18
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多