Android Studio SQLite数据库资产放入回收视图,但仅显示特定数据

cetgtptt  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(136)

我刚接触Android Studio,只用了两个月,用Java编程有一年了。
目前,我正在开发一个宠物收养应用程序,目标是让用户回答四个关于他们想要的宠物类型的问题,并根据复选框显示与用户想要的宠物相匹配的宠物列表。
我想我可以使用SQLite作为添加宠物的数据库,然后当用户选中复选框并提交时,应用程序可以检查数据库,并将宠物的姓名、年龄和性别发送到循环视图中。
我发现这并不像我想象的那么容易,我可以使用一些外部建议,因为我只有两个多星期的时间来做这件事。以下是我目前掌握的情况:
Main Activity

DataBaseHelper

import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DBHelper extends SQLiteAssetHelper {

    public static final String DBNAME = "PetAdoption.db";
    public static final int DBVERSION = 1;

    public DBHelper(Context context) {

        super(context,DBNAME,null,DBVERSION);
    }
}

数据库访问

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseAccess {

    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    private static DatabaseAccess instance;

    /**
     * Private constructor to avoid object creation from outside classes.
     *
     * @param context
     */
    private DatabaseAccess(Context context) {
        this.openHelper = new DBHelper(context);
    }

    /**
     * Return a singleton instance of DatabaseAccess.
     *
     * @param context the Context
     * @return the instance of DatabaseAccess
     */
    public static DatabaseAccess getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseAccess(context);
        }
        return instance;
    }

    /**
     * Open the database connection.
     */
    public void openDatabase() {

        this.database = openHelper.getWritableDatabase();

    }

    public SQLiteDatabase getWritableDatabase() {

        return openHelper.getWritableDatabase();

    }

    public SQLiteDatabase getReadableDataBase() {
        return openHelper.getReadableDatabase();
    }

    /**
     * Close the database connection.
     */
    public void closeDatabase() {
        if (database != null) {
            this.database.close();
        }
    }
}

主要活动

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private Context context;
    private String query;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(context);
        databaseAccess.openDatabase();
        Cursor cursor = databaseAccess.getWritableDatabase().rawQuery(query, null);

    }
}

我知道我仍然需要一个Recylerview的模型和特定的代码来提取与复选框匹配的宠物,但我不确定我的方向是否正确。任何建议都会很有帮助。

2vuwiymt

2vuwiymt1#

任何建议都会很有帮助。

  • 或许可以考虑以下几点。*

首先,演示创建数据库并加载一些数据(为了方便起见),而不是拥有资产(预打包的数据库)。
由于Schama不可用,这是编造的(这个答案是关于原理的,而不是与实际数据相反的,因为没有实际数据)。
表格名为宠物,它有5列:-

  • _id**(唯一标识一行的id列的Android标准)
  • 键入**作为宠物类型(狗、猫……)
  • 品种**,例如阿尔萨斯
  • 生活方式**新生儿、老人……
  • 成本**

加载了一些数据(在onCreate方法中,注意而不是SQLiteAssetHelper使用了股票SQliteOpenHelper*,因为没有要加载的资产*)
所以纯粹为了方便起见,DBHelper是:

public class DBHelper extends SQLiteOpenHelper /* changed for simulation of asset */ {

   public static final String DBNAME = "PetAdoption.db";
   public static final int DBVERSION = 1;

   private static String[] testdata1 = new String[]{"Dog","Alsatian","old","100"};
   private static String[] testdata2 = new String[]{"Dog","Golden Retriever","newborn","200"};
   private static String[] testdata3 = new String[]{"Cat","Siamese","young","150"};
   private static String[] testdata4 = new String[]{"Cat","Burmese","mature","110"};
   private static String[] testdata5 = new String[]{"Cat","Persian","old","75"};
   private static String[] testdata6 = new String[]{"Dog","Corgi","mature","300"};

   public DBHelper(Context context) {
      super(context,DBNAME,null,DBVERSION);
   }

   /* ADDED to simulate getting data from asset */
   @Override
   public void onCreate(SQLiteDatabase sqLiteDatabase) {
      sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS pet (" +
              BaseColumns._ID + " INTEGER PRIMARY KEY" +
              "," + "type TEXT" +
              "," + "breed TEXT" +
              "," + "lifestage TEXT" +
              "," + "cost REAL" +
              ")"
      );
      insertTestData(sqLiteDatabase,testdata1);
      insertTestData(sqLiteDatabase,testdata2);
      insertTestData(sqLiteDatabase,testdata3);
      insertTestData(sqLiteDatabase,testdata4);
      insertTestData(sqLiteDatabase,testdata5);
      insertTestData(sqLiteDatabase,testdata6);

   }

   private void insertTestData(SQLiteDatabase db, String[] data) {
      if (data.length != 4) return;
      ContentValues cv = new ContentValues();
      cv.put("type",data[0]);
      cv.put("breed",data[1]);
      cv.put("lifestage",data[2]);
      cv.put("cost",data[3]);
      db.insert("pet",null,cv);
   }

