我有一个Kotlin协程和改造项目。
我有这些依赖项:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
Run Code Online (Sandbox Code Playgroud)
今天,我在项目中将Retrofit更新为2.6.0。在https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter中,它已被弃用。在https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-260-2019-06-05中写道Retrofit当前支持suspend
。
因此,我删除了该文件,retrofit2-kotlin-coroutines-adapter:0.9.2
并在Retrofit客户端中更改了以下几行:
retrofit = Retrofit.Builder()
.baseUrl(SERVER_URL)
.client(okHttpClient)
.addConverterFactory(MyGsonFactory.create(gson))
//.addCallAdapterFactory(CoroutineCallAdapterFactory()) - removed it.
.build()
Run Code Online (Sandbox Code Playgroud)
运行时,第一个请求捕获异常:
java.lang.IllegalArgumentException: Unable to create call adapter for kotlinx.coroutines.Deferred<com.package.model.response.UserInfoResponse>
for method Api.getUserInfo
Run Code Online (Sandbox Code Playgroud)
据我了解,不是CoroutineCallAdapterFactory()
可以使用CallAdapter.Factory()
,而是抽象的。
如果在Api类中,我更改了suspend
开头添加的请求:
@FormUrlEncoded
@POST("user/info/")
suspend fun getUserInfo(@Field("token") token: String): Deferred<UserInfoResponse>
override suspend fun getUserInfo(token: String): Deferred<UserInfoResponse> =
service.getUserInfo(token)
Run Code Online (Sandbox Code Playgroud)
我得到这个例外:
java.lang.RuntimeException: Unable to invoke no-args constructor for kotlinx.coroutines.Deferred<com.package.model.response.UserInfoResponse>. Registering an …
Run Code Online (Sandbox Code Playgroud) 我在 中有一个初始化块onCreateView
,其中一些变量是从 SharedPreferences、DB 或 Network(当前来自 SharedPreferences)分配的。
我想在onViewCreated
. 但是它们在协程onCreateView
完成之前用空值更新。如何等到协程在主线程中完成?
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
...
GlobalScope.launch(Dispatchers.Main) {
val job = GlobalScope.launch(Dispatchers.IO) {
val task = async(Dispatchers.IO) {
settingsInteractor.getStationSearchCountry().let {
countryName = it.name
}
settingsInteractor.getStationSearchRegion().let {
regionName = it.name
}
}
task.await()
}
job.join()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
country.updateCaption(countryName)
region.updateCaption(regionName)
}
Run Code Online (Sandbox Code Playgroud)
更新 (20-05-2019)
目前我不使用onViewCreated
. 我在onCreate
和 中编写代码onCreateView
。在onCreateView
我以这种方式访问视图: …
我是 Kotlin 和 Android Studio 的新手,我目前的问题是......
我正在尝试让 Codelabs“android-room-with-a-view-kotlin”工作,同时修复各种构建错误,我认为我的 build.gradle 变得非常混乱!我通过添加依赖项更正了Word.kt 上的最后一次构建失败
kapt 'androidx.room:room-ktx:2.2.1'
Run Code Online (Sandbox Code Playgroud)
下一个构建在WordDao.kt上更进一步,但由于相同类型的错误而失败。
WordDao.java:21: error: To use Coroutine features, you must add `ktx` artifact from Room as a dependency. androidx.room:room-ktx:<version>
Run Code Online (Sandbox Code Playgroud)
我无法继续,因为我不知道要在 build.gradle 中更改什么,因为我已经添加了该依赖项?
正如我已经说过我的文件现在很迷茫,我将不胜感激任何以使其更明智的援助。谢谢, DaveInUk
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: "kotlin-kapt"
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.prepopplus"
//was minSdkVersion 15 Note Old phone is API16
minSdkVersion 21
targetSdkVersion 28
versionCode 1 …
Run Code Online (Sandbox Code Playgroud) 使用MaterialDatePicker我想显示所需的日期并有机会选择另一个。但是当 DatePicker 出现时,它会显示当前日期而不是指定日期。
我插入库:(implementation 'com.google.android.material:material:1.2.0-alpha06'
或 1.1.0)。
然后覆盖AppTheme
在styles.xml
:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
Run Code Online (Sandbox Code Playgroud)
现在可以显示 DatePicker。
val now = Calendar.getInstance()
now[Calendar.YEAR] = 2020
now[Calendar.MONTH] = 10
now[Calendar.DAY_OF_MONTH] = 1
val builder = MaterialDatePicker.Builder.datePicker()
builder.setSelection(now.timeInMillis)
val picker = builder.build()
fragmentManager?.let { picker.show(it, MaterialDatePicker::class.java.simpleName) }
Run Code Online (Sandbox Code Playgroud)
这是一个结果。我想显示 11 月 1 日,但显示的是 5 月 7 日。
更新 1
如上面的链接所写,我们可以使用CalendarConstraints.Builder
:
...
val constraintsBuilder = CalendarConstraints.Builder()
constraintsBuilder.setStart(now.timeInMillis)
constraintsBuilder.setEnd(now.timeInMillis)
val builder = MaterialDatePicker.Builder.datePicker()
builder.setCalendarConstraints(constraintsBuilder.build())
builder.setSelection(now.timeInMillis)
...
Run Code Online (Sandbox Code Playgroud)
这将显示所需的日期,我们可以选择另一天,但我们不能滚动月份。
更新 2
我想这是一个新的 Android …
android android-datepicker material-components material-components-android
我看到了诸如如何使用 Retrofit 库在 Android 中下载文件之类的主题?,他们使用@Streaming
和 RxJava / 回调。
我有 Kotlin、协程、改造 2.6.0 和/sf/answers/3953175411/ 中的查询:
@FormUrlEncoded
@Streaming
@POST("export-pdf/")
suspend fun exportPdf(
@Field("token") token: String
): ExportResponse
Run Code Online (Sandbox Code Playgroud)
我有一个改造客户:
retrofit = Retrofit.Builder()
.baseUrl(SERVER_URL)
.client(okHttpClient)
.build()
service = retrofit.create(Api::class.java)
Run Code Online (Sandbox Code Playgroud)
如果令牌参数正确,则查询返回 PDF 文件:
%PDF-1.4
%????
...
Run Code Online (Sandbox Code Playgroud)
如果出错,它将返回带有错误描述的 JSON:
{
"success": 0,
"errors": {
"message": "..."
}
}
Run Code Online (Sandbox Code Playgroud)
所以,ExportResponse 是一个包含 JSON 字段的数据类,POJO。
我无法访问文件数据
Response response = restAdapter.apiRequest();
try {
//you can now get your file in the InputStream
InputStream …
Run Code Online (Sandbox Code Playgroud) 我试过了,但没有添加联系人!
ContentResolver cr = this.getContentResolver();
ContentValues cv = new ContentValues();
cv.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, "sai1");
cv.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "9640954335");
cv.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
cr.insert(ContactsContract.RawContacts.CONTENT_URI, cv);
Run Code Online (Sandbox Code Playgroud) 在Android Studio 3.0中,模拟器在关闭后保存其状态.因此,如果我关闭电源(在模拟器中),它将关闭屏幕.我不能再打开了.
Android Studio 提供替换片段<fragment>
中的标签的功能Google Maps
。在我没有的应用程序中Navigation
,但可能会添加。我应该用 替换<fragment>
标签<FragmentContainerView>
吗?
查看https://proandroiddev.com/android-fragments-fragmentcontainerview-292f393f9ccf我发现我们也可以替换<FrameLayout>
为<androidx.fragment.app.FragmentContainerView>
. 我们应该这样做吗?
我想在用户退出应用程序时调用一些方法(请参阅1、2获取帮助)。
class BaseApplication : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
// Register observer.
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun init() {
println("*** called onCreate()")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun LibOnStart() {
println("*** called onStart()")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun LibOnStop() {
println("*** called onStop()")
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun LibOnResume() {
println("*** called onResume()")
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun LibOnPause() {
println("*** called onPause()")
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun cleanup() {
println("*** called onDestroy()")
}
}
Run Code Online (Sandbox Code Playgroud)
这些事件都会被触发,除了ON_DESTROY
。
I/System.out: *** called onPause() of Activity
I/System.out: …
Run Code Online (Sandbox Code Playgroud)