简体   繁体   English

检查我的值是否存在于数据库中?

[英]Check if my values exist in database or not?

I read some data from server and save them into database . 我从服务器读取一些数据并将其保存到数据库中。 I want to check if there is any new data or not , so i request to server and get 10 post (my post have id,title, image,..) .Now I want to compare my 10 new post title that exit in my whole database . 我想检查是否有任何新数据,所以我请求服务器并获得10个帖子(我的帖子具有ID,标题,图像等)。现在,我想比较我退出的10个新帖子标题整个数据库。 I do like this: I make ArrayList() to get data from server and to it : 我喜欢这样:我使ArrayList()从服务器获取数据并发送到它:

   List<Post> check = new ArrayList<Post>();   

and this is my database value 这是我的数据库价值

   List<dbSample> txtsSave = new ArrayList<>();

and now check like this . 现在检查这样。 (I check the title together ) . (我一起检查标题)。

         if (database.exists()) {
        for (int i = 0; i < check.size(); i++) {
            for (int j = 0; j < txtsSave.size(); j++) {
                if (check.get(i).getTitle().equals(txtsSave.get(j).getTitle())) {
                  Log.i("NewData","No new Data");
                } else {
                    Log.i("NewData"," new Data");
                }
            }
        }
    }

but I can see both Log in locat .How I can compare these together? 但是我可以同时看到“登录locat”。如何将它们进行比较? For example my txtsave size is 30 and my check size is 10 . 例如,我的txtsave大小为30而我的支票大小为10。 any suggestion? 有什么建议吗?

do like this: 这样做:

for (int i = 0; i < check.size(); i++) {
            for (int j = 0; j < txtsSave.size(); j++) {
                if (check.get(i).getTitle().equals(txtsSave.get(j).getTitle())) {
                  Log.i("NewData","No new Data");
                  break;
                } 
                if(j == (txtsSave.size() - 1))  {
                    Log.i("NewData"," new Data");
                }
            }
        }

I think the best way for you is to use .contains(object) in list like this: 我认为对您来说最好的方法是在列表中使用.contains(object),如下所示:

 for (int i = 0; i < check.size(); i++) {
      if(txtsSave.contains(check.get(i)){
                Log.i("NewData","No new Data");
                txtsSave.add(check.get(i));
            } else {
                Log.i("NewData"," new Data");
            }  
  }

you can check check if a object exist in database by: 您可以通过以下方法检查数据库中是否存在对象:

    public boolean hasObject(String string) {
    String selectString = "SELECT * FROM " + MY_TABLE_NAME + " WHERE column_name=?";

    Cursor cursor = myDatabase.rawQuery(selectString, new String[]{string});

    boolean hasObject = false;
    if (cursor.moveToFirst()) {
      hasObject = true;

    }

    cursor.close();    
    return hasObject;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM