在SQLite中添加新记录时,检查此名称是否已存在于Android中

smdncfj3  于 2023-05-15  发布在  Android
关注(0)|答案(2)|浏览(113)

我有SQLite数据库,我在那里保存数据,我想为每个新的条目检查数据库,如果已经存在这个记录,如果是,给我一个吐司词,如果没有插入数据库中的记录。我想检查搜索URL和本地URL是否存在于数据库中。
下面是代码。

public class BookmarkDB extends SQLiteOpenHelper {
    public static final String DBNAME = "bookmarks.db"; // The name of the database file
    public static final int DBVERSION = 1;  // The Database version

    public static final String TBL_BOOKMARK = "bookmark";
    public static final String COL_ID = BaseColumns._ID; // equates to _id
    public static final String COl_NAME = "name";
    public static final String COl_HIDDEN = "hidden";
    public static final String COL_ICON = "icon";
    public static final String COL_NATIVEURL = "nativeurl";
    public static final String COL_SEARCHURL = "searchurl";

    SQLiteDatabase mDB;
    Context mContext;

    public BookmarkDB(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // The SQL to be used to create the table
        String crt_bookmark_tbl_sql = "CREATE TABLE IF NOT EXISTS " + TBL_BOOKMARK + "(" +
                COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COl_NAME + " TEXT, " +
                COl_HIDDEN + " INTEGER, " +
                COL_ICON + " TEXT, " +
                COL_NATIVEURL + " TEXT," +
                COL_SEARCHURL + " TEXT" +
                ")";
        db.execSQL(crt_bookmark_tbl_sql); // CREATE THE TABLE

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXISTS " + DBNAME);
        onCreate(db);
    }

    public long addBookmark(long id, String name, boolean hidden, String icon, String nativeurl, String searchurl) {
        ContentValues cv = new ContentValues();

                    cv.put(COl_HIDDEN,hidden);
                    cv.put(COl_NAME,name);
                    cv.put(COL_ICON,icon);
                    cv.put(COL_NATIVEURL,nativeurl);
                    cv.put(COL_SEARCHURL,searchurl);
                  return  mDB.insert(TBL_BOOKMARK, null, cv);

        // uses the convenience insert method that builds the SQL
    }
    public ArrayList<Bookmark> getAllBookmarks() {
        ArrayList<Bookmark> rv  = new ArrayList<>();
        Cursor csr = mDB.query(TBL_BOOKMARK,null,null,null,null,null, null);

        while (csr.moveToNext()) {
            Bookmark b = new Bookmark();
            b.setId(csr.getString(csr.getColumnIndex(COL_ID)));
            int Icon = csr.getInt(csr.getColumnIndex(COL_ICON));
            String name = csr.getString(csr.getColumnIndex(COl_NAME));
            String searchUrl = csr.getString(csr.getColumnIndex(COL_SEARCHURL));
            b.setIcon(Icon);
            b.setName(name);
            b.setSearchUrl(searchUrl);
            b.setViewType(csr.getInt(csr.getColumnIndex(COl_NAME)));
            b.setNativeUrl(csr.getString(csr.getColumnIndex(COL_NATIVEURL)));
            rv.add(b);
        }
        return rv;

    }

    public void deleteBookmark(int id, String name){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM " + TBL_BOOKMARK + " WHERE "
                + COL_ID + " = '" + id + "'" +
                " AND " + COl_NAME + " = '" + name + "'";

        Log.d("Deleted", "Item" + query);
        db.execSQL(query);
    }

}

保存新记录的代码

