I want change profile using image capture on navigation drawer ? its possible? - android

Navigation drawer
I wrote this code but problem is crash application.
This id my nav_header file xml code,i am using circleimageview and imagebutton.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/Profile"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/ic_baseline_person_24"
app:civ_border_color="#color/black"
app:civ_border_width="2dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="#+id/change_Profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/background_center"
app:layout_constraintBottom_toBottomOf="#+id/Profile"
app:layout_constraintEnd_toEndOf="#+id/Profile"
app:srcCompat="#drawable/ic_baseline_add_circle_24" />
<TextView
android:id="#+id/User_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="72dp"
android:paddingTop="8dp"
android:text="Robin Hud"
android:textColor="#color/black"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="110dp"
android:text="sufiyan123#gmail.com"
android:textSize="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="135dp"
android:background="#color/underline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
----------
This is kotlin file code for navigation drawer
package com.example.pgf.view.home
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.view.MenuItem
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import com.example.pgf.R
import com.example.pgf.model.PGListModel
import com.example.pgf.view.authentication.Login
import com.example.pgf.view.home.fragments.*
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import de.hdodenhof.circleimageview.CircleImageView
class MainActivity : AppCompatActivity() {
private lateinit var toggle: ActionBarDrawerToggle
private lateinit var drawerLayout: DrawerLayout
var email:String? = null
var profile: CircleImageView? = null
var reqcode = 345
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Profile change
profile = findViewById(R.id.Profile)
var btnChange = findViewById<ImageButton>(R.id.change_Profile)
btnChange.setOnClickListener {
var captureImage = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(captureImage,reqcode)
}
//get user Email
val user = FirebaseAuth.getInstance().currentUser
email = user?.email
Toast.makeText(applicationContext,email,Toast.LENGTH_SHORT).show()
drawerLayout = findViewById(R.id.drawer)
val navView: NavigationView = findViewById(R.id.navView)
toggle = ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
replaceFragment(HomeFragment(),"Home")
navView.setNavigationItemSelectedListener {
it.isChecked = true
when(it.itemId){
R.id.nav_home -> replaceFragment(HomeFragment(),it.title.toString())
R.id.nav_star -> replaceFragment(StarFragment(),it.title.toString())
R.id.nav_help -> replaceFragment(HelpFragment(),it.title.toString())
R.id.nav_setting -> replaceFragment(SettingFragment(),it.title.toString())
R.id.nav_profile -> replaceFragment(ProfileFragment(),it.title.toString())
R.id.nav_logout -> logout()
R.id.nav_share -> Toast.makeText(applicationContext,"Clicked Share",Toast.LENGTH_SHORT).show()
}
true
}
}
private fun replaceFragment(fragment: Fragment, title: String){
val fragmentStateManagerControl = supportFragmentManager
val fragmentTransaction = fragmentStateManagerControl.beginTransaction()
fragmentTransaction.replace(R.id.framelayout,fragment)
fragmentTransaction.commit()
drawerLayout.closeDrawers()
setTitle(title)
}
fun logout(){
Firebase.auth.signOut()
startActivity(
Intent(this,Login::class.java)
)
this.finish()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (toggle.onOptionsItemSelected(item)){
return true
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(resultCode== Activity.RESULT_OK && requestCode==reqcode && data!=null)
{
profile!!.setImageBitmap(data.extras?.get("data") as Bitmap)
}
else
{
Toast.makeText(applicationContext,"Something Went Wrong!!",Toast.LENGTH_LONG).show()
}
}
}
This is my all code,so I want to change profile picture using camera capture on navigation drawer.
so what I do for this?
Logcat
enter image description here

Related

How use View.OnClickListener with FirestoreRecyclerAdapter

