领域:在重新启动后调用此方法之前,请先调用realm.init(context)

时间:2019-09-17 09:57:35

标签: java android kotlin widget realm

当前,我正在使用一个家庭小部件,该小部件显示我从Realm Data中获取的日期数据。一切正常,直到我重新启动手机进行了测试,并且在我将登录文件写入文件时发生了错误。它表明:

  

在调用此方法之前先调用realm.init(context)

这是我当前的代码:

ExampleAppWidget.kt

override fun onReceive(p0: Context?, p1: Intent?) {
    super.onReceive(p0, p1)
    if (p1?.action.equals(Intent.ACTION_BOOT_COMPLETED)){
        Log.d("MainActivityLog","ACTION_BOOT_COMPLETED: onReceive")
        Toast.makeText(p0, "Reload Widge onRecieve", Toast.LENGTH_LONG).show()
        p0?.let {
            Realm.init(p0)
            val realmConfiguration = RealmConfiguration.Builder()
                .build()
            Realm.setDefaultConfiguration(realmConfiguration)
            updateAppWidget(it)
        }
    }
}
private fun updateAppWidget(context: Context){

        val appWidgetIntent = Intent(context, ExampleAppWidget::class.java)
        appWidgetIntent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
        val appWidgetManager = AppWidgetManager.getInstance(context)
        val ids = appWidgetManager.getAppWidgetIds(
            ComponentName(context, ExampleAppWidget::class.java)
        )
        appWidgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
        context.sendBroadcast(appWidgetIntent)
}

override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        updateAppWidget(context,appWidgetManager,appWidgetIds)
    }

fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: IntArray) {
    val views: RemoteViews = RemoteViews(context.packageName,R.layout.example_app_widget)
    val ifmonthExist = checkMonthifExist(`datelocal`,context) // <---- Realm request error here only after reboot
    if(ifmonthExist){
        // Render Something when exist
    }else{
        // Request API Call
    }
}

这是我的领域请求功能:

fun checkMonthifExist(strdate: String,context: Context): Boolean {
    var realm: Realm? = null
    var ishave = false
    try {
        realm = getRealm(context)
        realm?.executeTransaction {
            val data = it.where(MyData::class.java).equalTo("monthyear",strdate).findFirst()
            if(data != null){
                ishave = true
            }
        }
    }catch (ex: Exception){
        CalendarUtils.writeToFile("${ex.localizedMessage} ||ExampleAppWidget line 295",context,"checkMonthifExist")

    }finally {
        realm?.close()
    }
    return ishave
}

0 个答案:

没有答案