[英]Populate a RecyclerView using SQLiteAssetHelper
当我使用SQLiteHelper从本地数据库填充它时,我的RecyclerView运行良好,但是现在我想使用SQLiteAssetHelper使用位于我的资产文件夹中的外部数据库填充它,因此我遵循了这个Github SQLiteAssetHelper示例中的示例,但我认为SimpleCursorAdapter()方法与ListView兼容,但与RecyclerView不兼容,因为它给我一个“不兼容的类型” IDE错误。
他们是否可以解决这个问题,还是应该将RecyclerView转换为ListView? 帮助将不胜感激。
public class DisplayActivity extends AppCompatActivity {
DataSource mDataSource;
List<Facility> facilityList = DataProvider.facilityList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDataSource = new DataSource(this);
mDataSource.open(); // Open database
mDataSource.seedDatabase(facilityList);
List<Facility> listFromDB = mDataSource.getAllItems();
FacilitiesAdapter adapter = new FacilitiesAdapter(this, listFromDB);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.displayActivityRecyclerView);
recyclerView.setAdapter(adapter);
} // End of onCreate()
@Override
protected void onPause() {
super.onPause();
mDataSource.close(); // Close database connection when application is
} // paused to prevent database leaks.
@Override
protected void onResume() {
super.onResume();
mDataSource.open(); // Open database connection when application is resumed
}
}
SQLiteHelper类别:
public class DBHelper extends SQLiteOpenHelper {
public static final String DB_FILE_NAME = "health.db";
public static final int DB_VERSION = 1;
public DBHelper(Context context) {
super(context, DB_FILE_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(FacilitiesTable.SQL_CREATE); // Execute SQL_CREATE statement;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(FacilitiesTable.SQL_DELETE); // delete old database
onCreate(db); // Create new database
}
}
SQLiteAssetHelper
是SQLiteAssetHelper
的即插即用替代SQLiteOpenHelper
,因为SQLiteAssetHelper
本身扩展了SQLiteOpenHelper
。
因此,给定的代码可与SQLiteOpenHelper
的子类SQLiteOpenHelper
,您所需要做的就是:
更改该子类以扩展SQLiteAssetHelper
远程onCreate()
和onUpgrade()
方法
如果需要,请调整对超类构造函数的调用
然后,按照文档将数据库包装在assets/
,您应该会很高兴。
现在,在扩展SQLiteAssetHelper
时,扩展SQLiteOpenHelper
时起作用的任何代码都应继续SQLiteAssetHelper
。
您可以使用以下方法将数据库从Assets文件夹复制到“默认”位置:
public final String path = "/data/data/YourPackageName/databases/";
public final String Name = "DataBaseName.db";
public void copydatabase() throws IOException {
OutputStream myOutput = new FileOutputStream(path + Name);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = getApplicationContext().getAssets().open("DataBaseName.db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
比只是打电话:
copydatabase()
并用try / catch包围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.