提问人:Joksova 提问时间:11/7/2023 最后编辑:Joksova 更新时间:11/7/2023 访问量:69
将 Kotlin Retrofit 与 Nodejs 服务器连接
Connect Kotlin Retrofit with Nodejs Server
问:
我正在尝试使用 Retrofit 将我的 Koltin 项目连接到 Nodejs 后端服务器,但每当我运行移动应用程序时,我都会看到一个白色的空白屏幕
这是我的适配器代码
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import tn.esprit.t1.databinding.ItemCatastropheBinding
import tn.esprit.t1.model.Catastrophe
class CatastropheAdapter: RecyclerView.Adapter<CatastropheAdapter.CatastropheViewHolder>() {
inner class CatastropheViewHolder(val binding: ItemCatastropheBinding): RecyclerView.ViewHolder(binding.root)
private val diffCallback = object : DiffUtil.ItemCallback<Catastrophe>(){
override fun areContentsTheSame(oldItem: Catastrophe, newItem: Catastrophe): Boolean {
return oldItem._id == newItem._id
}
override fun areItemsTheSame(oldItem: Catastrophe, newItem: Catastrophe): Boolean {
return oldItem==newItem
}
}
private val differ = AsyncListDiffer(this, diffCallback)
var catastrophes: List<Catastrophe>
get() = differ.currentList
set(value) { differ.submitList(value)}
override fun getItemCount()= catastrophes.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CatastropheViewHolder {
return CatastropheViewHolder(ItemCatastropheBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
))
}
override fun onBindViewHolder(holder: CatastropheViewHolder, position: Int) {
holder.binding.apply {
val catastrophe = catastrophes[position]
tvType.text = catastrophe.type
tvPlace.text = catastrophe.description
tvMag.text = catastrophe.magnitude.toString()
}
}
}
我想在我的回收器视图上显示 3 个文本视图(类型、描述、量级)
这是我的班级代码
data class Catastrophe(
val _id: Id,
val titre: String,
val type: String,
val tsunami: Int,
val description: String,
val date: Date,
val radius: Double,
val magnitude: Double,
val latitudeDeCatastrophe: Double,
val longitudeDeCatastrophe: Double,
val createdAt: Date,
val updatedAt: Date
)
巨灾API
interface CatastropheApi {
@GET("catastrophe/")
suspend fun getCatastophes(): Response<List<Catastrophe>>
}
这是我的改造实例代码
package tn.esprit.t1.repository
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
object RetrofitInstance {
val api: CatastropheApi by lazy {
Retrofit.Builder()
.baseUrl("http://192.168.1.105:9090/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(CatastropheApi::class.java)
}
}
最后是我的主要活动
package tn.esprit.t1
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.coroutines.launch
import retrofit2.HttpException
import retrofit2.http.HTTP
import retrofit2.http.Tag
import tn.esprit.t1.databinding.ActivityMainBinding
import tn.esprit.t1.repository.CatastropheAdapter
import tn.esprit.t1.repository.RetrofitInstance
import tn.esprit.t1.ui.theme.T1Theme
import java.io.IOException
const val TAG = "Main Activity"
class MainActivity : ComponentActivity() {
private lateinit var catastropheAdapter: CatastropheAdapter
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setupRecyclerView()
lifecycleScope.launch {
binding.progressBar.isVisible = true
val response = try {
RetrofitInstance.api.getCatastophes()
}
catch (e:IOException) {
Log.e(TAG, "IO Exception, No Internet Connection")
binding.progressBar.isVisible = false
return@launch
}
catch (e: HttpException) {
Log.e(TAG, "HttpException, no INternet ")
binding.progressBar.isVisible = false
return@launch
}
if (response.isSuccessful && response.body() != null)
{
catastropheAdapter.catastrophes = response.body()!!
}
else
{
Log.e(TAG, "Response not successful" )
}
binding.progressBar.isVisible = false
}
}
private fun setupRecyclerView() = binding.rvCatastrophe.apply {
catastropheAdapter = CatastropheAdapter()
adapter = catastropheAdapter
layoutManager = LinearLayoutManager(this@MainActivity)
}
}
这是 logcat
2023-11-07 15:00:52.245 11969-11969 tn.esprit.t1 tn.esprit.t1 I Late-enabling -Xcheck:jni
2023-11-07 15:00:56.107 11969-11969 tn.esprit.t1 tn.esprit.t1 W Unexpected CPU variant for x86: x86_64.
Known variants: atom, sandybridge, silvermont, kabylake, default
2023-11-07 15:00:57.314 11969-11969 re-initialized> tn.esprit.t1 W type=1400 audit(0.0:71): avc: granted { execute } for path="/data/data/tn.esprit.t1/code_cache/startup_agents/3dfe4a80-agent.so" dev="dm-33" ino=147461 scontext=u:r:untrusted_app:s0:c159,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c159,c256,c512,c768 tclass=file app=tn.esprit.t1
2023-11-07 15:00:58.071 11969-11969 tn.esprit.t1 tn.esprit.t1 W DexFile /data/data/tn.esprit.t1/code_cache/.studio/instruments-181d6ec9.jar is in boot class path but is not in a known location
2023-11-07 15:00:58.222 11969-11969 tn.esprit.t1 tn.esprit.t1 W Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
2023-11-07 15:00:58.223 11969-11969 tn.esprit.t1 tn.esprit.t1 W Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
2023-11-07 15:00:58.242 11969-11969 Compatibil...geReporter tn.esprit.t1 D Compat change id reported: 171979766; UID 10159; state: ENABLED
2023-11-07 15:00:58.399 11969-11969 ziparchive tn.esprit.t1 W Unable to open '/data/data/tn.esprit.t1/code_cache/.overlay/base.apk/classes6.dm': No such file or directory
2023-11-07 15:00:58.400 11969-11969 ziparchive tn.esprit.t1 W Unable to open '/data/app/~~GzDAPB5FTK6m4UOLjcK8TQ==/tn.esprit.t1-Sa28IPLd8ND7KFP4kRHMBg==/base.dm': No such file or directory
2023-11-07 15:00:58.401 11969-11969 ziparchive tn.esprit.t1 W Unable to open '/data/app/~~GzDAPB5FTK6m4UOLjcK8TQ==/tn.esprit.t1-Sa28IPLd8ND7KFP4kRHMBg==/base.dm': No such file or directory
2023-11-07 15:01:03.350 11969-11969 nativeloader tn.esprit.t1 D Configuring classloader-namespace for other apk /data/app/~~GzDAPB5FTK6m4UOLjcK8TQ==/tn.esprit.t1-Sa28IPLd8ND7KFP4kRHMBg==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~GzDAPB5FTK6m4UOLjcK8TQ==/tn.esprit.t1-Sa28IPLd8ND7KFP4kRHMBg==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/tn.esprit.t1
2023-11-07 15:01:03.392 11969-11969 GraphicsEnvironment tn.esprit.t1 V ANGLE Developer option for 'tn.esprit.t1' set to: 'default'
2023-11-07 15:01:03.393 11969-11969 GraphicsEnvironment tn.esprit.t1 V ANGLE GameManagerService for tn.esprit.t1: false
2023-11-07 15:01:03.395 11969-11969 GraphicsEnvironment tn.esprit.t1 V Neither updatable production driver nor prerelease driver is supported.
2023-11-07 15:01:03.405 11969-11969 NetworkSecurityConfig tn.esprit.t1 D No Network Security Config specified, using platform default
2023-11-07 15:01:03.410 11969-11969 NetworkSecurityConfig tn.esprit.t1 D No Network Security Config specified, using platform default
2023-11-07 15:01:03.485 11969-12078 libEGL tn.esprit.t1 D loaded /vendor/lib64/egl/libEGL_emulation.so
2023-11-07 15:01:03.496 11969-12078 libEGL tn.esprit.t1 D loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
2023-11-07 15:01:03.503 11969-12078 libEGL tn.esprit.t1 D loaded /vendor/lib64/egl/libGLESv2_emulation.so
2023-11-07 15:01:03.797 11969-11969 tn.esprit.t1 tn.esprit.t1 W Accessing hidden method Ljava/lang/invoke/MethodHandles$Lookup;-><init>(Ljava/lang/Class;I)V (unsupported, reflection, allowed)
2023-11-07 15:01:03.869 11969-11969 tn.esprit.t1 tn.esprit.t1 W Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (unsupported,core-platform-api, reflection, allowed)
2023-11-07 15:01:03.869 11969-11969 tn.esprit.t1 tn.esprit.t1 W Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (unsupported,core-platform-api, reflection, allowed)
2023-11-07 15:01:03.869 11969-11969 tn.esprit.t1 tn.esprit.t1 W Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (unsupported,core-platform-api, reflection, allowed)
2023-11-07 15:01:04.067 11969-11969 Choreographer tn.esprit.t1 I Skipped 36 frames! The application may be doing too much work on its main thread.
2023-11-07 15:01:04.123 11969-12076 HostConnection tn.esprit.t1 D createUnique: call
2023-11-07 15:01:04.124 11969-12076 HostConnection tn.esprit.t1 D HostConnection::get() New Host Connection established 0x70a0c8c49650, tid 12076
2023-11-07 15:01:04.419 11969-12076 HostConnection tn.esprit.t1 D HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_vulkan_async_qsri ANDROID_EMU_read_color_buffer_dma ANDROID_EMU_hwc_multi_configs GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
2023-11-07 15:01:04.422 11969-12076 OpenGLRenderer tn.esprit.t1 W Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
2023-11-07 15:01:04.422 11969-12076 OpenGLRenderer tn.esprit.t1 W Failed to initialize 101010-2 format, error = EGL_SUCCESS
2023-11-07 15:01:04.459 11969-12076 EGL_emulation tn.esprit.t1 D eglCreateContext: 0x70a0c8c49dd0: maj 2 min 0 rcv 2
2023-11-07 15:01:04.472 11969-12076 EGL_emulation tn.esprit.t1 D eglMakeCurrent: 0x70a0c8c49dd0: ver 2 0 (tinfo 0x70a2ec000080) (first time)
2023-11-07 15:01:04.550 11969-12076 Gralloc4 tn.esprit.t1 I mapper 4.x is not supported
2023-11-07 15:01:04.555 11969-12076 HostConnection tn.esprit.t1 D createUnique: call
2023-11-07 15:01:04.556 11969-12076 HostConnection tn.esprit.t1 D HostConnection::get() New Host Connection established 0x70a0c8c49110, tid 12076
2023-11-07 15:01:04.557 11969-12076 goldfish-address-space tn.esprit.t1 D allocate: Ask for block of size 0x100
2023-11-07 15:01:04.557 11969-12076 goldfish-address-space tn.esprit.t1 D allocate: ioctl allocate returned offset 0x3f3ffe000 size 0x2000
2023-11-07 15:01:04.581 11969-12076 Gralloc4 tn.esprit.t1 W allocator 4.x is not supported
2023-11-07 15:01:04.751 11969-12076 HostConnection tn.esprit.t1 D HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_vulkan_async_qsri ANDROID_EMU_read_color_buffer_dma ANDROID_EMU_hwc_multi_configs GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
2023-11-07 15:01:04.973 11969-12076 Parcel tn.esprit.t1 W Expecting binder but got null!
2023-11-07 15:01:04.974 11969-11969 Main Activity tn.esprit.t1 E IO Exception, No Internet Connection
2023-11-07 15:01:04.985 11969-12007 OpenGLRenderer tn.esprit.t1 I Davey! duration=1508ms; Flags=1, FrameTimelineVsyncId=38161, IntendedVsync=3403246544664, Vsync=3403846544640, InputEventId=0, HandleInputStart=3403855290100, AnimationStart=3403855305500, PerformTraversalsStart=3403855506400, DrawStart=3404540491200, FrameDeadline=3403263211330, FrameInterval=3403854704700, FrameStartTime=16666666, SyncQueued=3404549624100, SyncStart=3404552560300, IssueDrawCommandsStart=3404559417500, SwapBuffers=3404740054900, FrameCompleted=3404757783500, DequeueBufferDuration=21400, QueueBufferDuration=211400, GpuCompleted=3404757340000, SwapBuffersCompleted=3404757783500, DisplayPresentTime=0, CommandSubmissionCompleted=3404740054900,
2023-11-07 15:01:09.235 11969-12192 ProfileInstaller tn.esprit.t1 D Installing profile for tn.esprit.t1
2023-11-07 15:01:26.174 11969-12004 System tn.esprit.t1 W A resource failed to call close.
答:
0赞
Codemaker2015
11/7/2023
#1
确保您的 Android 应用具有访问互联网所需的权限。您应该在 AndroidManifest.xml 文件中拥有以下权限:
<uses-permission android:name="android.permission.INTERNET"
此外,在物理设备上运行时,您需要将“localhost”替换为服务器的实际 IP 地址。确保您在 Retrofit 配置中使用了正确的 URL。
在代码中,将基 URL 指定为 .确保这与 Node.js 服务器的实际位置匹配。RetrofitInstance
"http://192.168.1.105:9090/"
评论
1赞
Joksova
11/7/2023
是的,我已经添加了必要的权限,192.168.1.105 是我通过在 CMD 中运行“ipconfig”获得的 IP 地址
0赞
Codemaker2015
11/7/2023
你在那里使用任何代理服务吗?
0赞
Joksova
11/7/2023
不,我没有使用任何代理服务
评论
CatastropheApi