   @Override
   public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
   }
}

生成的宠物表将是:-

为了解如何灵活地选择数据MainActivity已更改为:-

public class MainActivity extends AppCompatActivity {

    //private Context context;
    //private String query;

    private String typeSelection = "dog";
    private String breedSelection = "alsatian";
    private String lifeStageSelection = "young";
    private String lowerCostRangeSelection = "0.0";
    private String upperCostRangeSelection = "150";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*
        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(context);
        databaseAccess.openDatabase();
        Cursor cursor = databaseAccess.getWritableDatabase().rawQuery(query, null);
         */
        DatabaseUtils.dumpCursor(
                getSelection(typeSelection,breedSelection,lifeStageSelection,lowerCostRangeSelection,upperCostRangeSelection)
        );
        DatabaseUtils.dumpCursor(
                getSelection("Dog",null,null,null,null)
        );
        DatabaseUtils.dumpCursor(
                getSelection("Cat",null,null,null,null)
        );
        DatabaseUtils.dumpCursor(
                getSelection(null,null,null,null,null)
        );
    }

    private Cursor getSelection(String type, String breed, String lifeStage, String lowerCost, String upperCost ) {
        String[] args = null;
        ArrayList<String> argsArrayList = new ArrayList<>();
        StringBuilder whereClause = new StringBuilder();
        if (type != null && type.length() > 0) {
            if (whereClause.length() < 1) whereClause.append(" ");
            else whereClause.append(" AND ");
            whereClause.append(" type=?");
            argsArrayList.add(type);
        }
        if (breed != null && breed.length() > 0) {
            if (whereClause.length() < 1) whereClause.append(" ");
            else whereClause.append(" AND ");
            whereClause.append(" breed=?");
            argsArrayList.add(breed);
        }
        if (lifeStage != null && type.length() > 0) {
            if (whereClause.length() < 1) whereClause.append(" ");
            else whereClause.append(" AND ");
            whereClause.append(" lifestage=?");
            argsArrayList.add(lifeStage);
        }
        if (lowerCost != null && upperCost != null && lowerCost.length() > 0 && upperCost.length() > 0) {
            if (whereClause.length() < 1) whereClause.append(" ");
            else whereClause.append(" AND ");
            whereClause.append(" cost BETWEEN ? AND ?");
            argsArrayList.add(lowerCost);
            argsArrayList.add(upperCost);
        }
        if (whereClause.length() > 1) {
            args = new String[argsArrayList.size()];
            int i = 0;
            for (String s: argsArrayList) {
                args[i++] = s;
            }
        }
        return DatabaseAccess.getInstance(this).getWritableDatabase().query("pet",null,whereClause.toString(),args,null,null,null);
    }
}

getSelection方法是主要的加法,即允许根据5个值进行选择的代码,在本例中为:

  • 类型
  • 该品种
  • 生活方式
  • 较低的成本和较高的成本(即范围选择)
  • SQLiteDatabase调用查询方法,推荐使用,而不是rawQuery。

该方法设计灵活,允许以无均为值的方式进行选择。没有人会选择每一行。

  • 请注意,必须同时提供较低和较高的成本,因为它们是一个范围。

OnCreate方法中的代码只是调用getSelection方法来反映各种选择。
这4行中的第一行将不检索任何内容,因为没有任何行与所有给定条件匹配。第二行将选择typeDog(3行)的行。第三行将选择类型的行(其他3行)。第四个函数返回所有行(因为传递的是空值,这等同于没有选择条件)。

  • 注意该方法没有经过全面的测试,只是作为一个指针。
  • DatabaseUtils是一个类,顾名思义,它具有一些有用的实用程序,如演示的转储游标。

输出到日志的结果是:-

2022-10-16 22:56:51.850 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@9c8df94
2022-10-16 22:56:51.850 I/System.out: <<<<<

2022-10-16 22:56:51.851 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@f1e7a3d
2022-10-16 22:56:51.852 I/System.out: 0 {
2022-10-16 22:56:51.852 I/System.out:    _id=1
2022-10-16 22:56:51.852 I/System.out:    type=Dog
2022-10-16 22:56:51.852 I/System.out:    breed=Alsatian
2022-10-16 22:56:51.853 I/System.out:    lifestage=old
2022-10-16 22:56:51.853 I/System.out:    cost=100
2022-10-16 22:56:51.853 I/System.out: }
2022-10-16 22:56:51.853 I/System.out: 1 {
2022-10-16 22:56:51.853 I/System.out:    _id=2
2022-10-16 22:56:51.853 I/System.out:    type=Dog
2022-10-16 22:56:51.853 I/System.out:    breed=Golden Retriever
2022-10-16 22:56:51.853 I/System.out:    lifestage=newborn
2022-10-16 22:56:51.853 I/System.out:    cost=200
2022-10-16 22:56:51.854 I/System.out: }
2022-10-16 22:56:51.854 I/System.out: 2 {
2022-10-16 22:56:51.854 I/System.out:    _id=6
2022-10-16 22:56:51.854 I/System.out:    type=Dog
2022-10-16 22:56:51.854 I/System.out:    breed=Corgi
2022-10-16 22:56:51.854 I/System.out:    lifestage=mature
2022-10-16 22:56:51.854 I/System.out:    cost=300
2022-10-16 22:56:51.854 I/System.out: }
2022-10-16 22:56:51.854 I/System.out: <<<<<