I'm trying to create an application and considering my level it's not easy! I hope you could help me since I didn't succeed with the many links I found on the internet.
I can't add the onClick function of View.OnClickListener, each time the Intent function is not recognized. I tried to implement it in the UserViewHolder and FirestoreRecyclerAdapter class but it doesn't work.
Here is my current code:
---------- kotlin part ---------
package edu.stanford.rkpandey.emojistatus
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import kotlinx.android.synthetic.main.activity_main.*
data class User(
val displayName: String? = "",
val emojis: String? = ""
)
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class MainActivity : AppCompatActivity() {
private val db = Firebase.firestore
private lateinit var auth: FirebaseAuth
// Query the users collection
private val query = db.collection("users")
val options = FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User::class.java)
.setLifecycleOwner(this).build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = Firebase.auth
val adapter = object: FirestoreRecyclerAdapter<User, UserViewHolder>(options) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(this#MainActivity).inflate(R.layout.item_pack, parent, false)
return UserViewHolder(view)
}
override fun onBindViewHolder(
holder: UserViewHolder,
position: Int,
model: User
) {
val tvName: TextView = holder.itemView.findViewById(R.id.title)
val tvEmojis: TextView = holder.itemView.findViewById(R.id.excerpt)
tvName.text = model.displayName
tvEmojis.text = model.emojis
}
}
rvUsers.adapter = adapter
rvUsers.layoutManager = LinearLayoutManager(this)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.miLogout) {
Log.i("MainActivity", "Logout")
auth.signOut()
val logoutIntent = Intent(this, LoginActivity::class.java)
logoutIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(logoutIntent)
}
return super.onOptionsItemSelected(item)
}
}
------- xml part -------
=> activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvUsers"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
=> item_pack
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100sp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="12sp"
android:layout_marginTop="12sp"
android:layout_marginEnd="12sp"
android:focusable="true"
android:clickable="true"
app:cardCornerRadius="10dp"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#color/colorPack">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
style="#style/NoteTitleFont"
android:textColor="#color/colorTitle"
tools:text="Note 1" />
<TextView
android:id="#+id/excerpt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12sp"
android:layout_below="#id/title"
android:maxLines="1"
android:ellipsize="end"
android:textStyle="italic"
android:textColor="#color/colorDescribe"
tools:text="test text va se trouver ici, ça va contenir le début de la description du package." />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
This code gives this result :
I would like that when I click on one of the carviews it can go to the activity_pack_detail.
Do you know how to do Intent to PackDetailActivity?
I get this error no matter what I do =>
You're getting that error because you are calling Intent's class constructor with a wrong argument. The first argument should be a Context and not a View. The keyword this is referring in your code to a View and not to a context, hence the error.
To solve this, you have to pass a Context object like this:
val i = Intent(view.getContext(), PackDetailActivity::class.java)
And your error will go away.

Navigation Broken on Android App Using Firebase Auth

