我是Kotlin的新手,请帮助我如何在Kotlin中使用ViewModelProviders.of(this)
我的Java代码为
mFavViewModel = ViewModelProviders.of(this).get(FavouritesViewModel.class);
我无法在 Kotlin 中找到 ViewModelProviders 类。尝试进行自动转换,但显示错误。
这是我的 DataModel 类。
class FavoritesDataViewModel:ViewModel{
private var mFavHelper: DatabaseHelper
private lateinit var mfav:ArrayList<Favorites>
constructor(application: Application) {
mFavHelper = DatabaseHelper(application)
}
fun getListFav():List<Favorites>{
if (mfav==null){
mfav = arrayListOf<Favorites>()
createDummyList()
loadFav()
}
val clonedFavs = arrayListOf<Favorites>()
for (i in 0 until mfav.size) {
clonedFavs.add(Favorites(mfav.get(i)))
}
return clonedFavs
}
fun createDummyList(){
addFav("https://www.journaldev.com", Date().getTime())
addFav("https://www.medium.com", Date().getTime())
addFav("https://www.reddit.com", Date().getTime())
addFav("https://www.github.com", Date().getTime())
addFav("https://www.hackerrank.com", Date().getTime())
addFav("https://www.developers.android.com", Date().getTime())
}
fun addFav(url:String,date:Long):Favorites{
val db:SQLiteDatabase = this.mFavHelper.getWritableDatabase();
val values: ContentValues = ContentValues();
values.put(DbSettings.DbEntry.COL_FAV_DATE,date)
values.put(DbSettings.DbEntry.COL_FAV_URL,url)
val id:Long = db.insertWithOnConflict(DbSettings.DbEntry.TABLE,
null,
values,SQLiteDatabase.CONFLICT_REPLACE)
db.close()
val fav:Favorites = Favorites(id,url,date)
mfav.add(fav)
return Favorites(fav)
}
fun loadFav(){
mfav.clear()
val db:SQLiteDatabase = mFavHelper.readableDatabase
val cursor:Cursor = db.query(DbSettings.DbEntry.TABLE,
arrayOf(
DbSettings.DbEntry._ID,
DbSettings.DbEntry.COL_FAV_URL,
DbSettings.DbEntry.COL_FAV_DATE
),
null, null, null, null, null);
while (cursor.moveToNext()){
val idxID:Int = cursor.getColumnIndex(DbSettings.DbEntry._ID)
val idxURL:Int = cursor.getColumnIndex(DbSettings.DbEntry.COL_FAV_URL)
val idxDate:Int = cursor.getColumnIndex(DbSettings.DbEntry.COL_FAV_DATE)
mfav.add(Favorites(cursor.getLong(idxID),cursor.getString(idxURL),cursor.getLong(idxDate)))
}
cursor.close()
db.close()
}
}
尝试使用以下代码行
var mFavViewModel = ViewModelProviders.of(activity).get(FavouritesViewModel::class.java)
implementation 'android.arch.lifecycle:extensions:1.1.1'
这里出现了错误:
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.nearex.mykotlinsample.viewmodel.FavoritesDataViewModel
at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:153)
at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)
at com.nearex.mykotlinsample.view.MainActivity.onCreate(MainActivity.kt:29)
_
作为前缀)的情况外,不使用特殊的前缀或后缀,例如在示例中看到的 name_、mName、s_name 和 kName”。 - EpicPandaForce