根据数据更改listview项目的文本颜色

时间:2015-08-04 16:32:14

标签: java

我正在尝试将一组项目加载到MySQL的listview中。根据数据,如果' no_sms_service' = 1然后我想只更改该项目的背景颜色。我试图覆盖视图,但它并没有专门更改项目。它会更改所有项目。我做错了什么?

public void loadReservations() {

    ListView lv = (ListView) this.findViewById(R.id.waitingList);

    String url = "jdbc:mysql://"+dbURL+":"+dbPort+"/"+dbDatabase+"";
    String user = dbUser;
    String pass = dbPass;

    List<String> waitingList = new ArrayList<String>();

    try {
        StrictMode.ThreadPolicy policy =
                new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, user, pass);

        Statement st = con.createStatement();
        final ResultSet rs = st.executeQuery("SELECT cust_name, reserve_Date, Seat_prefer, reserve_people, Notes, no_sms_service FROM seat_reserve WHERE reserve_Close=0 && DATE(reserve_Date) = DATE(NOW()) ORDER BY reserve_Date ASC");
        ResultSetMetaData rsmd = rs.getMetaData();

        String result;
        while (rs.next()) {

            String myTimestamp = rs.getTimestamp(2).toString();

            DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
            Date date = inputFormat.parse(myTimestamp);

            DateFormat outputFormat = new SimpleDateFormat("hh:mm a");
            String outputString = outputFormat.format(date);


            result = "\n" +"Name:  " + rs.getString(1)
                    + "\n" + "Reservation Time:  " + outputString
                     + "\n" + "Preferred Area:  " + rs.getString(3)
                    + "\n" + "Guests:  " + rs.getString(4)
            + "\n" + "Notes:  " + rs.getString(5) + "\n";

            waitingList.add(result);

            noSMS = rs.getInt(6);

            arrayAdapter =
                    new ArrayAdapter<String>(getApplicationContext(),
                            android.R.layout.simple_list_item_1,
                            waitingList) {

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

                            View view = super.getView(position, convertView, parent);
                            TextView text = (TextView) view.findViewById(android.R.id.text1);

                            if (noSMS == 1)
                            {
                                text.setTextColor(Color.RED);
                            }
                            return view;
                        }
                    };

        }

        lv.setAdapter(arrayAdapter);

    }

    catch(Exception e)
    {
        e.printStackTrace();

    }
}

1 个答案:

答案 0 :(得分:1)

您提供的代码存在多个问题。

首先,当使用getView构造View时,它不会评估您作为数据传入的result字符串的内容。由于ResultSet是一个临时数据容器,因此您需要为正在提取的数据提供更永久的存储解决方案,以便在ListView需要更新时对其进行评估。创建以下类:

public class ListItemData {
    ListItemData(ResultSet rs) throws SQLException {
        name = rs.getString(1);
        reservationDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S").parse(rs.getTimestamp(2).toString());
        preferredArea = rs.getString(3);
        guests = rs.getString(4);
        notes = rs.getString(5);
        noSms = rs.getInt(6) == 1;
    }

    String name;
    Date reservationDate;
    String preferredArea;
    String guests;
    String notes;
    boolean noSms;
}

您还要为列表中的每个元素创建一个新的ArrayAdapter。这不是ArrayAdapter应该如何工作的! ListView只能有一个 ArrayAdapter,并且它的逻辑是通过它的getView方法在列表中的每个项目上运行。

以下内容应放在loadReservations的某处,可能在onCreate中:

// only initialize the waitingList once here, and repopulate it in loadReservations
List<ListItemData> waitingList = new ArrayList<ListItemData>();

// only create the arrayAdapter once
arrayAdapter = new ArrayAdapter<ListItemData>(getApplicationContext(),
                   android.R.layout.simple_list_item_1,
                   waitingList) {
                   @Override
                   public View getView(int position, View convertView, ViewGroup parent) {

                       View view = super.getView(position, convertView, parent);
                       TextView text = (TextView) view.findViewById(android.R.id.text1);

                       ListItemData data = getItem(position);

                       //TODO: now you have access to all the data!

                       if (data.noSms)
                       {
                           text.setTextColor(Color.RED);
                       }

                       return view;
                   }
               };

lv.setAdapter(arrayAdapter);

现在初始化繁重工作已在ListItemData的构造函数中完成,我们的loadReservations函数可以大大简化:

public void loadReservations() {

    ListView lv = (ListView) this.findViewById(R.id.waitingList);

    String url = "jdbc:mysql://"+dbURL+":"+dbPort+"/"+dbDatabase+"";
    String user = dbUser;
    String pass = dbPass;

    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, user, pass);

        Statement st = con.createStatement();
        final ResultSet rs = st.executeQuery("SELECT cust_name, reserve_Date, Seat_prefer, reserve_people, Notes, no_sms_service FROM seat_reserve WHERE reserve_Close=0 && DATE(reserve_Date) = DATE(NOW()) ORDER BY reserve_Date ASC");
        ResultSetMetaData rsmd = rs.getMetaData();

        // clear out the waitingList (instead of making a brand new one!)
        waitingList.clear();

        while (rs.next()) {
            ListItemData data = new ListItemData(rs);

            waitingList.add(data);
        }

        // this must be called to notify the list to recalculate it's view
        arrayAdapter.notifyDataSetChanged();

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

请记住,我没有编译此代码,如果您发现任何问题,请告诉我,我会更新答案。