I am writing my first Android App and have implemented Firebase Auth. My app navigation was working correctly before I added in the Firebase pieces. Now I am not able to get from the Main Activity to my starting Frag (Frag1). I would like to have the app open to Frag1 once the Firebase Auth runs through its process, but I can't get that to work. Here are the main parts of my files:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.richeypro.android.fishpro">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:name=".CatchApplication"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".LoginActivity" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"
tools:replace="android:value" />
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.kt
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bumptech.glide.Glide
import com.firebase.ui.auth.AuthUI
import com.google.android.material.navigation.NavigationView
import com.google.firebase.auth.FirebaseAuth
import com.richeypro.android.fishpro.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
lateinit var binding: ActivityMainBinding
val auth = FirebaseAuth.getInstance().currentUser
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
var toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
var fragment = Fragment()
var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
ft.add(R.id.content_frame, fragment)
ft.commit()
var drawer: DrawerLayout = findViewById(R.id.drawer_layout)
var toggle: ActionBarDrawerToggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_open_drawer, R.string.nav_close_drawer)
drawer.addDrawerListener(toggle)
toggle.syncState()
var navigationView: NavigationView = findViewById(R.id.nav_view)
navigationView.setNavigationItemSelectedListener(this)
if(auth!=null && intent!= null){
createUI()
}
else{
startActivity(Intent(this,LoginActivity::class.java))
this.finish()
}
}
override fun onResume() {
super.onResume()
if(auth!=null&& intent!= null){
createUI()
}
else{
startActivity(Intent(this,LoginActivity::class.java))
this.finish()
}
}
fun createUI(){
var txtName: TextView = binding.txtName
var txtEmail: TextView = binding.txtEmail
var txtPhone: TextView = binding.txtPhone
var txtProvider: TextView = binding.txtProvider
var btnLogOut: Button = binding.btnLogOut
var btnCatchList: Button = binding.btnCatchList
var profile_image: ImageView = binding.profileImage
val list = auth?.providerData
var providerData:String = ""
list?.let {
for(provider in list){
providerData = providerData+ " " +provider.providerId
}
}
auth?.let {
txtName.text = auth.displayName
txtEmail.text = auth.email
txtPhone.text = auth.phoneNumber
txtProvider.text = providerData
Glide
.with(this)
.load(auth.photoUrl)
.fitCenter()
.placeholder(R.drawable.login_background)
.into(profile_image)
}
btnLogOut.setOnClickListener{
AuthUI.getInstance().signOut(this)
.addOnSuccessListener {
val intent = Intent(this,LoginActivity::class.java)
startActivity(intent)
// this.finish()
Toast.makeText(this, "Successfully Log Out", Toast.LENGTH_SHORT).show()
}
}
btnCatchList.setOnClickListener{
Toast.makeText(this, "Clicked FAB", Toast.LENGTH_SHORT).show()
val navController: NavController = Navigation.findNavController(this, R.id.nav_host_fragment)
val action = CatchDetailFragmentDirections.actionCatchDetailFragmentToAddCatchFragment(
null.toString(), 1)
navController.navigateUp()
navController.navigate(action)
}
}
// fun generateFBKey(){
// try {
// val info = packageManager.getPackageInfo(
// "com.example.firebaseintro",
// PackageManager.GET_SIGNATURES
// )
// for (signature in info.signatures) {
// val md: MessageDigest = MessageDigest.getInstance("SHA")
// md.update(signature.toByteArray())
// Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
// }
// } catch (e: PackageManager.NameNotFoundException) {
// } catch (e: NoSuchAlgorithmException) {
// }
// }
override fun onBackPressed() {
super.onBackPressed()
finishAffinity()
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var id: Int = item.itemId
var fragment: Fragment
var intent: Intent = Intent()
when (id) {
R.id.nav_catch_list -> fragment = CatchListFragment()
R.id.nav_add_angler -> fragment = AddAnglerFragment()
//R.id.nav_help -> //Do something here
//R.id.nav_feedback -> fragment = SendFeedbackFragment()
else -> fragment = SelectScreenFragment()
}
if (fragment != null) {
var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
ft.replace(R.id.content_frame, fragment)
ft.commit()
} else startActivity(intent)
var drawer: DrawerLayout = findViewById(R.id.drawer_layout)
drawer.closeDrawer(GravityCompat.START)
return true
}
}
LoginActivity.kt
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.ErrorCodes
import com.firebase.ui.auth.IdpResponse
import com.google.firebase.auth.FirebaseAuth
class LoginActivity : AppCompatActivity() {
companion object {
private const val RC_SIGN_IN = 123
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
createSignInIntent()
}
private fun createSignInIntent() {
val providers = arrayListOf<AuthUI.IdpConfig>(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.PhoneBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()
)
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.setIsSmartLockEnabled(false)
.setTheme(R.style.MySuperAppTheme)
.setLogo(R.drawable.fishem_up_logo_final_main_logo_white)
.build(),
RC_SIGN_IN
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == RC_SIGN_IN){
var response = IdpResponse.fromResultIntent(data)
if (resultCode == Activity.RESULT_OK){
val user = FirebaseAuth.getInstance().currentUser
val intent = Intent(this,MainActivity::class.java)
// val image = user?.photoUrl
//
// intent.putExtra("USERNAME", user?.displayName)
// intent.putExtra("USEREMAIL",user?.email)
// intent.putExtra("USERPHONE",user?.phoneNumber)
// intent.putExtra("USERPROVIDER",user?.providerId)
// intent.putExtra("USERIMAGE",user?.photoUrl)
startActivity(intent)
}
else{
if(response == null){
finish()
}
if (response?.getError()?.getErrorCode() == ErrorCodes.NO_NETWORK) {
//Show No Internet Notification
return
}
if(response?.getError()?.getErrorCode() == ErrorCodes.UNKNOWN_ERROR) {
Toast.makeText(this, response?.error?.errorCode.toString(), Toast.LENGTH_LONG)
.show()
Log.d("ERRORCODE", response?.error?.errorCode.toString())
return
}
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/mobile_navigation"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ImageView
android:id="#+id/profile_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/fui_ic_yahoo_24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="16dp"
android:layout_marginTop="64dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="16dp"/>
<TextView
android:id="#+id/txtName"
android:text="Peter Allen"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/profile_image"
style="#style/TextStyle" />
<TextView
android:id="#+id/txtEmail"
style="#style/TextStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Email"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtName" />
<TextView
android:id="#+id/txtPhone"
style="#style/TextStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Phone Number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtEmail" />
<TextView
android:id="#+id/txtProvider"
style="#style/TextStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Provider"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtPhone" />
<Button
android:id="#+id/btnCatchList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.522"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/txtPhone"/>
<Button
android:id="#+id/btnLogOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="#drawable/fui_idp_button_background_email"
android:text="Log Out"
android:textColor="#color/browser_actions_bg_grey"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.522"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnCatchList" />
<include
layout="#layout/toolbar_main"
android:id="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu_nav" />
</androidx.drawerlayout.widget.DrawerLayout>
Regardless of how you handle your fragment/activity state. You should only check the currentUser when necessary, you don't want it to initialize too early.
val auth = FirebaseAuth.getInstance()
if (auth.currentUser == null) {
// LoginActivity
} else {
}
You might want to check out AuthStateListener so you can listen to authentication changes asynchronously.

Android with Kotlin - Sending data back to MainActivity

I have two activities. I want to receive a value from MainActivity, change the value from SecondActivity, and send it back to editText of MainActivity.
However, the editText of MainActivity does not change even if I move back from SecondActivity.
Could you tell me which part I misunderstood?
MainActivity.kt code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.example.homework07.databinding.ActivityMainBinding
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
it.resultCode
val ret_num = it.data?.getIntExtra("result", 0) ?:0
Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
}
binding.button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("num", Integer.parseInt(binding.editText.text.toString()))
result.launch(intent)
}
}
}
activity_main.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Enter number only"
android:inputType="number"
android:minHeight="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="START SECOND ACTIVITY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>
SecondActivity.kt code
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.example.homework07.databinding.ActivitySecondBinding
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySecondBinding.inflate(layoutInflater)
setContentView(binding.root)
val viewModel = ViewModelProvider(this)[MyViewModel::class.java]
viewModel.myLiveData.observe(this) {
binding.textView.text = "$it"
}
var num2 = intent?.getIntExtra("num", 0) ?:0
binding.textView.text = "$num2"
binding.buttonInc.setOnClickListener {
num2 = viewModel.myLiveData.value ?:0
viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) + 1
}
binding.buttonDec.setOnClickListener {
num2 = viewModel.myLiveData.value ?:0
viewModel.myLiveData.value = Integer.parseInt(binding.textView.text.toString()) - 1
}
setResult(0, Intent().putExtra("result", num2))
}
}
activity_second.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonInc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="INCREASE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonDec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="DECREASE"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toBottomOf="#+id/buttonInc" />
</androidx.constraintlayout.widget.ConstraintLayout>
MyViewModel.kt code
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MyViewModel : ViewModel() {
val myLiveData : MutableLiveData<Int> = MutableLiveData()
}
Thank you.
You made a mistake:
setResult(0, Intent().putExtra("result", num2))
replace 0 (it cancel result) to Activity.RESULT_OK.
This line has a mistake (resultCode) parameter:
setResult(0, Intent().putExtra("result", num2))
It's better if you make a constant for resultCode or do something like this in your SecondActivity.kt.
setResult(200, Intent().putExtra("result", num2))
And in MainActivity.kt add this is "registerActivityForResult":
if(it.resultCode == 200){
//Rest of the code here
}
Or you can also follow Below answer
You should set the result before finishing the SecondActivity with:
intent.putExtra("result", num2)
setResult(Activity.RESULT_OK, intent)
finish()
The, after checking the result, retrieve the value in the FirstActivity:
val result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val ret_num = result.data?.getIntExtra("result", 0) ?:0
Snackbar.make(binding.root, "result code: ${it.resultCode}, result number: ${ret_num}", Snackbar.LENGTH_SHORT).show()
}
}

