android - 保存列表到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 数据库中的项目列表?我会感谢任何有答案的人。
解决方案
在您的 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
推荐阅读
- javascript - JavaScript:每列生成表列
- npm - JFrog 私有注册表无法 npm 安装
- discord - webhook 和角色/权限概念的问题
- css - 反应中的可重用搜索组件-文本溢出时css失败
- r - PCA 分析:dim desc() 中出现错误:数据不方便
- meteor - 在 MeteorJS 中的表单上提交后路由到新 URL
- php - 在 Wordpress 中在一页上使用 PHP 更改永久链接
- java - 你怎么知道如何限制有多少客户端可以进入你的基本群聊应用服务器?(最多 10 个)
- hadoop - 由于输入字符串的 java.lang.NumberFormatException 导致 Apache Tez 作业失败:“30s”
- java - Java中的Chrome sqlite数据库Cookie过期转换