如何在Android中检查数据库中是否已存在Id?

时间:2013-05-13 05:44:28

标签: android android-sqlite

我的问题是,我创建了一个应用程序,我需要下载文档,我想要的是比较值/ Id是否已经存在于数据库中,如果存在则复制并替换现有文件。我将文档ID作为唯一或主键。

我阅读了一些教程,但没有任何好处。

这是我的代码:

         Intent i = new Intent();  
         i.putExtra("item_name", item_name.folder_name);  
         i.putExtra("item_url", item_url.url);  
         i.putExtra("ID", DocumentID.ID);  
         String doc_Id = i.getStringExtra("ID");  
         String name = i.getStringExtra("item_name");  
         String url = i.getStringExtra("item_url");  
         i.getStringExtra("item_type");  
         database = new DMS_Database(Files_Folders_Activity.this);  
         database.Save_Doc(doc_Id, name, url);  
         database.close();  

       // check here If Doc_Id already exist then show Toast, 
       // But how to perform function like already exist????

    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));  
         request.setTitle(name);  
         // in order for this if to run, you must use the android 3.2 to compile your app  
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)   
           {  
            request.allowScanningByMediaScanner();  
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
           }  
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/Downloads", name);  
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);  
            manager.enqueue(request);  
          }  
        }  
     }  
    });  
  }  

数据库:

public void Save_Doc(String Id, String doc_name, String url)
{   
  SQLiteDatabase db = this.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put(DOCUMENT_ID, Id);
  values.put(DOCUMENT_NAME, doc_name);
  values.put(DOCUMENT_URL, url);
  db.insert(DOCUMENT_TABLE, null, values);
}
public Cursor Get_Doc(String rowId)
{
  SQLiteDatabase db = this.getReadableDatabase();
  //String[] Columans = new String[] {DOCUMENT_ID, DOCUMENT_NAME, DOCUMENT_URL};
  Cursor c = db.rawQuery("SELECT DOCUMENT_ID FROM " + DOCUMENT_TABLE + "WHERE     DOCUMENT_ID = ?", new String[]{String.valueOf(rowId)});
  return c;
}
  //Getting All Contacts
public List<FolderList> getAllDoc() {
   List<FolderList> DocList = new ArrayList<FolderList>();
   // Select All Query
   String selectQuery = "SELECT  * FROM " + DOCUMENT_TABLE;
   SQLiteDatabase db = this.getWritableDatabase();
   Cursor cursor = db.rawQuery(selectQuery, null);
   // looping through all rows and adding to list
   if (cursor.moveToFirst()) {
       do {
       FolderList document = new FolderList();
       document.setID(cursor.getString(0));
  //     document.setName(cursor.getString(1));
  //     document.setUrl(cursor.getString(2));
       // Adding Doc to list
       DocList.add(document);
   } while (cursor.moveToNext());
   }
   return DocList;      // return Doc list
  }
public void Delete_Doc(String Id) 
{
  SQLiteDatabase db = this.getReadableDatabase();
  db.delete(DOCUMENT_TABLE, DOCUMENT_ID + "=?", new String[]{String.valueOf(Id)});
}
public void update_Doc(String Id, String name, String url)
{
  SQLiteDatabase db = this.getWritableDatabase();
  ContentValues updatenote = new ContentValues();
  updatenote.put(DOCUMENT_ID, Id);
  updatenote.put(DOCUMENT_NAME, name);
  updatenote.put(DOCUMENT_URL, url);
  db.update(DOCUMENT_TABLE, updatenote, DOCUMENT_ID + "=?" , new String[]    {String.valueOf(Id)});
}
  }

2 个答案:

答案 0 :(得分:1)

您可以在DataBase(ourDatabase)中实现这样的功能。

public boolean dididExist(int id) {

        String[] allColumns = { DOCUMENT_ID };
        Cursor cursor = ourDatabase.query(DOCUMENT_TABLE, allColumns,
                DOCUMENT_ID + " = " + id, null, null, null,
                null);
        cursor.moveToFirst();
        boolean retBool = false;
        if (!cursor.isAfterLast()) {

            retBool = true;

        }
        return retBool;
    }

答案 1 :(得分:0)

你可以做的是执行一个带有你要检查的id的插入查询,它会抛出异常,在我的情况下,我通过创建一个已经可用的表来检查表的可用性。这不是一个好习惯,但这很有效。

    public boolean isEmployeeTableAvailable(Context cx) {
String employeeTableCreate = ""create table "
            + TABLENAME + "("
            + KEY_ROWID+" integer primary key autoincrement,"
            + KEY_NAME+" text not null);";
            try {
                MyTimeDB.execSQL(employeeTableCreate);
                MyTimeDB.close();
                return true;
            } catch (Exception ex) {
                Log.w("MyTime Database", "Employee Table Availability Check Exception");
                return false;
            }
        }