How can I do a setOnClickListener to a fragment that is not in my Activity?

I have 3 fragments here I show them, they have a TextView with the id omitir_swipe, and I need to use it in the activity where I show those 3 fragments, how would I achieve it?:
3 fragments xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorWhite"
>
<ImageView
android:id="#+id/image_swipe"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/books_swipe"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.246"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.329"
/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="116dp"
android:text="Amantium irae amoris integratio est."
android:textAlignment="center"
android:textColor="#color/colorBlack"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/image_swipe"
app:layout_constraintEnd_toEndOf="#+id/image_swipe"
app:layout_constraintHorizontal_bias="0.465"
app:layout_constraintStart_toStartOf="#+id/image_swipe" />
<TextView
android:id="#+id/omitir_swipe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Omitir"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginRight="30dp"
android:textColor="#color/colorBlack"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintBottom_toBottomOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="#+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
The 3 are the same so I only upload 1, they have the same id, to only use 1, I don't know if this is good, could you tell me whether to change it or not
3 Fragments .kt kotlin:
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.yr.iolite.R
class SwipeFragement1 : Fragment()
{
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_splash_screen_1, container, false)
}
}
in the 3 only change this number fragment_splash_screen_change this number
The activity where I show the 3 fragments xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Splash.SplashActivity">
<ImageView
android:id="#+id/bg_snow_splash"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/bg_snow"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<ImageView
android:id="#+id/logo_splash"
android:layout_width="320dp"
android:layout_height="200dp"
android:layout_marginTop="20dp"
android:src="#drawable/logo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0"
/>
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/penguin_splash"
android:layout_width="250dp"
android:layout_height="300dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.391"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/logo_splash"
app:layout_constraintVertical_bias="0"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:lottie_rawRes="#raw/party_penguin"
/>
<com.cuberto.liquid_swipe.LiquidPager
android:id="#+id/swipe_screen"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
The .kt from the previous activity:
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.airbnb.lottie.LottieAnimationView
import com.yr.iolite.MainActivity
import com.yr.iolite.R
import com.yr.iolite.WriteProblem.MinOrMax
import kotlinx.android.synthetic.main.activity_splash.*
import kotlinx.android.synthetic.main.fragment_splash_screen_1.*
class SplashActivity : AppCompatActivity()
{
var bg: ImageView? = null
var logo: ImageView? = null
var penguin: LottieAnimationView? = null
var anim: Animation? = null
private var pagerAdapter : ScreenSliderPagerAdapter? = null
private val SPLASH_TIME_OUT : Int = 5500
private var sharedPref : SharedPreferences ? = null
private var omitir_swipe : TextView? = null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
bg = findViewById(R.id.bg_snow_splash)
logo = findViewById(R.id.logo_splash)
penguin = findViewById(R.id.penguin_splash)
omitir_swipe = findViewById(R.id.omiti_swipe)
val viewPager : ViewPager = findViewById(R.id.swipe_screen)
pagerAdapter = ScreenSliderPagerAdapter(supportFragmentManager)
viewPager.adapter = pagerAdapter
anim = AnimationUtils.loadAnimation(this, R.anim.swipe_screen_anim)
viewPager.startAnimation(anim)
bg_snow_splash.animate().apply {
duration = 1000
startDelay = 4000
translationY(-1600f)
}
logo_splash.animate().apply {
duration = 1000
startDelay = 4000
translationY(-1400f)
}
penguin_splash.animate().apply {
duration = 1000
startDelay = 4000
translationY(1400f)
}
Handler(Looper.getMainLooper()).postDelayed({
var sharedPref= getSharedPreferences("SharedPref", MODE_PRIVATE)
var isFirstTime : Boolean = sharedPref.getBoolean("firstTime", true)
if(isFirstTime)
{
var editor : SharedPreferences.Editor = sharedPref.edit()
editor.putBoolean("firstTime", false)
editor.commit()
}
else
{
val intent = Intent(this, MinOrMax::class.java).apply {
putExtra(EXTRA_MESSAGE, "Intento con exito")
}
startActivity(intent)
finish()
}
}, 5000)
/*findViewById<TextView>(R.id.omitir_swipe).setOnClickListener{
val intent = Intent(this, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "xd")
}
startActivity(intent)
finish()
}*/
}
private class ScreenSliderPagerAdapter (fm : FragmentManager) : FragmentStatePagerAdapter(fm)
{
val NUM_TABS = 3
override fun getItem(position: Int): Fragment
{
return when (position)
{
0 -> SwipeFragement1()
1 -> SwipeFragement2()
else -> SwipeFragement3()
}
}
override fun getCount(): Int = NUM_TABS
}
}
I don't have any errors but when I uncomment the setOnClickListener it doesn't work it gives me a null pointer exception error, and that is because the id of the omit_swipe is not in the activity xml as you can see above instead it is in the fragments.
You can start a new activity and finish the current from the fragment.
class SwipeFragement1 : Fragment(){
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_splash_screen_1, container, false)
view.findViewById<TextView>(R.id.omitir_swipe).setOnClickListener{
val intent = Intent(activity, MainActivity::class.java).apply {
putExtra(EXTRA_MESSAGE, "xd")
}
activity.startActivity(intent)
activity.finish()
}
return view
}
}

