首页 > 解决方案 > 如何检查sqlite数据库中是否存在记录?

问题描述

我的问题是:如何检查记录是否存在?

描述是:我有两个片段

1- Main Fragment==> 包含recyclerview,在这个rec​​yclerview中数据来自firestore,当用户点击recyclerview单项时,将这些数据保存到sqlite数据库中。

2- Orders Fragment==> 包含recyclerview,在这个rec​​yclerview中数据来自从主片段保存的sqlite。

我关于当我在按回堆栈时返回主片段时的问题,我想检查数据是否已经存储在 sqlite 中,如果存在,则获取产品数量并将其替换为 recyclerview 中单个项目的主片段(产品数量 textview 是禁用,如果发现记录结束它并替换来自 sqlite 的值(如果记录存在)。

标签: javaandroidandroid-fragmentsandroid-sqlite

解决方案


我不太了解您的问题,但我认为您正在尝试检查是否有任何数据插入 SQLite 数据库。

为了做到这一点,我假设您已经在您DatabaseHelper.class的标准流程中定义了您的功能,因为您只是在询问如何检查是否有任何数据。您需要在您的助手类中使用一个函数来检查是否有任何数据并从您的MainFragment.java类中调用它。

你没有提供任何代码片段,所以我只是假设他们的声明。

假设您有一个活动,MainFragment.java并且layout_mainfragment.xml

在你的DatabaseHelper.class

public String checkRecord(String productName){
        this.db = getWritableDatabase();
        //Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME1,productName);
        String table = "record_table";
        String[] columns = {"product_name","product_quantity"};
        String selection = "product_name =?";
        String[] selectionArgs = {productName};
        String groupBy = null;
        String having = null;
        String orderBy = null;
        String limit = null;
        Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
        return cursor.getString(cursor.getColumnIndex("product_quantity"));
    }

如果找到任何索引,这应该返回函数参数为的任何产品名称的产品数量。

在你的layout_mainfragment.xml

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/mainFragment_recordCount"
    android:visibility="gone"/>

然后在你的MainFragment.java课上:

TextView recordCount;
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marker_specification);
        recordCount = (TextView) findViewById(R.id.mainFragment_recordCount);
        DatabaseHelper helper = new DatabaseHelper(mContext);
        String productRecord = helper.checkRecord("productname");
        //checkRecord will return quantity if index found and give productRecord that value.
        if(!productRecord.equals("")){
                recordCount.setVisibility(View.VISIBLE);
                recordCount.setText(productRecord);
                // If not empty, make TextView visible and set it's text to that quantity.
        }

         ....

        //(Your onCreate goes on)
         ....


}

推荐阅读