Android 使用改装和viewmodel的微调器值
我正试图在我的项目中实现编辑购物车。为此,我使用了旋转器。我发布了两种方法:一种是使用viewmodel,另一种是不使用viewmodel。当我不使用viewmodel时,它可以正常工作。问题在于使用viewmodel时 在不使用viewmodel的情况下,它在调用中发布正确的值,在我重新访问购物车时在微调器中正确设置值,但是在使用viewmodel时,如果我将微调器设置为3,则显示成功,但在重新访问时,我在微调器中看到8,甚至在我使用Postman发出的其余请求中,我在响应中看到8 适配器::------------Android 使用改装和viewmodel的微调器值,android,kotlin,spinner,viewmodel,android-spinner,Android,Kotlin,Spinner,Viewmodel,Android Spinner,我正试图在我的项目中实现编辑购物车。为此,我使用了旋转器。我发布了两种方法:一种是使用viewmodel,另一种是不使用viewmodel。当我不使用viewmodel时,它可以正常工作。问题在于使用viewmodel时 在不使用viewmodel的情况下,它在调用中发布正确的值,在我重新访问购物车时在微调器中正确设置值,但是在使用viewmodel时,如果我将微调器设置为3,则显示成功,但在重新访问时,我在微调器中看到8,甚至在我使用Postman发出的其余请求中,我在响应中看到8 适配器::
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/*** */
val aa: ArrayAdapter <*> =
ArrayAdapter<Any?>(context, android.R.layout.simple_spinner_item, country)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
holder.spin.setAdapter(aa)
holder.spin.setSelection(dataList?.get(position)?.quantity!! - 1, false)
holder.spin.setOnItemSelectedListener(object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position1: Int,
id: Long
) {
progressDialog.show()
val id = dataList?.get(position)!!.product.id
itemClick?.EditItem(position1, id!!.toInt())
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// todo for nothing selected
}
})
interface OnItemClick {
fun DeleteItem(position: Int, id:Int)
fun EditItem(position: Int,id: Int)
}
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/* */
override fun EditItem(position: Int, id: Int) {
val token: String = SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
RetrofitClient.instance.editCart(token, id, arrayOf(country[position]))
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(call: Call<DeleteResponse>, response: Response<DeleteResponse>) {
progressDialog?.dismiss()
finish()
var res = response
if (res.isSuccessful) {
Toast.makeText(applicationContext, res.body()?.user_msg, Toast.LENGTH_LONG).show()
progressDialog?.dismiss()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
applicationContext.startActivity(intent)
overridePendingTransition(0, 0)
Log.d("kjsfgxhufb", response.body()?.user_msg.toString())
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(applicationContext, jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
@FormUrlEncoded
@POST("editCart")
fun editCart(
@Header("access_token") token: String,
@Field("product_id") product_id: Int,
@Field("quantity") quantity: Array<Int>
): Call<DeleteResponse>
class CartViewModel(context: Application, savedStateHandle: SavedStateHandle) :
AndroidViewModel(context) {
/// val product_id:String?=null
sealed class Result {
object Missing : Result()
object NetworkFailure : Result()
object Success : Result()
}
val product_id: MutableLiveData<String> = savedStateHandle.getLiveData("product_id", "")
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
private var Cart: MutableLiveData<CartResponse>? = null
val CartList: MutableLiveData<CartResponse>?
get() {
if (Cart == null) {
Cart = MutableLiveData<CartResponse>()
loadCartList()
}
return Cart
}
private val loginResultEmitter = EventEmitter<CartViewModel.Result>()
val Results: EventSource<CartViewModel.Result> = loginResultEmitter
private fun loadCartList() {
val token: String =
SharedPrefManager.getInstance(
getApplication()
).user.access_token.toString()
RetrofitClient.instance.listcart(token).enqueue(object :
Callback<CartResponse> {
override fun onFailure(call: Call<CartResponse>, t: Throwable) {
Toast.makeText(getApplication(), "falied", Toast.LENGTH_LONG).show()
}
override fun onResponse(
call: Call<CartResponse>,
response: Response<CartResponse>
) {
if (response.isSuccessful) {
Cart!!.value = response.body()
}
}
})
}
fun loaddelete() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.deletecart(token, id)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
loginResultEmitter.emit(CartViewModel.Result.NetworkFailure)
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.body()?.status == 200) {
Toast.makeText(
getApplication(),
res.body()?.message,
Toast.LENGTH_LONG
).show()
loginResultEmitter.emit(CartViewModel.Result.Success)
} else {
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
fun loadEdit() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.editCart(token, id.toInt(), country)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.isSuccessful) {
Toast.makeText(getApplication(), res.body()?.user_msg, Toast.LENGTH_LONG)
.show()
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
class AddToCart : BaseClassActivity(), OnItemClick {
var progressDialog: ProgressDialog? = null
private val viewModel by viewModels<CartViewModel>()
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_to_cart)
getWindow().setExitTransition(null)
getWindow().setEnterTransition(null)
val progressDialog: ProgressDialog = ProgressDialog(applicationContext);
var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
setSupportActionBar(mActionBarToolbar);
// add back arrow to toolbar
setEnabledTitle()
mActionBarToolbar.setNavigationOnClickListener(View.OnClickListener {
onBackPressed()
})
placeorder.setOnClickListener {
val intent: Intent = Intent(applicationContext, AddressActivity::class.java)
startActivity(intent)
}
loadCart()
}
fun loadCart() {
val model = ViewModelProvider(this)[CartViewModel::class.java]
model.CartList?.observe(this, object : Observer<CartResponse> {
override fun onChanged(t: CartResponse?) {
generateDataList(t?.data?.toMutableList())
totalamount.setText(t?.total.toString())
}
})
}
fun generateDataList(dataList: MutableList<DataCart?>?) {
val recyclerView = findViewById<RecyclerView>(R.id.addtocartrecyleview) as? RecyclerView
val linear: LinearLayoutManager =
LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = linear
val adapter = CartAdapter(this@AddToCart, dataList)
recyclerView?.adapter = adapter
recyclerView?.addItemDecoration(DividerItemDecorator(resources.getDrawable(R.drawable.divider)))
// recyclerView?.setHasFixedSize(true)
adapter.setItemClick(this);
adapter.notifyDataSetChanged()
if (dataList?.isEmpty() ?: true) {
recyclerView?.setVisibility(View.GONE)
totalamount.setVisibility(View.GONE)
fl_footer.setVisibility(View.GONE)
placeorder.setVisibility(View.GONE)
emptytext.setVisibility(View.VISIBLE)
} else {
recyclerView?.setVisibility(View.VISIBLE)
totalamount.setVisibility(View.VISIBLE)
fl_footer.setVisibility(View.VISIBLE)
placeorder.setVisibility(View.VISIBLE)
emptytext.setVisibility(View.GONE)
}
recyclerView?.addOnScrollListener(object :
RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
Log.e("RecyclerView", "onScrollStateChanged")
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
}
})
}
override fun onBackPressed() {
super.onBackPressed()
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
NavUtils.navigateUpFromSameTask(this)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onResume() {
super.onResume()
loadCart()
}
override fun DeleteItem(position: Int, id: Int) {
}
override fun EditItem(position: Int, id: Int) {
viewModel.product_id.value = id.toString()
viewModel.loadEdit()
viewModel.country[position] = country[position]
viewModel.Results.observe(this) { result ->
when (result) {
CartViewModel.Result.Missing -> {
Toast.makeText(
applicationContext, "product is missing", Toast.LENGTH_LONG
).show()
}
CartViewModel.Result.Success -> {
finish()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
startActivity(intent)
overridePendingTransition(0, 0)
}
else -> {
Toast.makeText(applicationContext, "hello", Toast.LENGTH_LONG).show()
}
}
}
}
活动::-----
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/*** */
val aa: ArrayAdapter <*> =
ArrayAdapter<Any?>(context, android.R.layout.simple_spinner_item, country)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
holder.spin.setAdapter(aa)
holder.spin.setSelection(dataList?.get(position)?.quantity!! - 1, false)
holder.spin.setOnItemSelectedListener(object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position1: Int,
id: Long
) {
progressDialog.show()
val id = dataList?.get(position)!!.product.id
itemClick?.EditItem(position1, id!!.toInt())
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// todo for nothing selected
}
})
interface OnItemClick {
fun DeleteItem(position: Int, id:Int)
fun EditItem(position: Int,id: Int)
}
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/* */
override fun EditItem(position: Int, id: Int) {
val token: String = SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
RetrofitClient.instance.editCart(token, id, arrayOf(country[position]))
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(call: Call<DeleteResponse>, response: Response<DeleteResponse>) {
progressDialog?.dismiss()
finish()
var res = response
if (res.isSuccessful) {
Toast.makeText(applicationContext, res.body()?.user_msg, Toast.LENGTH_LONG).show()
progressDialog?.dismiss()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
applicationContext.startActivity(intent)
overridePendingTransition(0, 0)
Log.d("kjsfgxhufb", response.body()?.user_msg.toString())
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(applicationContext, jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
@FormUrlEncoded
@POST("editCart")
fun editCart(
@Header("access_token") token: String,
@Field("product_id") product_id: Int,
@Field("quantity") quantity: Array<Int>
): Call<DeleteResponse>
class CartViewModel(context: Application, savedStateHandle: SavedStateHandle) :
AndroidViewModel(context) {
/// val product_id:String?=null
sealed class Result {
object Missing : Result()
object NetworkFailure : Result()
object Success : Result()
}
val product_id: MutableLiveData<String> = savedStateHandle.getLiveData("product_id", "")
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
private var Cart: MutableLiveData<CartResponse>? = null
val CartList: MutableLiveData<CartResponse>?
get() {
if (Cart == null) {
Cart = MutableLiveData<CartResponse>()
loadCartList()
}
return Cart
}
private val loginResultEmitter = EventEmitter<CartViewModel.Result>()
val Results: EventSource<CartViewModel.Result> = loginResultEmitter
private fun loadCartList() {
val token: String =
SharedPrefManager.getInstance(
getApplication()
).user.access_token.toString()
RetrofitClient.instance.listcart(token).enqueue(object :
Callback<CartResponse> {
override fun onFailure(call: Call<CartResponse>, t: Throwable) {
Toast.makeText(getApplication(), "falied", Toast.LENGTH_LONG).show()
}
override fun onResponse(
call: Call<CartResponse>,
response: Response<CartResponse>
) {
if (response.isSuccessful) {
Cart!!.value = response.body()
}
}
})
}
fun loaddelete() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.deletecart(token, id)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
loginResultEmitter.emit(CartViewModel.Result.NetworkFailure)
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.body()?.status == 200) {
Toast.makeText(
getApplication(),
res.body()?.message,
Toast.LENGTH_LONG
).show()
loginResultEmitter.emit(CartViewModel.Result.Success)
} else {
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
fun loadEdit() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.editCart(token, id.toInt(), country)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.isSuccessful) {
Toast.makeText(getApplication(), res.body()?.user_msg, Toast.LENGTH_LONG)
.show()
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
class AddToCart : BaseClassActivity(), OnItemClick {
var progressDialog: ProgressDialog? = null
private val viewModel by viewModels<CartViewModel>()
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_to_cart)
getWindow().setExitTransition(null)
getWindow().setEnterTransition(null)
val progressDialog: ProgressDialog = ProgressDialog(applicationContext);
var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
setSupportActionBar(mActionBarToolbar);
// add back arrow to toolbar
setEnabledTitle()
mActionBarToolbar.setNavigationOnClickListener(View.OnClickListener {
onBackPressed()
})
placeorder.setOnClickListener {
val intent: Intent = Intent(applicationContext, AddressActivity::class.java)
startActivity(intent)
}
loadCart()
}
fun loadCart() {
val model = ViewModelProvider(this)[CartViewModel::class.java]
model.CartList?.observe(this, object : Observer<CartResponse> {
override fun onChanged(t: CartResponse?) {
generateDataList(t?.data?.toMutableList())
totalamount.setText(t?.total.toString())
}
})
}
fun generateDataList(dataList: MutableList<DataCart?>?) {
val recyclerView = findViewById<RecyclerView>(R.id.addtocartrecyleview) as? RecyclerView
val linear: LinearLayoutManager =
LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = linear
val adapter = CartAdapter(this@AddToCart, dataList)
recyclerView?.adapter = adapter
recyclerView?.addItemDecoration(DividerItemDecorator(resources.getDrawable(R.drawable.divider)))
// recyclerView?.setHasFixedSize(true)
adapter.setItemClick(this);
adapter.notifyDataSetChanged()
if (dataList?.isEmpty() ?: true) {
recyclerView?.setVisibility(View.GONE)
totalamount.setVisibility(View.GONE)
fl_footer.setVisibility(View.GONE)
placeorder.setVisibility(View.GONE)
emptytext.setVisibility(View.VISIBLE)
} else {
recyclerView?.setVisibility(View.VISIBLE)
totalamount.setVisibility(View.VISIBLE)
fl_footer.setVisibility(View.VISIBLE)
placeorder.setVisibility(View.VISIBLE)
emptytext.setVisibility(View.GONE)
}
recyclerView?.addOnScrollListener(object :
RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
Log.e("RecyclerView", "onScrollStateChanged")
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
}
})
}
override fun onBackPressed() {
super.onBackPressed()
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
NavUtils.navigateUpFromSameTask(this)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onResume() {
super.onResume()
loadCart()
}
override fun DeleteItem(position: Int, id: Int) {
}
override fun EditItem(position: Int, id: Int) {
viewModel.product_id.value = id.toString()
viewModel.loadEdit()
viewModel.country[position] = country[position]
viewModel.Results.observe(this) { result ->
when (result) {
CartViewModel.Result.Missing -> {
Toast.makeText(
applicationContext, "product is missing", Toast.LENGTH_LONG
).show()
}
CartViewModel.Result.Success -> {
finish()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
startActivity(intent)
overridePendingTransition(0, 0)
}
else -> {
Toast.makeText(applicationContext, "hello", Toast.LENGTH_LONG).show()
}
}
}
}
var country=arrayOf(1,2,3,4,5,6,7,8)
/* */
覆盖项目(位置:Int,id:Int){
val token:String=SharedPrefManager.getInstance(applicationContext).user.access\u token.toString()
修改client.instance.editCart(令牌、id、数组(国家[位置])
.enqueue(对象:回调{
覆盖失效时的乐趣(调用:调用,t:可丢弃){
Log.d(“res”和“+t”)
}
覆盖fun onResponse(调用:调用,响应:响应){
progressDialog?.discover()的
完成()
var res=响应
如果(解决成功){
Toast.makeText(applicationContext,res.body()?.user\u msg,Toast.LENGTH\u LONG.show())
progressDialog?.discover()的
val intent=intent(applicationContext,AddToCart::class.java)
intent.flags=intent.FLAG\u活动\u新任务或intent.FLAG\u活动\u多任务
applicationContext.startActivity(意图)
重写结束转换(0,0)
Log.d(“kjsfgxhufb”,response.body()?.user_msg.toString())
}否则{
试一试{
val jObjError=JSONObject(response.errorBody()!!.string())
Toast.makeText(applicationContext,jObjError.getString(“消息”)+jObjError.getString(“用户消息”),
Toast.LENGTH_LONG.show()的
}捕获(e:例外){
Toast.makeText(applicationContext,e.message,Toast.LENGTH\u LONG.show())
Log.e(“errorr”,e.message)
}
}
}
})
}
Api::-----------
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/*** */
val aa: ArrayAdapter <*> =
ArrayAdapter<Any?>(context, android.R.layout.simple_spinner_item, country)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
holder.spin.setAdapter(aa)
holder.spin.setSelection(dataList?.get(position)?.quantity!! - 1, false)
holder.spin.setOnItemSelectedListener(object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position1: Int,
id: Long
) {
progressDialog.show()
val id = dataList?.get(position)!!.product.id
itemClick?.EditItem(position1, id!!.toInt())
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// todo for nothing selected
}
})
interface OnItemClick {
fun DeleteItem(position: Int, id:Int)
fun EditItem(position: Int,id: Int)
}
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/* */
override fun EditItem(position: Int, id: Int) {
val token: String = SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
RetrofitClient.instance.editCart(token, id, arrayOf(country[position]))
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(call: Call<DeleteResponse>, response: Response<DeleteResponse>) {
progressDialog?.dismiss()
finish()
var res = response
if (res.isSuccessful) {
Toast.makeText(applicationContext, res.body()?.user_msg, Toast.LENGTH_LONG).show()
progressDialog?.dismiss()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
applicationContext.startActivity(intent)
overridePendingTransition(0, 0)
Log.d("kjsfgxhufb", response.body()?.user_msg.toString())
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(applicationContext, jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
@FormUrlEncoded
@POST("editCart")
fun editCart(
@Header("access_token") token: String,
@Field("product_id") product_id: Int,
@Field("quantity") quantity: Array<Int>
): Call<DeleteResponse>
class CartViewModel(context: Application, savedStateHandle: SavedStateHandle) :
AndroidViewModel(context) {
/// val product_id:String?=null
sealed class Result {
object Missing : Result()
object NetworkFailure : Result()
object Success : Result()
}
val product_id: MutableLiveData<String> = savedStateHandle.getLiveData("product_id", "")
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
private var Cart: MutableLiveData<CartResponse>? = null
val CartList: MutableLiveData<CartResponse>?
get() {
if (Cart == null) {
Cart = MutableLiveData<CartResponse>()
loadCartList()
}
return Cart
}
private val loginResultEmitter = EventEmitter<CartViewModel.Result>()
val Results: EventSource<CartViewModel.Result> = loginResultEmitter
private fun loadCartList() {
val token: String =
SharedPrefManager.getInstance(
getApplication()
).user.access_token.toString()
RetrofitClient.instance.listcart(token).enqueue(object :
Callback<CartResponse> {
override fun onFailure(call: Call<CartResponse>, t: Throwable) {
Toast.makeText(getApplication(), "falied", Toast.LENGTH_LONG).show()
}
override fun onResponse(
call: Call<CartResponse>,
response: Response<CartResponse>
) {
if (response.isSuccessful) {
Cart!!.value = response.body()
}
}
})
}
fun loaddelete() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.deletecart(token, id)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
loginResultEmitter.emit(CartViewModel.Result.NetworkFailure)
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.body()?.status == 200) {
Toast.makeText(
getApplication(),
res.body()?.message,
Toast.LENGTH_LONG
).show()
loginResultEmitter.emit(CartViewModel.Result.Success)
} else {
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
fun loadEdit() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.editCart(token, id.toInt(), country)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.isSuccessful) {
Toast.makeText(getApplication(), res.body()?.user_msg, Toast.LENGTH_LONG)
.show()
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
class AddToCart : BaseClassActivity(), OnItemClick {
var progressDialog: ProgressDialog? = null
private val viewModel by viewModels<CartViewModel>()
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_to_cart)
getWindow().setExitTransition(null)
getWindow().setEnterTransition(null)
val progressDialog: ProgressDialog = ProgressDialog(applicationContext);
var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
setSupportActionBar(mActionBarToolbar);
// add back arrow to toolbar
setEnabledTitle()
mActionBarToolbar.setNavigationOnClickListener(View.OnClickListener {
onBackPressed()
})
placeorder.setOnClickListener {
val intent: Intent = Intent(applicationContext, AddressActivity::class.java)
startActivity(intent)
}
loadCart()
}
fun loadCart() {
val model = ViewModelProvider(this)[CartViewModel::class.java]
model.CartList?.observe(this, object : Observer<CartResponse> {
override fun onChanged(t: CartResponse?) {
generateDataList(t?.data?.toMutableList())
totalamount.setText(t?.total.toString())
}
})
}
fun generateDataList(dataList: MutableList<DataCart?>?) {
val recyclerView = findViewById<RecyclerView>(R.id.addtocartrecyleview) as? RecyclerView
val linear: LinearLayoutManager =
LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = linear
val adapter = CartAdapter(this@AddToCart, dataList)
recyclerView?.adapter = adapter
recyclerView?.addItemDecoration(DividerItemDecorator(resources.getDrawable(R.drawable.divider)))
// recyclerView?.setHasFixedSize(true)
adapter.setItemClick(this);
adapter.notifyDataSetChanged()
if (dataList?.isEmpty() ?: true) {
recyclerView?.setVisibility(View.GONE)
totalamount.setVisibility(View.GONE)
fl_footer.setVisibility(View.GONE)
placeorder.setVisibility(View.GONE)
emptytext.setVisibility(View.VISIBLE)
} else {
recyclerView?.setVisibility(View.VISIBLE)
totalamount.setVisibility(View.VISIBLE)
fl_footer.setVisibility(View.VISIBLE)
placeorder.setVisibility(View.VISIBLE)
emptytext.setVisibility(View.GONE)
}
recyclerView?.addOnScrollListener(object :
RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
Log.e("RecyclerView", "onScrollStateChanged")
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
}
})
}
override fun onBackPressed() {
super.onBackPressed()
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
NavUtils.navigateUpFromSameTask(this)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onResume() {
super.onResume()
loadCart()
}
override fun DeleteItem(position: Int, id: Int) {
}
override fun EditItem(position: Int, id: Int) {
viewModel.product_id.value = id.toString()
viewModel.loadEdit()
viewModel.country[position] = country[position]
viewModel.Results.observe(this) { result ->
when (result) {
CartViewModel.Result.Missing -> {
Toast.makeText(
applicationContext, "product is missing", Toast.LENGTH_LONG
).show()
}
CartViewModel.Result.Success -> {
finish()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
startActivity(intent)
overridePendingTransition(0, 0)
}
else -> {
Toast.makeText(applicationContext, "hello", Toast.LENGTH_LONG).show()
}
}
}
}
@FormUrlEncoded
@发布(“编辑车”)
趣味编辑车(
@标头(“访问令牌”)令牌:字符串,
@字段(“产品id”)产品id:Int,
@字段(“数量”)数量:数组
):呼叫
上面的代码在没有实现viewmodel的情况下工作……它正在被编辑并获得成功响应
使用viewmodel实现
viewmodel::-------
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/*** */
val aa: ArrayAdapter <*> =
ArrayAdapter<Any?>(context, android.R.layout.simple_spinner_item, country)
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
holder.spin.setAdapter(aa)
holder.spin.setSelection(dataList?.get(position)?.quantity!! - 1, false)
holder.spin.setOnItemSelectedListener(object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position1: Int,
id: Long
) {
progressDialog.show()
val id = dataList?.get(position)!!.product.id
itemClick?.EditItem(position1, id!!.toInt())
}
override fun onNothingSelected(parent: AdapterView<*>?) {
// todo for nothing selected
}
})
interface OnItemClick {
fun DeleteItem(position: Int, id:Int)
fun EditItem(position: Int,id: Int)
}
var country = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
/* */
override fun EditItem(position: Int, id: Int) {
val token: String = SharedPrefManager.getInstance(applicationContext).user.access_token.toString()
RetrofitClient.instance.editCart(token, id, arrayOf(country[position]))
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(call: Call<DeleteResponse>, response: Response<DeleteResponse>) {
progressDialog?.dismiss()
finish()
var res = response
if (res.isSuccessful) {
Toast.makeText(applicationContext, res.body()?.user_msg, Toast.LENGTH_LONG).show()
progressDialog?.dismiss()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
applicationContext.startActivity(intent)
overridePendingTransition(0, 0)
Log.d("kjsfgxhufb", response.body()?.user_msg.toString())
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(applicationContext, jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG).show()
} catch (e: Exception) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
@FormUrlEncoded
@POST("editCart")
fun editCart(
@Header("access_token") token: String,
@Field("product_id") product_id: Int,
@Field("quantity") quantity: Array<Int>
): Call<DeleteResponse>
class CartViewModel(context: Application, savedStateHandle: SavedStateHandle) :
AndroidViewModel(context) {
/// val product_id:String?=null
sealed class Result {
object Missing : Result()
object NetworkFailure : Result()
object Success : Result()
}
val product_id: MutableLiveData<String> = savedStateHandle.getLiveData("product_id", "")
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
private var Cart: MutableLiveData<CartResponse>? = null
val CartList: MutableLiveData<CartResponse>?
get() {
if (Cart == null) {
Cart = MutableLiveData<CartResponse>()
loadCartList()
}
return Cart
}
private val loginResultEmitter = EventEmitter<CartViewModel.Result>()
val Results: EventSource<CartViewModel.Result> = loginResultEmitter
private fun loadCartList() {
val token: String =
SharedPrefManager.getInstance(
getApplication()
).user.access_token.toString()
RetrofitClient.instance.listcart(token).enqueue(object :
Callback<CartResponse> {
override fun onFailure(call: Call<CartResponse>, t: Throwable) {
Toast.makeText(getApplication(), "falied", Toast.LENGTH_LONG).show()
}
override fun onResponse(
call: Call<CartResponse>,
response: Response<CartResponse>
) {
if (response.isSuccessful) {
Cart!!.value = response.body()
}
}
})
}
fun loaddelete() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.deletecart(token, id)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
loginResultEmitter.emit(CartViewModel.Result.NetworkFailure)
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.body()?.status == 200) {
Toast.makeText(
getApplication(),
res.body()?.message,
Toast.LENGTH_LONG
).show()
loginResultEmitter.emit(CartViewModel.Result.Success)
} else {
try {
val jObjError =
JSONObject(response.errorBody()!!.string())
Toast.makeText(
getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
fun loadEdit() {
val id = product_id.value!!.toString().trim()
val token: String =
SharedPrefManager.getInstance(getApplication()).user.access_token.toString()
RetrofitClient.instance.editCart(token, id.toInt(), country)
.enqueue(object : Callback<DeleteResponse> {
override fun onFailure(call: Call<DeleteResponse>, t: Throwable) {
Log.d("res", "" + t)
}
override fun onResponse(
call: Call<DeleteResponse>,
response: Response<DeleteResponse>
) {
var res = response
if (res.isSuccessful) {
Toast.makeText(getApplication(), res.body()?.user_msg, Toast.LENGTH_LONG)
.show()
} else {
try {
val jObjError = JSONObject(response.errorBody()!!.string())
Toast.makeText(getApplication(),
jObjError.getString("message") + jObjError.getString("user_msg"),
Toast.LENGTH_LONG
).show()
} catch (e: Exception) {
Toast.makeText(getApplication(), e.message, Toast.LENGTH_LONG).show()
Log.e("errorrr", e.message)
}
}
}
})
}
class AddToCart : BaseClassActivity(), OnItemClick {
var progressDialog: ProgressDialog? = null
private val viewModel by viewModels<CartViewModel>()
var country =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.add_to_cart)
getWindow().setExitTransition(null)
getWindow().setEnterTransition(null)
val progressDialog: ProgressDialog = ProgressDialog(applicationContext);
var mActionBarToolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbartable);
setSupportActionBar(mActionBarToolbar);
// add back arrow to toolbar
setEnabledTitle()
mActionBarToolbar.setNavigationOnClickListener(View.OnClickListener {
onBackPressed()
})
placeorder.setOnClickListener {
val intent: Intent = Intent(applicationContext, AddressActivity::class.java)
startActivity(intent)
}
loadCart()
}
fun loadCart() {
val model = ViewModelProvider(this)[CartViewModel::class.java]
model.CartList?.observe(this, object : Observer<CartResponse> {
override fun onChanged(t: CartResponse?) {
generateDataList(t?.data?.toMutableList())
totalamount.setText(t?.total.toString())
}
})
}
fun generateDataList(dataList: MutableList<DataCart?>?) {
val recyclerView = findViewById<RecyclerView>(R.id.addtocartrecyleview) as? RecyclerView
val linear: LinearLayoutManager =
LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = linear
val adapter = CartAdapter(this@AddToCart, dataList)
recyclerView?.adapter = adapter
recyclerView?.addItemDecoration(DividerItemDecorator(resources.getDrawable(R.drawable.divider)))
// recyclerView?.setHasFixedSize(true)
adapter.setItemClick(this);
adapter.notifyDataSetChanged()
if (dataList?.isEmpty() ?: true) {
recyclerView?.setVisibility(View.GONE)
totalamount.setVisibility(View.GONE)
fl_footer.setVisibility(View.GONE)
placeorder.setVisibility(View.GONE)
emptytext.setVisibility(View.VISIBLE)
} else {
recyclerView?.setVisibility(View.VISIBLE)
totalamount.setVisibility(View.VISIBLE)
fl_footer.setVisibility(View.VISIBLE)
placeorder.setVisibility(View.VISIBLE)
emptytext.setVisibility(View.GONE)
}
recyclerView?.addOnScrollListener(object :
RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
Log.e("RecyclerView", "onScrollStateChanged")
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
}
})
}
override fun onBackPressed() {
super.onBackPressed()
val intent = Intent(this, HomeActivity::class.java)
startActivity(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
NavUtils.navigateUpFromSameTask(this)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onResume() {
super.onResume()
loadCart()
}
override fun DeleteItem(position: Int, id: Int) {
}
override fun EditItem(position: Int, id: Int) {
viewModel.product_id.value = id.toString()
viewModel.loadEdit()
viewModel.country[position] = country[position]
viewModel.Results.observe(this) { result ->
when (result) {
CartViewModel.Result.Missing -> {
Toast.makeText(
applicationContext, "product is missing", Toast.LENGTH_LONG
).show()
}
CartViewModel.Result.Success -> {
finish()
val intent = Intent(applicationContext, AddToCart::class.java)
intent.flags =
Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK
startActivity(intent)
overridePendingTransition(0, 0)
}
else -> {
Toast.makeText(applicationContext, "hello", Toast.LENGTH_LONG).show()
}
}
}
}
class CartViewModel(上下文:应用程序,savedStateHandle:savedStateHandle):
AndroidViewModel(上下文){
///val产品标识:字符串?=null
密封类结果{
缺少对象:结果()
对象网络故障:结果()
对象成功:结果()
}
val product_id:MutableLiveData=savedStateHandle.getLiveData(“product_id”,即“”)
var国家=
(1,2,3,4,5,6,7,8)
私有变量购物车:MutableLiveData?=null
val CartList:MutableLiveData?
得到(){
如果(购物车==null){
Cart=MutableLiveData()
loadCartList()
}
返回车
}
private val loginResultEmitter=EventEmitter()
val结果:EventSource=loginResultEmitter
私人娱乐装载车列表(){
val标记:字符串=
SharedPrefManager.getInstance(
getApplication()
).user.access_token.toString()
更新client.instance.listcart(令牌).enqueue(对象:
回拨{
覆盖失效时的乐趣(调用:调用,t:可丢弃){
Toast.makeText(getApplication(),“falied”,Toast.LENGTH_LONG.show())
}
覆盖响应(
呼叫:呼叫,,
答复:答复
) {
if(response.issucessful){
购物车!!.value=response.body()
}
}
})
}
fun loaddelete(){
val id=product_id.value!!.toString().trim()
val标记:字符串=
SharedPrefManager.getInstance(getApplication()).user.access\u token.toString()
更新client.instance.deletecart(令牌,id)
.enqueue(对象:回调{
覆盖失效时的乐趣(调用:调用,t:可丢弃){
loginResultEmitter.emit(CartViewModel.Result.NetworkFailure)
Log.d(“res”和“+t”)
}
覆盖响应(
呼叫:呼叫,,
答复:答复
) {
var res=响应
if(res.body()?.status==200){
Toast.makeText(
getApplication(),
res.body()?.消息,
吐司,长度
).show()
loginResultEmitter.emit(CartViewModel.Result.Success)
}否则{
试一试{
瓦尔·乔布杰罗=
JSONObject(response.errorBody()!!.string())
Toast.makeText(
getApplication(),
jObjError.getString(“消息”)+jObjError.getString(“用户消息”),
吐司,长度
).show()
}捕获(e:例外){
Toast.makeText(getApplication(),e.message,Toast.LENGTH\u LONG.show())
Log.e(“errorr”,e.message)
}
}
}
})
}
fun loadEdit(){
val id=product_id.value!!.toString().trim()
val令牌:Stri