public class ActivityChangeBookmark  extends AppCompatActivity {
    private ArrayList<String> listItems = new ArrayList<String>();
    private RecyclerView recyclerView;
    Button saveBookmark, cancelBookmark;
    TextView name, url;
    ImageView icon, mIcon;
    EditText mName, mUrl, mID;
    public static final String Save_Bookmark = "Save_Bookmark";
    static final String xmlFileName = "bookmarks.xml";
    String Url, Name;
    Integer Id;
    MyAdapter myAdapter;
     BookmarkDB bookmarkDB;
     ButtonRobotoMedium removeBookmark, sendToHomeScreen;
    ArrayList<Bookmark> arrayList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_bookmark);
        saveBookmark = findViewById(R.id.btnSave);
        name = findViewById(R.id.tvNameEdit);
        url = findViewById(R.id.tvURLEdit);
        recyclerView = findViewById(R.id.myRecyclerView);
        icon = findViewById(R.id.ivFavIcon);
        mName = findViewById(R.id.etNameEdit);
        mUrl = findViewById(R.id.etURLEdit);
        cancelBookmark = findViewById(R.id.btnCancel);
        removeBookmark = findViewById(R.id.btnRemove);
        sendToHomeScreen = findViewById(R.id.btnAddIconToDeviceScreen);
        name.setVisibility(View.GONE);
        url.setVisibility(View.GONE);
        bookmarkDB = new BookmarkDB(getApplicationContext());
        Intent intent = getIntent();
        myAdapter = new MyAdapter(getApplicationContext(), arrayList);

        Bundle extras = intent.getExtras();
        if (extras != null) {
            Url = intent.getExtras().getString("Url");
            Name = intent.getExtras().getString("Name");
            Id = intent.getExtras().getInt("ID");

            Bitmap bitmap = intent.getExtras().getParcelable("Image");
            mName.setText(Name);
            mUrl.setText(Url);
            Log.d("Id", "TakenId" + Id + Name + Url);

            icon.setImageBitmap(bitmap);
            removeBookmark.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("DeletedItem", "Test" + Id + Name);
                    bookmarkDB.deleteBookmark(Id, Name);
                    myAdapter.notifyDataSetChanged();
                    finish();
                }
            });
        }
         else {
            removeBookmark.setVisibility(View.GONE);
            sendToHomeScreen.setVisibility(View.GONE);
            icon.setImageResource(R.drawable.user_bookmark);
            mName.setText("");
            mUrl.setText("");
        }


        saveBookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                myAdapter.notifyDataSetChanged();
                finish();
                }
        });

        cancelBookmark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myAdapter.notifyDataSetChanged();
                finish();
            }
        });
    }

    public void saveData() {
        Random r = new Random();
        int low = 14;
        int high = 100;
        int result = r.nextInt(high-low) + low;
        bookmarkDB.addBookmark(result, mName.getText().toString(), false, "", mUrl.getText().toString(), "http://" + mUrl.getText().toString());
    }
}
afdcj2ne

afdcj2ne1#

最简单的方法是使用UNIQUE,从而使列/复合列,这将导致约束冲突,从而不允许插入行。
不太清楚的是你指的是什么专栏。标题显示为name列,在这种情况下,您可以将COl_NAME + " TEXT, " +更改为COl_NAME + " TEXT UNIQUE, " +
文本how声明 I wan 't to check if the search url and native url exists or not in the DB. 这意味着只有当两者的组合存在时,您才不想添加行,但是只有一个列已经存在的组合应该被添加。
假设这一点,那么您可以添加一个复合UNIQUE约束,在这种情况下,您可以添加行

", UNIQUE(" + COL_NATIVEURL + "," + COL_SEARCHURL + ")" +

这将添加到COL_SEARCHURL + " TEXT" +行之后
如果不想添加行(如果存在),则可以使用以下命令将UNIQUE添加到列定义中:-

COL_NATIVEURL + " TEXT UNIQUE," +
            COL_SEARCHURL + " TEXT UNIQUE" +
  • 请注意,如果没有添加行,addBookMark将返回-1。

如果上面的方法不适用,并且你想检查一个列,那么你可以基于BookmarkDB类中的以下方法进行检查:

public boolean ifNativeUrlExists(String nativeUrl) {

    boolean rv = false;
    String whereclause = COL_NATIVEURL + "=?";
    String[] whereargs = new String[]{nativeUrl};
    Cursor csr = mDB.query(TBL_BOOKMARK,null,whereclause,whereargs,null,null, null)
    if (csr.getCount() > 0) {
        rv = true;
    }
    csr.close();
    return rv;
}

你可以使用类似这样的东西来使用它:

public void saveData() {
    Random r = new Random();
    int low = 14;
    int high = 100;
    int result = r.nextInt(high-low) + low;
    if (!bookmarkDB.ifNativeUrlExists(mUrl.getText().toString())) {
        bookmarkDB.addBookmark(result, mName.getText().toString(), false, "", mUrl.getText().toString(), "http://" + mUrl.getText().toString());
    } else {
         ..... code to indicate not added
    }
}
  • 显然,这可以很容易地适用于其他列。

请注意,以上是原则性代码,尚未测试或运行,因此可能包含一些错误。

g2ieeal7

g2ieeal72#

我是这样做的,试试看:1-在SQLite数据库中创建名称UNIQUE
2-将此布尔方法添加到数据库助手类:

public boolean checkNameExist(String p_name){
        String[] column = {"p_name"};
        db = openDatabase();
        
        String selection = "p_name=?";
        String[] selectionArgs = {p_name};
        
        Cursor cursor = db.query(TABLE_NAME, column, selection, selectionArgs, null, null, null);
        int count = cursor.getCount();
        
        cursor.close();
        close();
        
        if(count > 0){
            return true;
            } else {
            return false;
        }
    }

3-在您的Activity中添加此in action按钮侦听器:

Db_Helper myDB = new Db_Helper(AddActivity.this);
            if (!myDB.checkNameExist(name_input.getText().toString().trim())) {
          myDB.addName(  name_input.getText().toString().trim());   
            }else {
                Toast.makeText(this, "Name Already exist!", Toast.LENGTH_SHORT).show();
                }

4-别忘了加上:

.toString().trim()

相关问题