RecyclerView doesn't scroll smoothly initially

I'm using Tmdb API and displaying it in a RecyclerView. The RecyclerView is not scrolling smoothly initially but then is working fine. I've tried to change Recyclerview height to 0dp or match_parent but it's still the same. I've tried also android:nestedScrollingEnabled="true". Please help me to fix this problem in the RecyclerView. Thank you in advance.
fragment_add.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.AddFragment">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="#+id/fragment_add_movieSeriesACT"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="24dp"
android:background="#drawable/edit_text_background"
android:hint="#string/movie_or_series"
android:imeOptions="actionDone"
android:inputType="textEmailAddress"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:textColor="#color/colorPrimary"
android:textColorHint="#color/colorEight"
android:textCursorDrawable="#null"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/fragment_add_mainRV"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:scrollbars="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/fragment_add_movieSeriesACT" />
<ProgressBar
android:id="#+id/fragment_add_mainPB"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:indeterminateTint="#color/colorOne"
android:indeterminateTintMode="src_atop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
AddFragment.kt
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.martiandeveloper.muuvi.R
import com.martiandeveloper.muuvi.adapter.RecyclerViewMovieAdapter
import com.martiandeveloper.muuvi.viewmodel.AddViewModel
import kotlinx.android.synthetic.main.fragment_add.*
class AddFragment : Fragment() {
private lateinit var viewModel: AddViewModel
private val adapter = RecyclerViewMovieAdapter(arrayListOf())
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_add, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initUI()
}
private fun initUI() {
viewModel = ViewModelProviders.of(this).get(AddViewModel::class.java)
setRecyclerView()
observe()
viewModel.refreshData()
}
private fun setRecyclerView() {
fragment_add_mainRV.layoutManager = LinearLayoutManager(context)
fragment_add_mainRV.adapter = adapter
}
private fun observe() {
viewModel.movieList.observe(viewLifecycleOwner, Observer { movieList ->
movieList?.let {
adapter.updateMovieList(it)
}
})
viewModel.isError.observe(viewLifecycleOwner, Observer { isError ->
isError?.let {
setProgress(1F, true, View.GONE)
if (it) {
setToast(resources.getString(R.string.something_went_wrong_please_try_again_later))
}
}
})
viewModel.isLoading.observe(viewLifecycleOwner, Observer { isLoading ->
isLoading?.let {
if (it) {
setProgress(.5F, false, View.VISIBLE)
} else {
setProgress(1F, true, View.GONE)
}
}
})
}
private fun setProgress(alpha: Float, enable: Boolean, visible: Int) {
fragment_add_movieSeriesACT.alpha = alpha
fragment_add_mainRV.alpha = alpha
fragment_add_movieSeriesACT.isEnabled = enable
fragment_add_mainPB.visibility = visible
}
private fun setToast(text: String) {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
}
}
AddViewModel.kt
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.martiandeveloper.muuvi.model.MovieResult
import com.martiandeveloper.muuvi.model.Movie
import com.martiandeveloper.muuvi.service.MovieService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableSingleObserver
import io.reactivex.schedulers.Schedulers
class AddViewModel : ViewModel() {
private val movieService = MovieService()
private val disposable = CompositeDisposable()
val movieList = MutableLiveData<List<Movie>>()
val isError = MutableLiveData<Boolean>()
val isLoading = MutableLiveData<Boolean>()
fun refreshData() {
isLoading.value = true
disposable.add(
movieService.getData().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<MovieResult>() {
override fun onSuccess(t: MovieResult) {
movieList.value = t.results
isError.value = false
isLoading.value = false
}
override fun onError(e: Throwable) {
isError.value = true
isLoading.value = false
}
})
)
}
}
RecyclerViewMovieAdapter.kt
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.martiandeveloper.muuvi.R
import com.martiandeveloper.muuvi.model.Movie
import kotlinx.android.synthetic.main.recyclerview_movie_item.view.*
class RecyclerViewMovieAdapter(private val movieList: ArrayList<Movie>) :
RecyclerView.Adapter<RecyclerViewMovieAdapter.RecyclerViewMovieViewHolder>() {
lateinit var context: Context
class RecyclerViewMovieViewHolder(var view: View) : RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerViewMovieViewHolder {
context = parent.context
val view = LayoutInflater.from(context)
.inflate(R.layout.recyclerview_movie_item, parent, false)
return RecyclerViewMovieViewHolder(view)
}
override fun getItemCount(): Int {
return movieList.size
}
override fun onBindViewHolder(holder: RecyclerViewMovieViewHolder, position: Int) {
holder.view.recyclerview_movie_item_movieTitleMTV.text =
movieList[position].movieTitle
holder.view.recyclerview_movie_item_movieVoteAverageMTV.text =
movieList[position].movieVoteAverage.toString()
Glide.with(context)
.load("https://image.tmdb.org/t/p/w300${movieList[position].moviePosterPath}")
.into(holder.view.recyclerview_movie_item_moviePosterIV)
}
fun updateMovieList(newMovieList: List<Movie>) {
movieList.clear()
movieList.addAll(newMovieList)
notifyDataSetChanged()
}
}
recyclerview_movie_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingStart="16dp"
android:paddingTop="8dp"
android:paddingEnd="8dp"
android:paddingBottom="8dp">
<androidx.cardview.widget.CardView
android:layout_width="80dp"
android:layout_height="80dp"
app:cardBackgroundColor="#android:color/transparent"
app:cardCornerRadius="10dp"
app:cardElevation="0dp">
<ImageView
android:id="#+id/recyclerview_movie_item_moviePosterIV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
app:srcCompat="#drawable/default_user_image" />
</androidx.cardview.widget.CardView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:orientation="vertical">
<com.google.android.material.textview.MaterialTextView
android:id="#+id/recyclerview_movie_item_movieTitleMTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:textSize="18sp"
android:textStyle="bold" />
<com.google.android.material.textview.MaterialTextView
android:id="#+id/recyclerview_movie_item_movieVoteAverageMTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimaryDark" />
</LinearLayout>
</LinearLayout>
I believe this is due to size of the image , I had similar issue try to fit the image you obtain using glide into imageview, I have added centerCrop():
Glide.with(context).load("https://image.tmdb.org/t/p/w300${movieList[position].moviePosterPath}") .centerCrop().into(holder.view.recyclerview_movie_item_moviePosterIV);
If this does not work try to change imageview scaletype or centerCrop() to fitCenter()

Categories

Resources