Adding ScrollBar in Kotlin class - android

I am having trouble ScrollBar it shows error when I add it in a Kotlin class. Import library is also showing an error. What should I do? Below is the code:
import android.widget.Toast
import com.github.barteksc.pdfviewer.PDFView
import com.github.barteksc.pdfviewer.ScrollBar
import kotlinx.android.synthetic.main.activity_pdf.view.*
import java.io.File
class PDF_Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pdf)
val pdfView = findViewById(R.id.pdfView) as PDFView
val scrollBar = findViewById<ScrollBar>(R.id.scrollBar)
pdfView.setScrollBar(scrollBar)
scrollBar.setHorizontal(false)
val i = this.intent
val path = i.extras!!.getString("PATH")
val file = File(path!!)
if (file.canRead()) {
pdfView.fromFile(file).defaultPage(1).onLoad { nbPages -> Toast.makeText(this#PDF_Activity, nbPages.toString(), Toast.LENGTH_LONG).show() }.load()
}

Related

Why is "image" in .into red

I don't understand why "image" in .into is underlined in red.
I just need the picture to be shown by clicking on the button
enter image description here
package com.example.raspisanie
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val image = findViewById<View>(R.id.image)
val button = findViewById<View>(R.id.button)
val url = "https://vsegda-pomnim.com/uploads/posts/2022-04/1649143490_6-vsegda-pomnim-com-p-priroda-islandii-foto-8.jpg"
button.setOnClickListener {
Glide.with(this)
.load(url)
.into(image)
}
}
}
It is due to type mismatch. The type of image should be ImageView. Change val image = findViewById<View>(R.id.image) to val image = findViewById<ImageView>(R.id.image)

I encountered a problem while following a tutorial on building an app with Kotlin

The error that appears is as follows "Type mismatch: inferred type is String? but String is expected". How can I solve this problem?
The source code is as follows:
package com.example.submission2.Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.example.submission2.Adapter.AdapterSectionPager
import com.example.submission2.ViewModel.DetailVM
import com.example.submission2.databinding.ActivityDetailBinding
class DetailActivity : AppCompatActivity() {
companion object{
const val EXTRA_USERNAME = "extra_username"
}
private lateinit var binding: ActivityDetailBinding
private lateinit var viewModel: DetailVM
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowHomeEnabled(true)
}
val username = intent.getStringExtra(EXTRA_USERNAME)
viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(DetailVM::class.java)
viewModel.setPenggunaDetail(username)
viewModel.getPenggunaDetail().observe(this) {
if (it != null) {
binding.apply {
tvNamaDetail.text = it.name
tvUsernameDetail.text = it.login
tvCompanyDetail.text = it.company
tvEmailDetail.text = it.email
tvFollowersDetail.text = "${it.followers} Followers"
tvFollowingDetail.text = "${it.following} Follwing"
Glide.with(this#DetailActivity)
.load(it.avatar_url)
.transition(DrawableTransitionOptions.withCrossFade())
.centerCrop()
.into(ivDetailProfil)
}
}
}
val sectionPagerAdpter = AdapterSectionPager(this,supportFragmentManager)
binding.apply {
viewPager.adapter = sectionPagerAdpter
tabs.setupWithViewPager(viewPager)
}
}
}
error appears on the line "viewModel.set User Data(username)" username is used in extra_username which will be called in main
for main activity as follows:
package com.example.submission2.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.submission2.Adapter.AdapterPengguna
import com.example.submission2.DataBase.Pengguna
import com.example.submission2.R
import com.example.submission2.ViewModel.MainVM
import com.example.submission2.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel: MainVM
private lateinit var adapter: AdapterPengguna
private fun searchPengguna(){
binding.apply {
val query = etSearch.text.toString()
if (query.isEmpty())return
showLoading(true)
viewModel.setSearchPengguna(query)
}
}
private fun showLoading(state: Boolean){
if (state){
binding.progressBarMain.visibility = View.VISIBLE
}else{
binding.progressBarMain.visibility = View.GONE
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
adapter = AdapterPengguna()
adapter.notifyDataSetChanged()
adapter.setOnItemClickCallback(object :AdapterPengguna.OnItemClickCallback{
override fun onItemCliked(data: Pengguna) {
Intent(this#MainActivity,DetailActivity::class.java).also {
it.putExtra(DetailActivity.EXTRA_USERNAME, data.login)
startActivity(it)
}
}
})
viewModel = ViewModelProvider(this,ViewModelProvider.NewInstanceFactory()).get(MainVM::class.java)
binding.apply {
rvPengguna.layoutManager = LinearLayoutManager(this#MainActivity)
rvPengguna.setHasFixedSize(true)
rvPengguna.adapter = adapter
btnSearch.setOnClickListener {
searchPengguna()
}
etSearch.setOnKeyListener { v, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER){
searchPengguna()
return#setOnKeyListener true
}
return#setOnKeyListener false
}
}
viewModel.getSearchPengguna().observe(this,{
if (it!= null){
adapter.setList(it)
showLoading(false
)
}
})
}
}
In your code there is no such line as viewModel.setUserData
I guess that the error occurs in the line viewModel.setPenggunaDetail(username)
In this case, you should pay attention to the fact that the all intent.getExtra calls returns nullable values.
Thus, if the setPenggunaDetail call expects a non-nullable argument, you must first check username value for null

