Kotlin-android unresolved reference : queue - android

I imported retrofi2.Callback
and I still get this error unresolved reference: enqueue
this is the code of the login class
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.cbmis.imageapp.Common.Common
import com.cbmis.imageapp.Model.APIResponse
import com.cbmis.imageapp.Remote.IMyAPI
import kotlinx.android.synthetic.main.activity_login.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class LoginActivity : AppCompatActivity() {
internal lateinit var mService:IMyAPI
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
//initservice
mService = Common.api
//Event
txtregister.setOnClickListener { startActivity(Intent(this#LoginActivity,RegisterActivity::class.java))
finish()
}
btn_login.setOnClickListener { authentificateUser(findViewById<TextView>(R.id.email).text.toString(), findViewById<TextView>(R.id.password).text.toString()) }
}
private fun authentificateUser(email: String, password: String) {
mService.loginUser(email, password)
.enqueue(object :Callback<APIResponse> {
override fun onFailure(call: Call<APIResponse>?, t: Throwable?) {
Toast.makeText(this#LoginActivity,t!!.message,Toast.LENGTH_SHORT).show()
}
override fun onResponse(call: Call<APIResponse>?, response: Response<APIResponse>?) {
if (response!!.body()!!.error)
Toast.makeText(this#LoginActivity,response!!.body()!!.errr_msg,Toast.LENGTH_SHORT).show()
else
Toast.makeText(this#LoginActivity, "Login Success!",Toast.LENGTH_SHORT).show()
}
})
}
}
and this is the interface/
interface IMyAPI {
#FormUrlEncoded
#POST("signup.php")
fun registerUser(#Field("email") email:String,#Field("name")name:String,#Field("password") password:String,#Field("dateofbirth") dateofbirth:String,#Field("genderM") genderM:String,#Field("genderF") genderF:String):Class<APIResponse>
#FormUrlEncoded
#POST("login.php")
fun loginUser(#Field("email") email:String,#Field("password") password:String):Class<APIResponse>
}
Any solutions can be proposed to solve this problem

You should be returning a Retrofit Call from your API's functions:
interface IMyAPI {
#FormUrlEncoded
#POST("signup.php")
fun registerUser(/* params */) : Call<APIResponse>
#FormUrlEncoded
#POST("login.php")
fun loginUser(/* params */): Call<APIResponse>
}

Related

None of the following functions can be called with the arguments supplied: public suspend fun delay(timeMillis: Long):

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
class SplashScreen : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
private val SPLASH_DISPLAY_LENGTH = 5000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
progressBar = findViewById(R.id.progressBar)
GlobalScope.launch(Dispatchers.Main) {
delay(SPLASH_DISPLAY_LENGTH)
progressBar.visibility = View.VISIBLE
loadWebView()
}
}
private suspend fun loadWebView() {
withContext(Dispatchers.IO) {
delay(SPLASH_DISPLAY_LENGTH)
}
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
This is a Splash Screen. I got this error - None of the following functions can be called with the arguments supplied:public suspend fun delay(timeMillis: Long): Unit defined in kotlinx.coroutinespublic suspend fun delay(duration: Duration): Unit defined in kotlinx.coroutines. Can anybody help me please. Thanks in Advance.
I got it. I removed SPLASH_DISPLAY_LENGTH and added the duration directly like this- delay(5000). It worked --
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
#OptIn(DelicateCoroutinesApi::class)
#SuppressLint("CustomSplashScreen")
class SplashScreen1 : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
progressBar = findViewById(R.id.progrssBar2)
GlobalScope.launch(Dispatchers.Main) {
delay(3000)
progressBar.visibility = View.VISIBLE
loadWebView()
}
}
private suspend fun loadWebView() {
withContext(Dispatchers.IO) {
delay(3000)
}
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}
It is another answer thanks to #Tenfour04. Comment
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*
class SplashScreen1 : AppCompatActivity() {
private lateinit var progressBar: ProgressBar
//Define the constant as long instead of int
private val SPLASH_DISPLAY_LENGTH = 5000L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen)
progressBar = findViewById(R.id.progress_circular)
GlobalScope.launch(Dispatchers.Main) {
delay(SPLASH_DISPLAY_LENGTH)
progressBar.visibility = View.VISIBLE
loadWebView()
}
}
private suspend fun loadWebView() {
withContext(Dispatchers.IO) {
delay(SPLASH_DISPLAY_LENGTH)
}
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}

Object is not abstract and does not implement abstract member public abstract fun error

Am trying to run kotlin native code inside my flutter app ,, here is how my kotlin code look slike
package com.deliveryrunner.driver
import android.content.*
import io.flutter.embedding.android.FlutterActivity
import androidx.annotation.NonNull
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import android.content.Intent
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import android.location.Location
class MainActivity : FlutterActivity() {
private val LOCATION_CHANNEL = "com.deliveryrunner.driver/getCurrentLocation";
private lateinit var channel: MethodChannel
private lateinit var fusedLocationClient: FusedLocationProviderClient
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler {
call, result ->
if (call.method == "currentLocation") {
val arguments = call.arguments() as Map<String, String>
val test = arguments["test"]
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location ->
result.success("got the loation")
}
}
}
}
}
but I am getting this error whenever I run the app
e: D:\Flutter\src\flutter\.pub-cache\hosted\pub.dartlang.org\workmanager-0.4.1\android\src\main\kotlin\be\tramckrijte\workmanager\BackgroundWorker.kt: (132, 21): Object is not abstract and does not implement abstract member public abstract fun error(p0: String, p1: String?, p2: Any?): Unit defined in io.flutter.plugin.common.MethodChannel.Result
e: D:\Flutter\src\flutter\.pub-cache\hosted\pub.dartlang.org\workmanager-0.4.1\android\src\main\kotlin\be\tramckrijte\workmanager\BackgroundWorker.kt: (137, 25): 'error' overrides nothing

Getting FATAL EXCEPTION while running the applications second screen

I am working on a android application that is NewsApp. I had made 2 activity. First is MainActivity and Second is HomeActivity. There is a button on MainActivity that is Register. If user press the button the MainActivity will be finish and HomeActivity appears but in my case when the user click register button the HomeActivity is not appearing and emulator show "App has stopped".
Since I am new to this I am not able to spot where the problem is and don't know how I can resolve it.
Thanks in advance.
The Error I am getting is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.newsapp, PID: 8723
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.project.newsapp.HomeActivity.onResponse(HomeActivity.kt:108)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
I am also attaching my HomeActivity and MainActivity code so you can tell me where I am doing it wrong.
My HomeActivity Code:
package com.project.newsapp
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.project.newsapp.contract.Request
import com.project.newsapp.contract.Response
import com.project.newsapp.network.IRequestContract
import com.project.newsapp.network.NetworkClient
import com.project.newsapp.utils.Constant
import com.project.newsapp.utils.DataProvider
import com.project.newsapp.utils.showToast
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.activity_home.btnExit
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
class HomeActivity : AppCompatActivity(), Callback<Response>, View.OnClickListener {
lateinit var userId:String
lateinit var userName:String
private val retrofitClient = NetworkClient.getNetworkClient()
private val requestContract = retrofitClient.create(IRequestContract::class.java)
private lateinit var sharedPreferences: SharedPreferences
private lateinit var progressDialog: ProgressDialog
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
progressDialog = ProgressDialog(this)
progressDialog.setMessage("Please wait...")
progressDialog.setCancelable(true)
sharedPreferences = getSharedPreferences(Constant.PREF_NAME, Context.MODE_PRIVATE)
title = "NewsApp"
userId = intent.getStringExtra(Constant.KEY_USER_ID).toString()
userName = intent.getStringExtra(Constant.KEY_USER_NAME).toString()
txtUserName.text = "Welcome $userName"
btnAllNews.setOnClickListener (this)
btnMyNews.setOnClickListener (this)
btnSignOut.setOnClickListener (this)
btnExit.setOnClickListener (this)
}
override fun onStart() {
super.onStart()
progressDialog.show()
val request = Request(
action = Constant.GET_NEWS,
userId = userId
)
val callResponse = requestContract.makeApiCall(request)
callResponse.enqueue(this)
}
override fun onClick(v: View?) {
when(v?.id){
R.id.btnAllNews -> {
if(DataProvider.response.allNews.size>0){
Intent(this,ViewAllNewsActivity::class.java).apply {
startActivity(this)
}
}else{
showToast("Blogs are not available")
}
}
R.id.btnMyNews -> {
}
R.id.btnSignOut -> {
signOut()
}
}
}
private fun signOut(){
val editor = sharedPreferences.edit()
editor.clear().commit()
Intent(this,MainActivity::class.java).apply{
startActivity(this)
finish()
}
}
override fun onResponse(call: Call<Response>, response: retrofit2.Response<Response>) {
if(progressDialog.isShowing)
progressDialog.dismiss()
if(response.body()!=null){
val serverResponse = response.body()
if(serverResponse!!.status){
DataProvider.response = serverResponse
}else{
showToast(serverResponse.message)
edUserName.setText("")
}
}
else{
showToast("Server is not responding. Please try again later.")
}
}
override fun onFailure(call: Call<Response>, t: Throwable) {
if(progressDialog.isShowing)
progressDialog.dismiss()
showToast("Server is not responding. Please try again later.")
}}
My MainActivity Code:
package com.project.newsapp
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.project.newsapp.contract.Request
import com.project.newsapp.contract.Response
import com.project.newsapp.network.IRequestContract
import com.project.newsapp.network.NetworkClient
import com.project.newsapp.utils.Constant
import com.project.newsapp.utils.showToast
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
class MainActivity : AppCompatActivity(), Callback<Response> {
private val retrofitClient = NetworkClient.getNetworkClient()
private val requestContract = retrofitClient.create(IRequestContract::class.java)
private lateinit var progressDialog:ProgressDialog
private lateinit var sharedPreferences:SharedPreferences
lateinit var userName:String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressDialog = ProgressDialog(this)
progressDialog.setMessage("Please wait...")
progressDialog.setCancelable(true)
sharedPreferences = getSharedPreferences(Constant.PREF_NAME, Context.MODE_PRIVATE)
checkIfUserAlreadyRegistered()
btnRegister.setOnClickListener {
userName = edUserName.text.toString().trim().uppercase()
if(userName.isNullOrEmpty()){
showToast("Please Enter your Name")
}else{
progressDialog.show()
val request = Request(
action = Constant.REGISTER_USER,
userName = userName
)
val callResponse = requestContract.makeApiCall(request)
callResponse.enqueue(this)
}
}
/*btnExit.setOnClickListener {
finish()
}*/
}
override fun onFailure(call: Call<Response>, t: Throwable) {
if(progressDialog.isShowing)
progressDialog.dismiss()
showToast("Server is not responding. Please try again later.")
edUserName.setText("")
}
override fun onResponse(call: Call<Response>, response: retrofit2.Response<Response>) {
if(progressDialog.isShowing)
progressDialog.dismiss()
if(response.body()!=null){
val serverResponse = response.body()
if(serverResponse!!.status){
saveUserToPref(serverResponse.userId,userName)
Intent(this, HomeActivity::class.java).apply {
putExtra(Constant.KEY_USER_ID, serverResponse.userId)
putExtra(Constant.KEY_USER_NAME, userName)
startActivity(this)
finish()
}
}else{
showToast(serverResponse.message)
edUserName.setText("")
}
}
else{
showToast("Server is not responding. Please try again later.")
edUserName.setText("")
}
}
private fun saveUserToPref(userId:String, userName:String){
val editor = sharedPreferences.edit()
editor.putString(Constant.KEY_USER_ID,userId)
editor.putString(Constant.KEY_USER_NAME,userName)
editor.commit()
}
private fun checkIfUserAlreadyRegistered(){
val userId = sharedPreferences.getString(Constant.KEY_USER_ID,"invalid user id")
val userName = sharedPreferences.getString(Constant.KEY_USER_NAME,"invalid user name")
if(!userId.contentEquals("invalid user id")
&& !userName.contentEquals("invalid user name")){
Intent(this, HomeActivity::class.java).apply {
putExtra(Constant.KEY_USER_ID, userId)
putExtra(Constant.KEY_USER_NAME, userName)
startActivity(this)
finish()
}
}
}}
Kotlin synthetic accessors are deprecated.
One of the reasons why they are deprecated is that they lead to the error that you are seeing. edUserName appears to be null, implying that R.layout.activity_home does not actually have a widget whose ID maps to edUserName.
The problem may come from:
import kotlinx.android.synthetic.main.activity_main.*
Most likely, that should not be in HomeActivity, since you are not using activity_main there.

