Can not import Adapter - android

Im learning Kotlin and Mvvm for Android. I am using a recycler view, and when i try to set the adapter i cant import the Adapter class, I dont know if the problem is in the code because Android Studio let me import ViewHolder class inside the Adapter class but not Adapter class
FrontPageActivity.kt
package com.jmyp.resport.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.jmyp.resport.model.New
import com.jmyp.resport.R
import com.jmyp.resport.viewmodel.NewViewModel
class FrontPageActivity : AppCompatActivity() {
lateinit var adapter : NewsAdapter // I can not import this but i can
// NewsAdapter.NewViewHolder
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_front_page)
var viewModelNews = ViewModelProviders.of(this).get(NewViewModel::class.java)
viewModelNews.getNews().observe(this, Observer<ArrayList<New>> { news ->
adapter = NewsAdapter(this, news)
})
}
}
NewsAdapter.kt
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.jmyp.resport.model.New
import com.jmyp.resport.R
import com.jmyp.resport.view.FrontPageActivity
import kotlinx.android.synthetic.main.row_front_page.view.*
class NewsAdapter(private val context: FrontPageActivity, private val news : ArrayList<New>) : RecyclerView.Adapter<NewsAdapter.NewViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewViewHolder {
return NewViewHolder(LayoutInflater.from(context).inflate(R.layout.row_front_page,parent,false))
}
override fun getItemCount(): Int {
return news.size
}
override fun onBindViewHolder(holder: NewViewHolder, position: Int) {
holder.title.text = news.get(position).titulo
}
class NewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cover = itemView.iv_cover
val title = itemView.tv_title
}
}

You seem to be missing package in your Adapter class. Add it and try again :)

Related

Firebase remove child recyclerview Kotlin

I need to remove child from Firebase after onClick from RecyclerView Adapter.
I have something like this:
Firebase database is
recyclerview is
My biggest problem is not sure how to get the "key" of the child node from the recyclerview.
I have been stuck on this supposedly simple thing for about 3 days so hopefully any help is appreciated.
package com.cpg12.findingfresh.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.cpg12.findingfresh.R
import com.cpg12.findingfresh.database.ShoppingList
import com.google.firebase.database.FirebaseDatabase
class ShoppingListAdapter : RecyclerView.Adapter<ShoppingListAdapter.ShoppingListViewHolder>() {
private val shoppingList = ArrayList<ShoppingList>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingListViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.shopping_list_item, parent, false)
/** References the node to which market data is stored**/
val databaseReference = FirebaseDatabase.getInstance().getReference("Users")
return ShoppingListViewHolder(itemView)
}
override fun onBindViewHolder(holder: ShoppingListAdapter.ShoppingListViewHolder, position: Int) {
val currentItem = shoppingList[position]
holder.sListItem.text = currentItem.shoppingItem
}
override fun getItemCount(): Int {
return shoppingList.size
}
fun updateShoppinglist(shoppingList: List<ShoppingList>){
this.shoppingList.clear()
this.shoppingList.addAll(shoppingList)
notifyDataSetChanged()
}
class ShoppingListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val sListItem : TextView = itemView.findViewById(R.id.ShoppingItemTV)
override fun onClick(v: View?) {
databaseReference.child(marketName).setValue(markets).child(key).setValue("")
}
}
}

Glide won't load pictures Android Kotlin

I need images from firebase storage to be loaded into my application and displayed in recycle view
For this I decided to use a glide
But when I run the application, nothing is displayed, just a blank screen, and there are no errors
I rewrote the code several times, as for me this is the working one, but it still does not work :)
What could be causing it not to work?
NumberFragment
package com.example.hotel2.number
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.hotel2.UserModule
import com.example.hotel2.databinding.FragmentNumberBinding
import com.example.hotel2.utilits.showToast
import com.google.firebase.firestore.FirebaseFirestore
class NumberFragment : Fragment() {
private var _binding: FragmentNumberBinding? = null
private val binding get() = _binding!!
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: NumberAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentNumberBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onStart() {
super.onStart()
binding.recycleView.apply {
layoutManager = LinearLayoutManager(activity)
}
fetchData()
}
fun fetchData(){
FirebaseFirestore.getInstance().collection("number/")
.get()
.addOnSuccessListener { documents ->
for (document in documents){
val user = documents.toObjects(UserModule::class.java)
binding.recycleView.adapter = NumberAdapter(context!!, user)
}
}
.addOnFailureListener {
showToast("Error")
}
}
}
NumberAdapter
package com.example.hotel2.number
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.hotel2.R
import com.example.hotel2.UserModule
class NumberAdapter(private val context: Context, private val users: List<UserModule>): RecyclerView.Adapter<NumberViewHolder>() {
override fun getItemCount(): Int {
return users.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NumberViewHolder {
return NumberViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.recyclerview_item,parent,false))
}
override fun onBindViewHolder(holder: NumberViewHolder, position: Int) {
val user = users[position]
holder.userName.text = user.UserName
Glide.with(context)
.load(user.UserImage)
.into(holder.userImage)
}
}
class NumberViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val userName: TextView = itemView.findViewById(R.id.textView6)
val userImage: ImageView = itemView.findViewById(R.id.image)
}
UserModule
package com.example.hotel2
data class UserModule(
val UserName: String,
val UserImage: String
){
constructor():this("","")
}