2022-10-16 22:56:51.854 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@166d232
2022-10-16 22:56:51.855 I/System.out: 0 {
2022-10-16 22:56:51.855 I/System.out:    _id=3
2022-10-16 22:56:51.856 I/System.out:    type=Cat
2022-10-16 22:56:51.856 I/System.out:    breed=Siamese
2022-10-16 22:56:51.856 I/System.out:    lifestage=young
2022-10-16 22:56:51.856 I/System.out:    cost=150
2022-10-16 22:56:51.856 I/System.out: }
2022-10-16 22:56:51.856 I/System.out: 1 {
2022-10-16 22:56:51.856 I/System.out:    _id=4
2022-10-16 22:56:51.856 I/System.out:    type=Cat
2022-10-16 22:56:51.856 I/System.out:    breed=Burmese
2022-10-16 22:56:51.856 I/System.out:    lifestage=mature
2022-10-16 22:56:51.856 I/System.out:    cost=110
2022-10-16 22:56:51.856 I/System.out: }
2022-10-16 22:56:51.856 I/System.out: 2 {
2022-10-16 22:56:51.856 I/System.out:    _id=5
2022-10-16 22:56:51.856 I/System.out:    type=Cat
2022-10-16 22:56:51.856 I/System.out:    breed=Persian
2022-10-16 22:56:51.856 I/System.out:    lifestage=old
2022-10-16 22:56:51.856 I/System.out:    cost=75
2022-10-16 22:56:51.856 I/System.out: }
2022-10-16 22:56:51.856 I/System.out: <<<<<

2022-10-16 22:56:51.857 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@17eeb83
2022-10-16 22:56:51.857 I/System.out: 0 {
2022-10-16 22:56:51.857 I/System.out:    _id=1
2022-10-16 22:56:51.857 I/System.out:    type=Dog
2022-10-16 22:56:51.857 I/System.out:    breed=Alsatian
2022-10-16 22:56:51.857 I/System.out:    lifestage=old
2022-10-16 22:56:51.858 I/System.out:    cost=100
2022-10-16 22:56:51.858 I/System.out: }
2022-10-16 22:56:51.858 I/System.out: 1 {
2022-10-16 22:56:51.858 I/System.out:    _id=2
2022-10-16 22:56:51.858 I/System.out:    type=Dog
2022-10-16 22:56:51.858 I/System.out:    breed=Golden Retriever
2022-10-16 22:56:51.858 I/System.out:    lifestage=newborn
2022-10-16 22:56:51.858 I/System.out:    cost=200
2022-10-16 22:56:51.858 I/System.out: }
2022-10-16 22:56:51.858 I/System.out: 2 {
2022-10-16 22:56:51.858 I/System.out:    _id=3
2022-10-16 22:56:51.858 I/System.out:    type=Cat
2022-10-16 22:56:51.858 I/System.out:    breed=Siamese
2022-10-16 22:56:51.858 I/System.out:    lifestage=young
2022-10-16 22:56:51.858 I/System.out:    cost=150
2022-10-16 22:56:51.858 I/System.out: }
2022-10-16 22:56:51.858 I/System.out: 3 {
2022-10-16 22:56:51.858 I/System.out:    _id=4
2022-10-16 22:56:51.858 I/System.out:    type=Cat
2022-10-16 22:56:51.858 I/System.out:    breed=Burmese
2022-10-16 22:56:51.858 I/System.out:    lifestage=mature
2022-10-16 22:56:51.859 I/System.out:    cost=110
2022-10-16 22:56:51.859 I/System.out: }
2022-10-16 22:56:51.859 I/System.out: 4 {
2022-10-16 22:56:51.859 I/System.out:    _id=5
2022-10-16 22:56:51.859 I/System.out:    type=Cat
2022-10-16 22:56:51.859 I/System.out:    breed=Persian
2022-10-16 22:56:51.859 I/System.out:    lifestage=old
2022-10-16 22:56:51.859 I/System.out:    cost=75
2022-10-16 22:56:51.859 I/System.out: }
2022-10-16 22:56:51.859 I/System.out: 5 {
2022-10-16 22:56:51.859 I/System.out:    _id=6
2022-10-16 22:56:51.859 I/System.out:    type=Dog
2022-10-16 22:56:51.859 I/System.out:    breed=Corgi
2022-10-16 22:56:51.859 I/System.out:    lifestage=mature
2022-10-16 22:56:51.859 I/System.out:    cost=300
2022-10-16 22:56:51.859 I/System.out: }
2022-10-16 22:56:51.859 I/System.out: <<<<<

相关问题