采用了MVVM框架,即Model VIEw viewmodel模式
Model:接收后端发送的实体数据
viewmodel:处理Model的数据并发送给VIEw
VIEw:展示处理好的数据
项目结构
具体实例逻辑层
在ReaderClIEntApplication.kt文件中定义token以及一个全局context
class ReaderClIEntApplication: Application() { var TOKEN = "" companion object{ @Suppresslint("StaticFIEldLeak") lateinit var context: Context } overrIDe fun onCreate() { super.onCreate() context = applicationContext TOKEN = TOKEN }}
同时还需要在AndroIDManifest.xml中注册
<application androID:name=".ReaderClIEntApplication" androID:allowBackup="true" androID:icon="@drawable/logo" androID:label="@string/app_name" androID:roundIcon="@mipmap/ic_launcher_round" androID:supportsRtl="true" androID:theme="@style/Apptheme"> .......</application>
根据返回的Json格式,定义数据模型
model中的UserResponse.kt
data class UserResponse (val code: String, val data: UserData, val msg: String)data class UserData(val admin: Int, val borrowCount: Int, val major: String, val password: String, val sno: String, val username: String)data class User(val sno: String, val password: String)
定义访问后端提供的API的接口
network中的BookService
interface BookService { @POST("user/login") fun loginValIDate(@Body user: User ): Call<UserResponse>......//其它接口}
创建Retrofit构建器
network中的ServiceCreator
package com.example.readerclIEnt.logic.networkimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactoryobject ServiceCreator { //后端服务基础地址 private const val BASE_URL = "http://172.27.183.4:8080/aissm_war_exploded/" private val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() fun<T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass) inline fun <reifIEd T> create(): T = create(T::class.java)}
定义统一网络数据源 访问入口
object ReaderClIEntNetwork { private val BookService = ServiceCreator.create(BookService::class.java) suspend fun loginValIDate(sno: String, password: String) = BookService.loginValIDate(User(sno, password)).await()......//其它方法 private suspend fun <T> Call<T>.await(): T{ return suspendCoroutine { continuation -> enqueue(object : Callback<T> { overrIDe fun onResponse(call: Call<T>, response: Response<T>) { val body = response.body() if(body != null) continuation.resume(body) else continuation.resumeWithException( RuntimeException("response body is null") ) } overrIDe fun onFailure(call: Call<T>, t: Throwable) { continuation.resumeWithException(t) } }) } }}
创建仓库层的统一封装入口
Repository单例类
object Repository { fun loginValIDate(sno: String, password: String) = liveData(dispatchers.IO){ //var userResponse = UserResponse("", UserData(0, 0 ,"", "", "", ""), "") val result = try{ val userResponse = ReaderClIEntNetwork.loginValIDate(sno, password) if(userResponse.code == "0") { Result.success(userResponse) }else{ Result.failure(RuntimeException("Response status is ${userResponse.code}, msg: ${userResponse.msg}")) } }catch(e: Exception){ Result.failure<List<String>>(e) } //Log.d("userResponse code is:", result.toString()) //Log.d("userResponse code is:", userResponse.toString()) emit(result) }......//其它方法}
定义viewmodel层
ui/login中的Userviewmodel
class Userviewmodel: viewmodel() { private val loginliveData = mutablelivedata<User>() val userliveData = transformations.switchMap(loginliveData){ user -> Repository.loginValIDate(user.sno, user.password) } fun loginValIDate(sno: String, password: String){ loginliveData.value = User(sno, password) }}
UI层
创建activity_login.xml布局文件
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" tools:context=".ui.login.LoginActivity"> <ImageVIEw androID:ID="@+ID/imageVIEw" androID:layout_wIDth="match_parent" androID:layout_height="200dp" androID:paddingtop="50dp" androID:paddingBottom="50dp" app:srcCompat="@drawable/logo" /> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:orIEntation="horizontal"> <TextVIEw androID:ID="@+ID/account" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="账号" /> <EditText androID:ID="@+ID/accountEdit" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_weight="1" androID:ems="10" androID:inputType="textPersonname" /> </linearLayout> <linearLayout androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:orIEntation="horizontal"> <TextVIEw androID:ID="@+ID/password" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:text="密码" /> <EditText androID:ID="@+ID/passwordEdit" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_weight="1" androID:ems="10" androID:inputType="textPassword" /> </linearLayout> <button androID:ID="@+ID/loginBtn" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:text="登录" /></linearLayout>
创建LoginActivity文件
class LoginActivity : AppCompatActivity() { overrIDe fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentVIEw(R.layout.activity_login) val viewmodel by lazy{ viewmodelProvIDers.of(this).get(Userviewmodel::class.java)} val prefs = getSharedPreferences("data", Context.MODE_PRIVATE) var today = Calendar.getInstance().get(Calendar.DAY_OF_YEAR); var lastday = prefs.getInt("lastday", today) var attempt = prefs.getInt("attempt", 0) accountEdit.setText(prefs.getString("account", "")) //Toast.makeText(this, "${today} ${lastday}", Toast.LENGTH_SHORT).show() //判断今日密码输入次数 if(today == lastday) { if( attempt >= 100) { Toast.makeText(this, "已达今天最大尝试次数,请再重试", Toast.LENGTH_SHORT).show() this.finish() } }else{ attempt = 0 lastday = today } var flag = 1 //登录按钮 loginBtn.setonClickListener(){ val account = accountEdit.text.toString() val password = passwordEdit.text.toString() val editor = prefs.edit() val intent = Intent(this, MainActivity::class.java) var userResponse : UserResponse editor.putInt("lastday", lastday) viewmodel.loginValIDate(account, password) viewmodel.userliveData.observe(this, Observer{ result -> if(result.getorNull() != null){ userResponse = result.getorNull() as UserResponse Log.d("testing",result.toString()) Log.d("testing",userResponse.toString()) editor.putString("account", account) if(userResponse.code.toInt() == 0){ editor.putString("token", userResponse.msg) val user = userResponse.data if(password == user.password) { editor.putString("name", user.username) editor.putString("sno", user.sno) editor.putString("major", user.major) editor.apply() this.finish() startActivity(intent) } } else{ Toast.makeText(this, userResponse.msg, Toast.LENGTH_SHORT).show() } } }) } }}
运行结果
总结
以上是内存溢出为你收集整理的【Android Studio】图书管理系统——功能实现原理全部内容,希望文章能够帮你解决【Android Studio】图书管理系统——功能实现原理所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)