如何在Kotlin中使用ViewModelProviders

时间:2018-12-19 08:02:00

标签: android kotlin kotlin-android-extensions kotlin-extension

我是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)

3 个答案:

答案 0 :(得分:4)

在Kotlin中,您可以编写如下内容

val mFavViewModel = ViewModelProviders.of(activity).get(FavouritesViewModel::class.java)

确保已在gradle中添加以下依赖项

implementation 'android.arch.lifecycle:extensions:1.1.1'

答案 1 :(得分:1)

  

尝试以下

var mFavViewModel = ViewModelProviders.of(activity).get(FavouritesViewModel::class.java)

答案 2 :(得分:1)

假定使用了kotlin-已弃用ViewModelProviders类,而可以使用ViewModelProvider。要使用此功能,需要在应用程序build.gradle中添加一个依赖项-

 implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

创建视图模型类-

class MyViewModel: ViewModel(){
}

可以从片段-onCreateView中找到相同的类对象。例如-

class MyFragment: Fragment(){
    ...
    private lateint var myViewModel: MyViewModel
    ...
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
         ...
         myViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
         ...

     }

}