I have a program that I am currently working on. I need to make it so when I hit the "delete" button after typing the food name in, it deletes the recycler view item from the list and database. Here's a screen shot of what I mean:
I have copy and pasted some of the main structures that I know I need to modify. I just do not know what exactly I need to do. These sections are commented out.
Here is the code in the MainActivity.kt:
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var adapter: FoodListAdapter? = null
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
adapter = FoodListAdapter(R.layout.food_row)
food_recycler.layoutManager = LinearLayoutManager(this)
food_recycler.adapter = adapter
buttonAdd.setOnClickListener { viewModel.insertFood(Food(editFoodName.text.toString())) }
// buttonDelete.setOnClickListener { viewModel.insertFood(Food(editFoodName.text.toString())) }
viewModel.allFoods?.observe(this, Observer { foods ->
foods?.let {
adapter?.setFoodList(it)
}
})
}
}
The code in FoodDao.kt:
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
#Dao
interface FoodDao {
#Insert
fun insertFood(product: Food)
#Query("SELECT * FROM foods")
fun getAllFoods(): LiveData<List<Food>>
#Query ("SELECT * FROM foods WHERE foodName = :name")
fun findFood(name: String) : List<Food>
}
The code in MainViewModel.kt:
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val repository: FoodRepository =
FoodRepository(application)
var allFoods: LiveData<List<Food>>?
init {
allFoods = repository.allFoods
}
fun insertFood(food: Food) {
repository.insertFood(food)
}
// fun deleteFood(food: Food) {
// repository.deleteFood(food)
// }
}
The code in FoodRepository.kt:
import android.app.Application
import android.os.AsyncTask
import androidx.lifecycle.LiveData
class FoodRepository(application: Application) {
val allFoods: LiveData<List<Food>>?
private var foodDao: FoodDao?
init {
val db: FoodDatabase? =
FoodDatabase.getDatabase(application)
foodDao = db?.foodDao()
allFoods = foodDao?.getAllFoods()
}
fun insertFood(newfood: Food) {
val task = InsertAsyncTask(foodDao)
task.execute(newfood)
}
private class InsertAsyncTask constructor(private val asyncTaskDao: FoodDao?) :
AsyncTask<Food, Void, Void>() {
override fun doInBackground(vararg params: Food): Void? {
asyncTaskDao?.insertFood(params[0])
return null
}
}
// fun deleteFood(newfood: Food) {
// val task = DeleteAsyncTask(foodDao)
// task.execute(newfood)
// }
//
// private class DeleteAsyncTask constructor(private val asyncTaskDao: FoodDao?) :
// AsyncTask<Food, Void, Void>() {
//
// override fun doInBackground(vararg params: Food): Void? {
// asyncTaskDao?.insertFood(params[0])
// return null
// }
// }
}
The thing here is that you need to update your recycler view with your new data:
recyclerView?.notifyDataSetChanged()
first you set the delete method setup.
#Delete
fun deleteFood(product: Food);
your view model method is right and repository method is right.you call method in activity.
buttonDelete.setOnClickListener { viewModel.deleteFood(Food(editFoodName.text.toString())) }
When you call the all foods then you need to update your recycler view with your new data.
viewModel.allFoods?.observe(this, Observer { foods ->
foods?.let {
adapter?.setFoodList(it)
recyclerView?.notifyDataSetChanged()
}
})
Related
I want to init and call a kotlin viewModel from a java class.
this is my viewModel
#HiltViewModel
class PermProdsTestViewModel #Inject constructor(
private val prodsUseCase: ProductUseCase
) : ViewModel() {
private val _prods = MutableStateFlow(ProdsState())
val prods: StateFlow<ProdsState> = _prods
fun getPermittedProducts(serviceName: String?, productTypes: List<String>?, permission: String?, subServiceName: String?, filter: Boolean?) =
viewModelScope.launch(Dispatchers.IO) {
permittedProdsUseCase.invoke(serviceName, productTypes, permission, subServiceName, filter).collect() {
when (it) {
is DataResult.Success -> {
_prods.value = ProdsState(products = it.data)
Timber.d("Api request success, getting results")
}
is DataResult.Error -> {
ProdsState(error = it.cause.localizedMessage ?: "Unexpected Error")
Timber.d("Error getting permitted products")
}
}
}
}}
and I want to call it from a java file activity and use the method.
How can i do it?
Did you maybe forgot to put annotation #AndroidEntryPoint above your class declaration? I tried to access to your ViewModel class from java class and it works for me.
Here is my code:
#AndroidEntryPoint
public class TestActivity extends AppCompatActivity {
private PermProdsTestViewModel vm;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
vm = new ViewModelProvider(this).get(PermProdsTestViewModel.class);
vm.getPermittedProducts();
}
}
I am struggling with viewmodel injection. I have been following tutorials and changed the code a little bit in order to adjust it to my needs, but the app crashes.
I have App class holding my DaggerComponent with it's modules. Inside it's onCreate I have:
component = DaggerAppComponent.builder().daoModule(DaoModule(this)).build()
My AppModule:
#Singleton
#Component(modules = [DaoModule::class, ViewModelModule::class])
interface AppComponent {
val factory: ViewModelFactory
}
ViewModelModule :
#Module
abstract class ViewModelModule {
#Binds
#Singleton
abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory
#Binds
#Singleton
#IntoMap
#ViewModelKey(TaskViewModel::class)
abstract fun splashViewModel(viewModel: TaskViewModel): ViewModel
}
MyFactory:
#Singleton
class ViewModelFactory #Inject constructor(
private val viewModels: MutableMap<Class<out ViewModel>,
#JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
viewModels[modelClass]?.get() as T
}
I used here ViewModelKey, ViewModelModule and Factory, and Fragment extension function to perform Fragment viewmodel injection. I found it online and used it succesfuly on previous projects. This is my util function:
#MainThread
inline fun <reified VM : ViewModel> Fragment.daggerViewModels(
noinline ownerProducer: () -> ViewModelStoreOwner = { this }
) = createViewModelLazy(
VM::class,
{ ownerProducer().viewModelStore },
{ App.component.factory }
)
And my DaoModule.
#Module
class DaoModule(private val app: Application) {
#Provides
#Singleton
fun getDB(): TaskDatabase = TaskDatabase.getAppDatabase(context())
#Provides
#Singleton
fun context(): Context = app.applicationContext
#Provides
fun gettaskDao(taskDatabase: TaskDatabase) : TaskDao = taskDatabase.TaskDao()
}
My entity:
#Entity(tableName = "userinfo")
data class Task(
#PrimaryKey(autoGenerate = true) #ColumnInfo(name = "id") val id: Int = 0,
#ColumnInfo(name = "name") val name: String,
#ColumnInfo(name = "email") val email: String,
#ColumnInfo(name = "phone") val phone: String?
)
My TaskDatabase as follows:
#Database(entities = [Task::class], version = 1)
abstract class TaskDatabase : RoomDatabase() {
abstract fun TaskDao(): TaskDao
companion object {
private var INSTANCE: TaskDatabase? = null
fun getAppDatabase(context: Context): TaskDatabase {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.applicationContext, TaskDatabase::class.java, "AppDBB"
)
.allowMainThreadQueries()
.build()
}
return INSTANCE!!
}
}
}
My Dao interface.
#Dao
interface TaskDao {
#Query("SELECT * FROM userinfo")
fun getAllTaskInfo(): List<Task>?
#Insert
fun insertTask(user: Task?)
#Delete
fun deleteTask(user: Task?)
#Update
fun updateTask(user: Task?)
}
And now I have a logic to init my TaskViewModel inside my Fragment and attach observer to my Task List. However the app crashes.
Inside my fragment I have:
val viewModel: TaskViewModel by daggerViewModels { requireActivity() }
and also:
DaggerFragmentComponent
.builder()
.appComponent((requireActivity().application as App).getAppComponent())
.build()
.inject(this)
viewModel.allTaskList.observe(viewLifecycleOwner) {
// textView.text = it.toString()
}
and my TaskViewModel class is as follows:
class TaskViewModel #Inject constructor(var taskDao: TaskDao) : ViewModel() {
private var _allTaskList = MutableLiveData<List<Task>>()
val allTaskList = _allTaskList as LiveData<List<Task>>
init {
getAllRecords()
}
private fun getAllRecords() = _allTaskList.postValue(taskDao.getAllTaskInfo())
fun insertTask(task: Task) {
taskDao.insertTask(task)
getAllRecords()
}
}
Now I understand that this is A LOT of code, but can somebody help me figure this out? The dagger sees it's graph as I can build the project, so all the dependencies are provided. What I did wrong here? My logcat:
I found the solution myself. This was missing.
implementation 'androidx.room:room-runtime:2.5.0-alpha01'
I have a Client class (written in Kotlin in an Android app) that implements an interface ReadyCallback (written in Java in a library of the app, the app is dependent on this library). In Client I have a createClient() method which will create a client with the parameter of ReadyCallback. If it's ready, I will perform other tasks by calling classC.otherMethod(), if not ready, I just create the client without doing other stuff:
In the library:
// Somewhere in this library, I have logic to call `readyCallback.onReady()` when I consider it's "ready"
interface ReadyCallback {
void onReady()
}
class Manager {
private final ReadyCallback readyCallback;
public void onConnected(final boolean isConnected) {
if (isConnected) {
readyCallback.onReady();
}
}
}
In the app:
class ClassA internal constructor(private val clientProvider: ClassB, private val classC: ClassC, private val classD: ClassD) : ReadyCallback {
fun createClient() {
val client = clientProvider.create(getReadyCallback())
}
private fun getReadyCallback() {
return ReadyCallback { onReady() }
}
override fun onReady() {
logInfo { "It's ready! Now do some stuff by calling classC.otherMethod()" }
classC.otherMethod()
}
}
In unit test, I want to verify that when I create the client and it's ready, classC's otherMethod() will be invoked. I tried to do the following but it's not correct:
import com.nhaarman.mockitokotlin2.*
import org.junit.*
class ClassATest {
lateinit var unitUnderTest: ClassA
lateinit var clientProviderMock: ClassB
lateinit var classCMock: ClassC
lateinit var clientMock: ClassD
#Before
override fun setup() {
super.setup()
clientProviderMock = mock()
classCMock = mock()
clientMock = mock()
unitUnderTest = ClassA(clientProvider = clientProviderMock, classC = classCMock, classD = classDMock)
whenever(clientProviderMock.create(any()).thenReturn(client)
}
#Test
fun `when create client then call otherMethod`() {
unitUnderTest.createClient()
verify(classCMock).otherMethod()
}
}
The error message shows:
Wanted but not invoked:
classC.otherMethod();
Actually, there were zero interactions with this mock.
I think the reason I got this error is because, if I don't call getReadyCallback(), it means I am not invoking the callback, so there's no call to classC.otherMethod(). But other than that I am really stuck on this, I don't know how to unit test my desire behavior (If it's ready, classC.otherMethod() will be called, if not ready, this method won't be called).
I know I can't do things like below because unitUnderTest is not a mock object:
callbackMock = mock()
whenever(unitUnderTest.getReadyCallback()).thenReturn(callbackMock)
whenever(clientProviderMock.create(callbackMock).thenReturn(client)
Can anyone help me out please?
The only way I can think of is to add a boolean flag in callback's onReady() method. So it will become:
In library:
interface ReadyCallback {
void onReady(final boolean isReady)
}
class Manager {
private final ReadyCallback readyCallback;
public void onConnected(final boolean isConnected) {
if (isConnected) {
readyCallback.onReady(true);
} else {
readyCallback.onReady(false);
}
}
}
In app:
class ClassA internal constructor(private val clientProvider: ClassB, private val classC: ClassC, private val classD: ClassD) : ReadyCallback {
fun createClient() {
val client = clientProvider.create(getReadyCallback())
}
private fun getReadyCallback() {
return ReadyCallback { isReady -> onReady(isReady) }
}
override fun onReady(isReady: Boolean) {
if (isReady) {
logInfo { "It's ready! Now do some stuff by calling classC.otherMethod()" }
classC.otherMethod()
}
}
}
In unit test:
import com.nhaarman.mockitokotlin2.*
import org.junit.*
class ClassATest {
lateinit var unitUnderTest: ClassA
lateinit var clientProviderMock: ClassB
lateinit var classCMock: ClassC
lateinit var clientMock: ClassD
#Before
override fun setup() {
super.setup()
clientProviderMock = mock()
classCMock = mock()
clientMock = mock()
unitUnderTest = ClassA(clientProvider = clientProviderMock, classC = classCMock, classD = classDMock)
whenever(clientProviderMock.create(any()).thenReturn(client)
}
#Test
fun `when create client and ready then call otherMethod`() {
unitUnderTest.onReady(true)
unitUnderTest.createClient()
verify(classCMock).otherMethod()
}
#Test
fun `when create client and not ready then do not call otherMethod`() {
unitUnderTest.onReady(false)
unitUnderTest.createClient()
verifyZeroInteractions(classCMock)
}
}
But I still don't know how to test without the boolean parameter in the callback's method. Does anyone know how to do that?
I think I figured it out. I don't need a parameter in onReady().
In library:
interface ReadyCallback {
void onReady()
}
// place to determine when is "ready"
class Manager {
private final ReadyCallback readyCallback;
public void onConnected(final boolean isConnected) {
if (isConnected) {
readyCallback.onReady();
}
}
}
In app:
class ClassA internal constructor(private val clientProvider: ClassB, private val classC: ClassC, private val classD: ClassD) : ReadyCallback {
fun createClient() {
val client = clientProvider.create(getReadyCallback())
}
private fun getReadyCallback() {
return ReadyCallback { onReady() }
}
override fun onReady() {
logInfo { "It's ready! Now do some stuff by calling classC.otherMethod()" }
classC.otherMethod()
}
}
In unit test:
import com.nhaarman.mockitokotlin2.*
import org.junit.*
class ClassATest {
lateinit var unitUnderTest: ClassA
lateinit var clientProviderMock: ClassB
lateinit var classCMock: ClassC
lateinit var clientMock: ClassD
#Before
override fun setup() {
super.setup()
clientProviderMock = mock()
classCMock = mock()
clientMock = mock()
unitUnderTest = ClassA(clientProvider = clientProviderMock, classC = classCMock, classD = classDMock)
whenever(clientProviderMock.create(any()).thenReturn(client)
}
#Test
fun `when create client and ready then call otherMethod`() {
unitUnderTest.onReady()
unitUnderTest.createClient()
verify(classCMock).otherMethod()
}
#Test
fun `when create client and not ready then do not call otherMethod`() {
unitUnderTest.createClient()
verifyZeroInteractions(classCMock)
}
}
I am using MVVM pattern in my app I have separate repository class for network operations. In repository class I am getting response from the server. How can I show Toast message send from the server in my main activity.
Below is my code:
Repository.java
public class MyRepository {
MutableLiveData<List<Facts>> mutableLiveData = new MutableLiveData<>();
Application application;
public MyRepository(Application application) {
this.application = application;
}
public MutableLiveData<List<Facts>> getMutableLiveData(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
apiService.getFacts().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<Facts>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(List<Facts> facts) {
if(facts.size() > 0 && facts != null){
mutableLiveData.setValue(facts);
}
}
#Override
public void onError(Throwable e) {
TastyToast.makeText(application,e.getMessage(),TastyToast.LENGTH_SHORT,
TastyToast.ERROR).show();
}
#Override
public void onComplete() {
}
});
return mutableLiveData;
}
}
FactsViewModel.java
public class FactsViewModel extends AndroidViewModel {
MyRepository repo;
public FactsViewModel(#NonNull Application application) {
super(application);
repo = new MyRepository(application);
}
public LiveData<List<Facts>> getAllFacts(){
return repo.getMutableLiveData();
}
}
MainActivity.java
private void myFacts(){
FactsViewModel viewModel = new ViewModelProvider(this).get(FactsViewModel.class);
viewModel.getAllFacts().observe(this, new Observer<List<Facts>>() {
#Override
public void onChanged(List<Facts> facts) {
adapter = new FactsAdapter(facts,getActivity());
recycle.setAdapter(adapter);
}
});
}
How can I show error toast messages in MainActivity?
To implement that you firstly need to create a class which has the status of the response ,
Loading which is before the fetching of the data and there you can set progress bar to visible then on success you would set the data to your adapter and right after your hide your progress bar and in the on failure one , you show the toast message error
This is the generic class
class AuthResource<T>(
var authStatus : AuthStatus? = null,
var data : T,
var msg : String? = null
)
fun <T> success(#Nullable data: T): AuthResource<T> {
return AuthResource(
AuthStatus.Success,
data,
null
)
}
fun <T> Error(#NonNull msg: String?, #Nullable data: T) : AuthResource<T>? {
return AuthResource(
AuthStatus.ERROR,
data,
msg
)
}
fun <T> loading(#Nullable data: T): AuthResource<T>? {
return AuthResource(
AuthStatus.LOADING,
data,
null
)
}
enum class AuthStatus {
Success, ERROR, LOADING
}
This is my view model where i implement the authResource with the api response
class MainViewModel #Inject constructor( private var webAuth: WebAuth,
private var favFoodDao: FavFoodDao,
private var application: Application) : ViewModel() {
/// you have to create MediatorLiveData with authresource which contains your modelclass
private var mediatorLiveData = MediatorLiveData<AuthResource<WrapLatestMeals>>()
///Here you return a livedata object
fun ObserverCountries(): LiveData<AuthResource<WrapCountries>> {
var liveData = LiveDataReactiveStreams.fromPublisher(
webAuth.getCountries()
///onerrorreturn , rxjava operator which returns error in case
///of response failure
.onErrorReturn(object : Function<Throwable, WrapCountries> {
override fun apply(t: Throwable): WrapCountries {
var country = WrapCountries()
return country
}
})
.map(object : Function<WrapCountries,
AuthResource<WrapCountries>> {
override fun apply(t: WrapCountries):
AuthResource<WrapCountries> {
if(t.meals.isNullOrEmpty())
{
return Error(
"Error",
t
)!!
}
return success(t)
}
})
.subscribeOn(Schedulers.io())
)
//add that data to mediatorLivedata
mediatorLiveDataCountries.addSource(liveData, Observer {
mediatorLiveDataCountries.postValue(it)
mediatorLiveDataCountries.removeSource(liveData)
})
return mediatorLiveDataCountries
}
This is how you handle the status in your MainActivity
mainViewModel = ViewModelProvider(this,provider)[MainViewModel::class.java]
mainViewModel.ObserverCountries().observe(viewLifecycleOwner, Observer {
when(it.authStatus) {
AuthStatus.LOADING -> /// here you show progressbar in response pre-fetch
{
countriesFragmentBinding.countryprogress.show()
}
AuthStatus.Success -> { // here you update your ui
countriesAdapter = CountriesAdapter(it.data.meals!!,
requireContext())
countriesFragmentBinding.recyclercountries.adapter = countriesAdapter
countriesAdapter!!.deleteCategory(23)
countriesFragmentBinding.countryprogress.hide()
}
AuthStatus.ERROR -> // here you hide your progressbar and show your toast
{
countriesFragmentBinding.countryprogress.hide()
ToastyError(requireContext(),getString(R.string.errorretreivingdata))
}
}
})
return countriesFragmentBinding.root
}
}
I'm trying to fetch some data with Retrofit on my Android project update this on the ViewModel and my activity with LiveData.
Here is my service Class:
class PaymentService {
private var paymentMethodList = ArrayList<PaymentMethodModel>()
private val paymentMethodListLiveData = MutableLiveData<List<PaymentMethodModel>>()
init {
paymentMethodListLiveData.value = paymentMethodList
}
fun fetchPaymentMethods() {
val retrofit = Retrofit.Builder()
.baseUrl(SERVICE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(PaymentClient::class.java)
val jsonCall = service.getListOfPaymentMethods()
jsonCall.enqueue(object : Callback<List<PaymentMethodModel>> {
override fun onResponse(call: Call<List<PaymentMethodModel>>, response: Response<List<PaymentMethodModel>>) {
paymentMethodList = (response.body() as ArrayList<PaymentMethodModel>?)!!
}
override fun onFailure(call: Call<List<PaymentMethodModel>>, t: Throwable) {
//TODO
}
})
}
And here is where I'm trying to listen to the changes on the list:
goToNextButton.setOnClickListener {
paymentMethods = PaymentMethodSelectionViewModel().getAllPaymentMethods()
paymentMethods!!.observe(viewLifecycleOwner, Observer {
Log.e("", "")
})
}
The problem is that so far I'm getting the list only the first time with 0 elements and this observer method is not getting called after the rest call is made and the list updated.
Edit
class PaymentRepository {
private val paymentService = PaymentService()
fun getPaymentMethods(): LiveData<List<PaymentMethodModel>> {
paymentService.fetchPaymentMethods()
return paymentService.getPaymentMethods()
}
}
class PaymentMethodSelectionViewModel: ViewModel() {
private val paymentRepository = PaymentRepository()
private val paymentMethods = paymentRepository.getPaymentMethods()
fun getAllPaymentMethods(): LiveData<List<PaymentMethodModel>> {
paymentRepository.getPaymentMethods()
return paymentMethods
}
}
Change your request into viewmodel
class PaymentMethodSelectionViewModel: ViewModel() {
//Data
var paymentMethodList = MutableLiveData<List<PaymentMethodModel>>()
fun getAllPayments(){
val retrofit = Retrofit.Builder()
.baseUrl(SERVICE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
val service = retrofit.create(PaymentClient::class.java)
val jsonCall = service.getListOfPaymentMethods()
jsonCall.enqueue(object : Callback<List<PaymentMethodModel>> {
override fun onResponse(call: Call<List<PaymentMethodModel>>, response: Response<List<PaymentMethodModel>>) {
var data: List<PaymentMethodModel> = (response.body() as ArrayList<PaymentMethodModel>?)!!
paymentMethodList.value=data
}
override fun onFailure(call: Call<List<PaymentMethodModel>>, t: Throwable) {
//TODO
}
})
}
}
in your view (activity) use
//load
paymentMethodSelectionViewModel.getAllPayments();
//Observers
paymentMethodSelectionViewModel.paymentMethodList.observe(this,
Observer { list ->
// your code
})
I recommend you use retrofit 2 with corutines or RXJAVA2,
check this tutorial
https://medium.com/#amtechnovation/android-architecture-component-mvvm-part-1-a2e7cff07a76
https://medium.com/#saquib3705/consuming-rest-api-using-retrofit-library-with-the-help-of-mvvm-dagger-livedata-and-rxjava2-in-67aebefe031d
As #tyczj says in the comment, every time you use a LiveData, you have to decide when all the observers receive an update notification.
You can do this notification by calling post function of your paymentMethodListLiveData object. This is the correct way to use LiveData in Java.
In Kotlin I think you have to add something like this on your onResponse method:
paymentMethodListLiveData.value = paymentMethodList;
to implicitly call the post method and trigger methods in your observe function.
Hope this help or give you some hints.
Cheers