2017-06-26 65 views
-1

我的代码是从sqlite数据库制作arraylist,就像这样。的ArrayList从arraylist中获取字符串

例如: example of arraylist

因此,举例来说,如果用户希望看到从我的列表中的所有人地址为“示例2”,我该怎么办呢代码?如果有帮助,即时将结果打印到gridview。我能够在那里打印每一个数据,但我希望它可以通过用户选择进行过滤。


到目前为止,我做了一个模型类,它有所有信息的getter和setter。我也有一个适配器,可以在我的MainActivity中将所需的数据打印到我的对象中。问题是我想在数据显示之前过滤数据,所以我认为它必须在我的适配器中进行。但我不知道如何?

+0

请告诉我们你到目前为止试过的东西。 –

+1

你没有提供代码,所以这里是一个普通的答案:查询地址为“example2”的条目带有SQL-“select”语句,所以你只能得到匹配的条目,而不是所有条目。 – mumpitz

回答

0

如果你想在SQL中编写它,那么它将作为Select * from arraylist where address = "example2"。请提及您想要编码的语言?

0

我了解你想从你的用户数据库中收集的所有数据到一个列表:

public static List<User> getUsers() { 
      List<User> allUsers = new ArrayList<User>(); 
      DataSource ds = MyDataSourceFactory.getMySQLDataSource(); 
      Connection con = null; 
      PreparedStatement stmt = null; 
      ResultSet rs = null; 
      try { 
       con = open(con, ds); 
       String SQL = "SELECT id,name,address from YOUR DATA TABLE; 
       stmt = con.prepareStatement(SQL); 
       rs = stmt.executeQuery(); 
       while (rs.next()) { 
        int i = rs.getInt("id"); 
        String name = rs.getString("name"); 
        String address = rs.getString("address"); 
        User us = new Location(i,name,address); 
        locs.add(loc); 
       } 
      } catch (SQLException e) { 
       e.printStackTrace(); 
      } finally { 
       close(stmt, con, rs); 
      } 
      return res; 
     } 

这两种方法用于打开和关闭与数据库的连接:

public static Connection open(Connection con, DataSource ds) 
        throws SQLException { 
       try { 
        con = ds.getConnection(); 
       } catch (SQLException e) { 
        e.printStackTrace(); 
       } 
       if (con == null) { 
        throw new SQLException("cannot connect to database!"); 
       } 
       return con; 
      } 

public static void close(PreparedStatement preparedStatement, 
        Connection con, ResultSet rs) { 
       try { 
        if (rs != null) 
         rs.close(); 
        if (preparedStatement != null) 
         preparedStatement.close(); 
        if (con != null) 
         con.close(); 
       } catch (SQLException e) { 
        e.printStackTrace(); 
       } 
      } 
0

从代码中过滤数据并不是一个好主意,但可以在sql查询中完成。 喜欢这个:

SELECT id, name, address FROM table WHERE address = 'example2'