到sqlite,android,firebase,arraylist,firebase-realtime-database,android-sqlite"/>

首页 > 解决方案 > 保存列表到sqlite

问题描述

我正在开发 Firebase 应用程序,我想将 5000 多个检索到的 PriceList 项目的列表保存到 SQLite 中。

这是我的Firebase 代码

@Override
protected void onStart() {
    super.onStart();

    mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            pricesArrayList.clear();

            for (DataSnapshot PricesListDataSnapshot : dataSnapshot.getChildren()) {

                PricesList pricesList = PricesListDataSnapshot.getValue(PricesList.class);
                pricesArrayList.add(pricesList);

                // I don't know what is the insertion code for SQLite

            }

            // here goes the code for retrieved data from SQLite after it was saved from Firebase

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

这是DB.class代码

private class DBHelper extends SQLiteOpenHelper {
    private static final int VERSION = 1;
    private static final String DB_NAME = "MyDB1.db";
    public static final String id = "_id";
    public static final String ItemCode = "ItemCode";
    public static final String Product = "Product";

    DBHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String create_sql = "CREATE TABLE IF NOT EXISTS "
                + DB_NAME + '(' + id
                + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + ItemCode + " TEXT ,"
                + Product + " TEXT ," +')';
        db.execSQL(create_sql);

    }

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

应该使用什么代码来存储 SQLite 数据库中的项目列表?我会感谢任何有答案的人。

标签: androidfirebasearraylistfirebase-realtime-databaseandroid-sqlite

解决方案


在您的 DBHelper 中,您需要一种将数据插入数据库的方法,所以.. 首先:创建方法

public void isInsertData(Price price) {
   try {
      SQLiteDatabase db = this.getWritableDatabase();
      ContentValues insertValues = new ContentValues();
      insertValues.put(ItemCode, price.getItemCode());
      insertValues.put(Product, price.getProduct());
      db.insert(DB_NAME, null, insertValues);
    } catch (Exception e) {
      e.printStackTrace();
    }
}

我看到您的表名看起来与您的数据库名称相似,我建议您更改它,但如果您愿意的话。

第二:我们需要一个帮助器实例并调用新方法,下一行进入您的迭代。

DbHelper dbHelper = new DbHelper(this); //or ActivityName.this
for (DataSnapshot PricesListDataSnapshot : dataSnapshot.getChildren()) {
            PricesList pricesList = PricesListDataSnapshot.getValue(PricesList.class);
            pricesArrayList.add(pricesList);
            dbHelper.isInsertData(pricesList);
  }

而已!现在您将数据保存在数据库中。

如果您在此之后有任何疑问,我建议您阅读此链接 https://developer.android.com/training/data-storage/sqlite


推荐阅读