The recycler view in my fragment is causing the animations to look choppy

My app is a dictionary app. I am using a room database to save the recent queries in my app. I am showing all the contents of the room database inside my recycler view. When the user searches for a word, the user is taken to the result fragment and the query is added to the room database behind the scenes. It also plays a slide in from right animation when the new fragment is getting added. On pressing the back or the up button, it should take you back with an animation the top level fragment, the main fragment. But the problem I am facing is that something with the recycler view makes that animation look very choppy.
This is how it should look: https://i.imgur.com/vdOtA2Y.mp4
This is how it looks: https://i.imgur.com/OKpDj7G.mp4
I am pasting the fragment with the recycler view, viewmodel and the recycler view adapter here and I am also pasting a link to the whole app's github repo https://github.com/sbeve72/JADA
package com.sbeve.jada.fragments.main
import android.os.Bundle
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.sbeve.jada.R
import com.sbeve.jada.activities.MainActivity
import com.sbeve.jada.databinding.FragmentMainBinding
import com.sbeve.jada.recyclerview_utils.RecentQueriesAdapter
import com.sbeve.jada.retrofit_utils.RetrofitInit
class MainFragment : Fragment(R.layout.fragment_main), RecentQueriesAdapter.OnItemClickListener {
private val navController: NavController by lazy {
this.findNavController()
}
//the currently running instance of the activity
private val mainActivityContext: MainActivity by lazy {
activity as MainActivity
}
private val stayInPlaceAnimation: Animation? by lazy {
val anim: Animation = AlphaAnimation(1.0F, 1.0F)
anim.duration = 150
anim
}
private val viewModel: MainViewModel by viewModels()
private lateinit var fragmentMainBinding: FragmentMainBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fragmentMainBinding = FragmentMainBinding.bind(view)
fragmentMainBinding.queriesRecyclerView.layoutManager = LinearLayoutManager(mainActivityContext)
fragmentMainBinding.currentLanguage.text = RetrofitInit.supportedLanguages.first[mainActivityContext.savedLanguageIndex]
fragmentMainBinding.changeLanguageGearIcon.setOnClickListener {
createChangeLanguageDialog().show()
}
fragmentMainBinding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
//work
viewModel.addQuery(mainActivityContext.savedLanguageIndex, query)
navController.navigate(MainFragmentDirections.actionMainFragmentToResultFragment(query))
hideSoftKeyboard()
return true
}
override fun onQueryTextChange(newText: String?) = false
})
setAdapter()
}
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int) = stayInPlaceAnimation
private fun createChangeLanguageDialog() =
MaterialAlertDialogBuilder(mainActivityContext)
.setTitle(getString(R.string.choose_a_language))
.setSingleChoiceItems(RetrofitInit.supportedLanguages.first, mainActivityContext.savedLanguageIndex)
{ dialogInterface, i ->
fragmentMainBinding.currentLanguage.text = RetrofitInit.supportedLanguages.first[i]
mainActivityContext.applicationSharedPreferences
.edit()
.putInt(getString(R.string.language_setting_key), i)
.apply()
dialogInterface.dismiss()
}
.create()
//hides the keyboard
private fun hideSoftKeyboard() {
val imm: InputMethodManager = mainActivityContext.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
//Find the currently focused view, so we can grab the correct window token from it.
var view = mainActivityContext.currentFocus
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = View(activity)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
private fun setAdapter() {
viewModel.allQueries.observe(viewLifecycleOwner) {
val adapter = RecentQueriesAdapter(it, this)
fragmentMainBinding.queriesRecyclerView.adapter = adapter
}
}
override fun onItemClick(position: Int) {
val queryText = viewModel.allQueries.value!![position].queryText
navController.navigate(MainFragmentDirections.actionMainFragmentToResultFragment(queryText))
}
}
package com.sbeve.jada.fragments.main
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sbeve.jada.myApplication
import com.sbeve.jada.retrofit_utils.RetrofitInit
import com.sbeve.jada.room_utils.DictionaryDatabase
import com.sbeve.jada.room_utils.DictionaryDatabaseDAO
import com.sbeve.jada.room_utils.RecentQuery
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MainViewModel : ViewModel() {
private var roomDatabase = DictionaryDatabase.getInstance(myApplication.getInstance())
private val databaseDao: DictionaryDatabaseDAO = roomDatabase.getDao()
val allQueries = databaseDao.getAllQueries()
fun addQuery(languageIndex: Int, query: String) {
viewModelScope.launch {
withContext(IO) {
val recentQuery = RecentQuery(0, query, RetrofitInit.supportedLanguages.first[languageIndex], System.currentTimeMillis())
databaseDao.addQuery(recentQuery)
}
}
}
}
package com.sbeve.jada.recyclerview_utils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.recyclerview.widget.RecyclerView
import com.sbeve.jada.databinding.QueryLayoutBinding
import com.sbeve.jada.room_utils.RecentQuery
import java.text.SimpleDateFormat
import java.util.*
class RecentQueriesAdapter(private val dataSet: List<RecentQuery>, private val onItemClickListener: OnItemClickListener) :
RecyclerView.Adapter<RecentQueriesAdapter.ViewHolder>() {
class ViewHolder(myItemView: QueryLayoutBinding, private val onItemClickListener: OnItemClickListener) :
RecyclerView.ViewHolder(myItemView.root), View.OnClickListener {
init {
myItemView.root.setOnClickListener(this)
}
private val queryText = myItemView.queryText
fun setQueryText(queryValue: String) {
queryText.text = HtmlCompat.fromHtml(queryValue, HtmlCompat.FROM_HTML_MODE_LEGACY)
}
private val time = myItemView.time
fun setTimeText(timeValue: Long) {
time.text = SimpleDateFormat.getDateTimeInstance().format(Date(timeValue))
}
override fun onClick(v: View?) {
onItemClickListener.onItemClick(adapterPosition)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = QueryLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding, onItemClickListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentItem = dataSet[position]
holder.setQueryText(currentItem.queryText)
holder.setTimeText(currentItem.timeDate)
}
override fun getItemCount() = dataSet.size
interface OnItemClickListener {
fun onItemClick(position: Int)
}
}

Fragment to Fragment transaction in Adapter Class Android

Hello I'm new in Android Developing and I'm creating a family Application in Android Studio. Whenever I want to go to another fragment in Adapter class the fragment is overlapping old fragment.
I want to go to Another fragment name SubFamilyFragment() from the adapter class.
I tried many ways from internet but I'm not getting success.
Here is my Adapter class code
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.example.mks.Fragments.SubFamilyFragment
import com.example.mks.Models.Family
import com.example.mks.R
class FamilyRecyclerAdapter(val context: Context, val familyList: ArrayList<Family>) : RecyclerView.Adapter<FamilyRecyclerAdapter.viewHolder>() {
class viewHolder(view: View) : RecyclerView.ViewHolder(view) {
val familyName : TextView = view.findViewById(R.id.familyName)
val familyMember : TextView = view.findViewById(R.id.familyMemberCount)
val subFamily : CheckBox = view.findViewById(R.id.chkSubFamily)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): viewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.family_recycler_single_row,parent,false)
return viewHolder(view)
}
override fun getItemCount(): Int {
return familyList.size
}
override fun onBindViewHolder(holder: viewHolder, position: Int) {
val number = familyList[position]
holder.familyName.text = number.familyName
holder.familyMember.text = number.familyMember.toString()
holder.subFamily.text = number.subFamily.toString()
holder.itemView.setOnClickListener {
val activity : AppCompatActivity = it.context as AppCompatActivity
if (number.subFamily){
// val fragment2 = SubFamilyFragment()
// val fragmentTransaction: FragmentTransaction = activity.supportFragmentManager.beginTransaction()
// fragmentTransaction.replace(R.id.nav_host_fragment, fragment2)
// fragmentTransaction.commit()
val myFragment: Fragment = SubFamilyFragment()
(it.getContext() as AppCompatActivity).supportFragmentManager.beginTransaction()
.replace(R.id.nav_host_fragment, myFragment).addToBackStack(null)
.commit()
}
else{
Toast.makeText(context,"No Sub Family",Toast.LENGTH_SHORT).show()
}
}
}
}```
This code is working but the fragment is overlapping.
Please tell me what to do.

How to add an onItemClickListener() in grid View implemented using custom adapter (here i named CategoryAdapter)

MainActivity.kt file - this is the main activity.
How to add an onItemClickListener() in gridview implemented using a custom adapter (here I named CategoryAdapter)? I like to add it to set click listener in the image.
MainActivity.kt
package com.hari.rideit.Controller
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.viewpager.widget.ViewPager
import com.google.android.material.navigation.NavigationView
import com.hari.rideit.Adapters.CategoryAdapter
import com.hari.rideit.Adapters.ViewPageAdapter
import com.hari.rideit.R
import com.hari.rideit.Services.DataService
import kotlinx.android.synthetic.main.content_main.*
import java.util.*
class MainActivity : AppCompatActivity() , NavigationView.OnNavigationItemSelectedListener{
lateinit var adapter:CategoryAdapter
lateinit var toolbar: Toolbar
lateinit var drawerLayout: DrawerLayout
lateinit var navView: NavigationView
lateinit var gridview:GridView
internal lateinit var viewPager:ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
drawerLayout = findViewById(R.id.drawer_layout)
navView = findViewById(R.id.nav_view)
gridview= findViewById(R.id.contentGridView)
val toggle = ActionBarDrawerToggle(
this, drawerLayout, toolbar, 0, 0
)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
navView.setNavigationItemSelectedListener(this)
adapter= CategoryAdapter(this,DataService.categories)
gridview.adapter= adapter
viewPager=findViewById<View>(R.id.viewPager) as ViewPager
val adapter= ViewPageAdapter(this)
viewPager.adapter=adapter
}
Category Adapter:
this is the custom adapter used to get the image and text in gridview
package com.hari.rideit.Adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.hari.rideit.R
import com.hari.rideit.model.Category
class CategoryAdapter(context:Context,categories:List<Category>):BaseAdapter(){
val context= context
val categories= categories
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val categoryView: View
categoryView = LayoutInflater.from(context).inflate(R.layout.category_layout, null)
val categoryImage: ImageView = categoryView.findViewById(R.id.categoryImage)
val categoryname: TextView = categoryView.findViewById(R.id.categoryText)
val category = categories[position]
categoryname.text = category.title
val resourceId =
context.resources.getIdentifier(category.image, "drawable", context.packageName)
categoryImage.setImageResource(resourceId)
return categoryView
}
override fun getItem(position: Int): Any {
return categories[position]
}
override fun getItemId(position: Int): Long {
return 0
}
override fun getCount(): Int {
return categories.count()
}
}
You can add onClickListener to each item of the GridView. Before returning categoryView, set onClickListener on it.
categoryView.setOnClickListener {
//put your code here
}
If you want to access the clicked position in your MainActivity.kt. Create an Interface in CategoryAdapter class. See the code below.
interface OnItemClickListener{
fun onClick(position:Int)
}
Now pass a variable to CategoryAdapter of type OnItemClickListener.
class CategoryAdapter(context:Context,categories:List<Category>, var listener:OnItemClickListener):BaseAdapter(){
// rest of the code
Now before returning. Before return categoryView, set onClickListener on it and pass the position to the listener
categoryView.setOnClickListener {
listener.onClick(position)
}
Now in your MainActivity.kt file implement OnItemClickListener and override OnClick function.
class MainActivity : AppCompatActivity() , NavigationView.OnNavigationItemSelectedListener, CategoryAdapter .OnItemClickListener {
//rest of the code
override fun onClick(position:Int){
// perform the code.
}
}
You need to change your adapter constructor to:
class CategoryAdapter(context:Context,categories:List<Category>, val listener: View.OnClickListener)
And call it from your Activity like this:
adapter= CategoryAdapter(this,DataService.categories, object: View.OnClickListener{
override fun onClick(v: View?) {
Toast.makeText(context, "Click", Toast.LENGTH_LONG).show()
}
})
Inside your adapter, add this code after "categoryImage.setImageResource(resourceId)":
categoryImage.setOnClickListener {
listener.onClick(categoryImage)
}
convertView.setOnClickListener(){}

Categories

Resources