kotlin Cursor.requery () is deprecated. What should I use?
This method was deprecated in API level 15.
Don't use this. Just request a new cursor, so you can do this asynchronously and update your list view once the new cursor comes back.
I'm using requery() in the following code:
class MainActivity : AppCompatActivity() {
lateinit var db:SQLiteDatabase
lateinit var rs:Cursor
lateinit var adapter: SimpleCursorAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var helper = MyHelper(applicationContext)
db= helper.readableDatabase
rs = db.rawQuery("SELECT * FROM TABLE LIMIT 20",null)
btnDelete.setOnClickListener {
db.delete("TABLE","_id=?", arrayOf(rs.getString(0)))
rs.requery() // ??????
}
How should I fix rs.requery() sir
I don't quite understand, hope you can help me
Related
I have a issue in getting a list returned in observe event in my activity. i am developing a login screen in MVVM. viewmodel is as follows.
my problem is i can get returned data in observe call back into a UI control. but same data returned assign into a list variable is empty. in other words, list returned unable to pass into a a list variable in an activity.
class LoginViewModel #Inject internal constructor (private val loginRepository: LoginRepository,private val usersRepository: UsersRepository): ViewModel() {
private var _userEmail:MutableLiveData<String>
private var _userPassword:MutableLiveData<String>
private var _userLoginData:MutableLiveData<UserLoginData>
private var allUsers:MutableLiveData<List<Users>>
private var findUser:MutableLiveData<List<Users>>
init{
_userEmail= MutableLiveData()
_userPassword= MutableLiveData()
_userLoginData= MutableLiveData()
allUsers= MutableLiveData()
findUser= MutableLiveData()
}
fun getEmail():LiveData<String>{
return _userEmail
}
fun getPassword():MutableLiveData<String>{
return _userPassword
}
fun userLogin(userEmail:String,userPassword:String):MutableLiveData<UserLoginData>{
_userEmail.postValue(userEmail)
_userPassword.postValue(userPassword)
viewModelScope.launch(Dispatchers.IO) {
var userlogindata:UserLoginData=loginRepository.userLogin(userEmail,userPassword)
_userLoginData.postValue(userlogindata)
}
return _userLoginData
}
fun getAllUsers():MutableLiveData<List<Users>>{
//lateinit var _allUsers:List<Users>
viewModelScope.launch(Dispatchers.IO) {
val _allUsers:List<Users> =usersRepository.getUsers()
allUsers.postValue(_allUsers)
}
return allUsers
}
fun findUser(userEmail:String):MutableLiveData<List<Users>>{
//lateinit var finduser:List<Users>
viewModelScope.launch(Dispatchers.IO) {
val _findUser:List<Users> =usersRepository.findUser(userEmail)
findUser.postValue(_findUser)
}
return findUser
}
}
in an activity i am observing the users list and getting the list into a list variable in the activity. code in the activity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var loginViewModel: LoginViewModel
lateinit var loginData:UserLoginData
var users:List<Users> = emptyList()
var findUser:List<Users> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
/*observe users list*/
loginViewModel.getAllUsers().observe(this, {It->
users=It
binding.textView.text=It[0].email.toString()
})
loginViewModel.findUser(binding.loginEditTextTextEmailAddressTxt.toString().trim()).observe(this,{it->
findUser=it
})
This program failed if i use data in the users or findUser lists.
Kindly help me to find the best practice in getting the changed data from viewmodel into an activity
ViewModel:
data class User(
var name: String
)
private val _allUsers = MutableLiveData<List<User>>()
private val allUsers: LiveData<List<User>> get() = _allUsers
fun fetchAllUsers(): LiveData<List<User>> {
viewModelScope.launch {
//delay is simulating network request delay
delay(1000)
//listOf is simulating usersRepository.getUsers()
_allUsers.value = listOf(User("name1"), User("name2"), User("name3"))
}
return allUsers
}
Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.fetchAllUsers().observe(viewLifecycleOwner) { userList ->
userList.forEach {
Log.d("user", it.name)
}
}
You can try this way but I do not prefer returning liveData with function because you have to observe liveData once. You need to be careful observe once.
I have problem with RecyclerView into ViewModel.
RecyclerView without viewmodel working perfect.
My MainFragment:
private lateinit var shoppingListViewModel: ShoppingListViewModel
private lateinit var categoryAdapter: CategoryAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shoppingListViewModel = ViewModelProvider(requireActivity())[ShoppingListViewModel::class.java]
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.categoryRV.layoutManager = LinearLayoutManager(requireContext())
shoppingListViewModel.allCategories.observe(viewLifecycleOwner, { <-- when I add this line,
updateCategories(it) crashing my app
})
}
private fun updateCategories(list: List<Category>) {
categoryAdapter = CategoryAdapter(list)
binding.categoryRV.adapter = categoryAdapter
}
My ViewModel:
class ShoppingListViewModel(application: Application) : AndroidViewModel(application) {
private val repository = Repository(application)
val allCategories = repository.showAllCategories()
}
My Repo:
class Repository(app: Application) {
private val shoppingListsDao = ShoppingListDatabaseBuilder.getInstance(app.applicationContext).shoppingListDao()
fun showAllCategories(): LiveData<List<Category>> {
return shoppingListsDao.showAllCategories()
}
}
My Interface Dao:
#Dao
interface ShoppingListDao {
#Query("SELECT * FROM category")
fun showAllCategories(): LiveData<List<Category>>
}
Everything looks good, no errors. I don't know what going on :(
I find my problem.
I need to update of version DB :)
I am trying to figure out how to correctly use the viewLifecycleOwner in MainActivity, I have read and been told lifecycles are used with fragments. However, I am not implementing fragments in my app. When adding observers in the code, I am using "this" in place of viewLifecycleOwner. This would not rise any errors, but will eventually not work as it doesn't bind data properly in the virtual device (when running the app, it only displays a blank page for the app without data or images). So far, what I have in MainActivity is the following code.
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: DrinkViewModel
// Contains all the views
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Use Data Binding to get reference to the views
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.drinkButton.setOnClickListener {
onDrinkClicked()
}
viewModel.revenue.observe(this, Observer { newRevenue ->
binding.revenueText.text = newRevenue.toString()
})
viewModel.drinksSold.observe(this, Observer { newAmount ->
binding.amountSoldText.text = newAmount.toString()
})
}
}
After EpicPandaForce's comment, I focused on whether I was correctly binding the data and images. I realized I was not. I was mistakenly binding revenue and amountSold as texts. I was also trying to set newRevenue and newAmount to strings. Revenue and amountSold were supposed to be passed as Integers. The following code is the correct one.
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: DrinkViewModel
// Contains all the views
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Use Data Binding to get reference to the views
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.drinkButton.setOnClickListener {
onDrinkClicked()
}
viewModel.revenue.observe(this, Observer { newRevenue ->
binding.revenue = newRevenue
})
viewModel.drinksSold.observe(this, Observer { newAmount ->
binding.drinkSold = newAmount
})
}
}
I use retrofit for get data From API. i will displays data ini the maps. data was successfull get from retrofit, but i found problem get data response to fun onMapReady. i don't know to be it
class HomeMapsActivity : AppCompatActivity(), OnMapReadyCallback,
MapHomeContract.View {
private lateinit var mMap: GoogleMap
lateinit var presenter: MapHomePresenter
lateinit var prefsManager: PrefsManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home_maps)
supportActionBar!!.title = "Posisi driver"
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
prefsManager = PrefsManager(this)
presenter = MapHomePresenter(this)
presenter.getAnak(prefsManager.prefsIdUser)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
for (dataAnak in anak) {
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
override fun onResult(dataAnakResponse: AnakResponse) {
dataAnakResponse.anak
}
}
please help
onMapReady() is called when you initially start the Map Activity. You can set the map data in onResult.
override fun onResult(dataAnakResponse: AnakResponse) {
val anak = dataAnakResponse.anak
for (dataAnak in anak) {
// Add a marker in Sydney and move the camera
val sydney = LatLng(-34.0, 151.0)
mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
I want to get input from the user using EditText and pass it to server and show the response to the user. I do this simply without any architecture but I would like to implement it in MVVM.
this is my repository code:
class Repository {
fun getData(context: Context, word: String): LiveData<String> {
val result = MutableLiveData<String>()
val request = object : StringRequest(
Method.POST,
"https://jsonplaceholder.typicode.com/posts",
Response.Listener {
result.value = it.toString()
},
Response.ErrorListener {
result.value = it.toString()
})
{
#Throws(AuthFailureError::class)
override fun getParams(): MutableMap<String, String> {
val params = HashMap<String, String>()
params["word"] = word
return params
}
}
val queue = Volley.newRequestQueue(context)
queue.add(request)
return result
}
}
and these are my View Model codes:
class ViewModel(application: Application) : AndroidViewModel(application) {
fun getData(word: String): LiveData<String> {
val repository = Repository()
return repository.getData(getApplication(), word)
}
}
and my mainActivity would be like this:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val model = ViewModelProviders.of(this).get(ViewModel::class.java)
model.getData("test").observe(this, Observer {
Log.i("Log", "activity $it")
})
}
}
My layout has an EditText which I want to get user input and pass it to the server, how should i do that?
Here how i did it in my projet.
You can probably use android annotations.
It's gonna requiere you to put some dependencies and maybe change the class a bit, but then you gonna link your Viewmodel with your repository and then you gonna have to program the setter of the variable to do a notifyChange() by making the class herited from BaseObservable. Then in the xml, if you did the correctly, you should be able to do a thing like text:"#={model.variable}" and it should be updating at the same time.
A bit hard and explain or to show for me sorry, but i would look into Android Annotations with #DataBinding, #DataBound :BaseObservable
https://github.com/androidannotations/androidannotations/wiki/Data-binding-support
Hope that can help a bit!