I am not able to validate my new activity

I created a new empty activity for my project but I am getting an error. The activity file as well as the layout file is shown in red color. I tried creating an intent object from MainActivity, in order to start this activity but received the following error
Classifier 'Details' does not have a companion object, and thus must
be initialized here
I've attached a screenshot of my android studio.
Code for new activity
package com.example.safetyapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class Details : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
}
}
package com.example.safetyapp
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.firebase.ui.auth.AuthUI
import com.google.firebase.auth.FirebaseAuth
class MainActivity : AppCompatActivity() {
final val AUTH_REQUEST_CODE = 7192
lateinit var firebaseAuth:FirebaseAuth
lateinit var listener: FirebaseAuth.AuthStateListener
lateinit var providers: List<AuthUI.IdpConfig>
override fun onStart(){
super.onStart()
firebaseAuth.addAuthStateListener(listener)
}
override fun onStop(){
super.onStop()
if(listener!=null){
firebaseAuth.removeAuthStateListener(listener)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button2 = findViewById<Button>(R.id.button2)
val defence = findViewById<Button>(R.id.Defence)
button2.setOnClickListener{
val myintent = Intent(this, Details::class.java)
}
init()
}
private fun init() {
providers = arrayListOf(AuthUI.IdpConfig.PhoneBuilder().build(),
AuthUI.IdpConfig.EmailBuilder().build())
firebaseAuth = FirebaseAuth.getInstance()
listener = object:FirebaseAuth.AuthStateListener{
override fun onAuthStateChanged(p0: FirebaseAuth) {
val user = p0.currentUser
if(user!= null){
// Do something
}
else{
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setLogo(R.drawable.logo)
.build(),AUTH_REQUEST_CODE)
}
}
}
}
}
You didn't import the Details class, add this line between your MainActivity class imports
import com.example.safetyapp.Details

How can I pass data (image) from RecyclerView to a separate Activity in Kotlin?

I'm trying to pass data from a RecyclerView that contains a list of photos to a separate Activity that should show Details about the selected photo.
since im new to Kotlin, i've tried a lot and failed to come up with a solution.. I'd be thankful if anyone has a word on this.
PhotosActivity.kt
package com.example.wallpaperapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class PhotosActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_photos)
val recyclerPhotos = findViewById<RecyclerView>(R.id.rv_photo)
recyclerPhotos.layoutManager = LinearLayoutManager(this)
recyclerPhotos.adapter = PhotosAdapter(getPhotosData(), this)
}
private fun getPhotosData(): List<PhotoModel>{
return listOf(
PhotoModel(R.drawable.photo1),
PhotoModel(R.drawable.photo2),
PhotoModel(R.drawable.photo3),
PhotoModel(R.drawable.photo4),
PhotoModel(R.drawable.photo5),
PhotoModel(R.drawable.photo6),
PhotoModel(R.drawable.photo7),
PhotoModel(R.drawable.photo8)
)
}
}
PhotosModel.kt
package com.example.wallpaperapp
import java.io.Serializable
data class PhotoModel(
val image: Int,
): Serializable
PhotosAdapter.kt
package com.example.wallpaperapp
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
class PhotosAdapter(val listOfPhotos: List<PhotoModel>,
val context: Activity): RecyclerView.Adapter<PhotosAdapter.ViewHolder>() {
inner class ViewHolder(view: View): RecyclerView.ViewHolder(view){
val img = view.findViewById<ImageView>(R.id.img_test)
init{
itemView.setOnClickListener {
val intent = Intent(context, PhotoDetailsActivity::class.java)
intent.putExtra("PHOTO", listOfPhotos[adapterPosition])
context.startActivity(intent)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotosAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_photo, parent,false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return listOfPhotos.size
}
override fun onBindViewHolder(holder: PhotosAdapter.ViewHolder, position: Int) {
holder.img.setImageResource(listOfPhotos[position].image)
}
}
PhotoDetailsActivity.kt
package com.example.wallpaperapp
import android.app.WallpaperManager
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.ViewCompat.setBackground
class PhotoDetailsActivity : AppCompatActivity() {
lateinit var arrow: ImageView
lateinit var img: ImageView
lateinit var btn_set: Button
lateinit var bitmap: Bitmap
lateinit var manager: WallpaperManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_photo_details)
val selectedPhoto = intent.extras?.getSerializable("PHOTO") as PhotoModel
arrow = findViewById(R.id.img_arrow)
arrow.setOnClickListener {
val intent = Intent(this, PhotosActivity::class.java)
startActivity(intent)
}
img = findViewById(R.id.img_detail)
btn_set = findViewById(R.id.btn_wallpaper)
btn_set.setOnClickListener(View.OnClickListener {
fun setOnClickr(l: (View) -> Unit){
setBackgroundd()
}
})
}
fun setBackgroundd() {
val bitmap = BitmapFactory.decodeResource(resources, R.layout.activity_photos)
img.setImageBitmap(bitmap)
manager = WallpaperManager.getInstance(getApplicationContext())
manager.setBitmap(bitmap)
}
}
thanks in advance!

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