Kotlin livedata observer not triggered

i'm practising a bit with kotlin and was testing Room and livedata, my app gets data from a json and the stores it in room, i want to move this network call to its own file and class, but if i do so the observer i set to get the changes don't trigger anymore, any help would be appreciated
here is a snipped of my mainactivity, if more is needed to know what happens please let me know
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import androidx.room.Room
import com.optiva.videoplayer.data.*
import com.optiva.videoplayer.network.GetData
import com.optiva.videoplayer.network.Networking
import com.optiva.videoplayer.network.RetrofitConnect
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbcategories = Room.databaseBuilder(applicationContext, CategoriesDatabase::class.java,"categories.db").build()
val dbvideo = Room.databaseBuilder(applicationContext, VideosDatabase::class.java,"videos.db").build()
val retrofitData = RetrofitConnect.retrofitInst?.create(GetData::class.java)
val categoriesList = retrofitData?.getAll()
categoriesList?.enqueue(object: Callback<DataList> {
override fun onResponse(
call: Call<DataList>,
response: Response<DataList>
) {
val test = response?.body()
val cat = test?.categories
val vid = test?.videos
lifecycleScope.launch(Dispatchers.IO) {
if (cat != null) {
for(c in cat){
dbcategories.categoriesDAO().insertAll(CategoriesEntity(c.id,c.title,c.type))
}
}
if (vid != null) {
for(v in vid){
dbvideo.VideosDAO().insertAll(VideosEntity(v.id,v.thumb,v.videoUrl,v.categoryId,v.name))
}
}
}
}
override fun onFailure(call: Call<DataList>, t: Throwable) {
Toast.makeText(applicationContext,"error", Toast.LENGTH_LONG).show()
}
})
val textView: TextView = findViewById(R.id.test) as TextView
dbcategories.categoriesDAO().getALL().observeForever({categories ->
if(categories.size>0){
textView.text= categories[0].title
}
})
dbcategories.categoriesDAO().getALL().observe(this, {categories ->
if(categories.size>0){
textView.text= categories[0].title
}
}
} ```

Learning Kotlin and stuck with ArrayAdapter

I am learning Kotlin and all was going well until it stopped working, the only thing I changed were the references.
I've tried to adjust the "this" parameter and it has not worked,
Here is my code:
package com.example.myweatherapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ForecastActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_forecast)
var retriever = WeatherRetriever()
val callback = object : Callback<Weather> {
override fun onFailure(call: Call<Weather>?, t: Throwable) {
println("It failed")
}
override fun onResponse(
call: Call<Weather>?, response: Response<Weather>?) {
println("It wORKED")
println(response?.body()?.main)
title = response?.body()?.name
var forecasts = response?.body()?.main
var castListView = findViewById<ListView>(R.id.forecastListView)
var adapter = ArrayAdapter(this#ForecastActivity,android.R.layout.simple_list_item_1,forecasts)
castListView.adapter=adapter
}
}
retriever.getForecast(callback)
}
}
I am getting the following error: "None of the following functions can be called with the arguments supplied:"
Any help for a newbie?
Thanks a lot!
Edit: Here is the weather class
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
interface weatherAPI{
#GET("weather?id=3621224&units=metric&appid=ff2563aab36fc89bc7a3c4fe58dd7f3e")
fun getForecast() : Call<Weather>
}
class Weather(val main: WeatherForecast, val name: String )
class WeatherForecast (val main: List<main>)
class main (val temp: String, val feels_like: String, val temp_min: String, val temp_max: String)
class WeatherRetriever {
val service : weatherAPI
init {
val retrofit= Retrofit.Builder().baseUrl("https://api.openweathermap.org/data/2.5/").addConverterFactory(GsonConverterFactory.create()).build()
service = retrofit.create(weatherAPI::class.java)
}
fun getForecast(callback : Callback<Weather>){
val call = service.getForecast()
call.enqueue(callback)
}
}

Categories

Resources