I could not connect my recyclerview in fragment with adapter - android

my fragment class
class RecyclerFragment : Fragment() {
var recycler:RecyclerView? =null
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
recycler = view?.findViewById(R.id.recycler)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_recycler, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
recycler?.layoutManager = LinearLayoutManager(this.context,RecyclerView.VERTICAL,false)
recycler?.adapter = Custom_Adapter() // error-Unresolved reference: Custom_Adapter
}
}
//here is my adater
class Custom_Adapter() : RecyclerView.Adapter<Custom_Adapter.ViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): Custom_Adapter.ViewHolder {
var myViewInflater = LayoutInflater.from(viewGroup.context).inflate(R.layout.custom_layout,viewGroup,false)
return ViewHolder(myViewInflater)
}
override fun onBindViewHolder(holder: Custom_Adapter.ViewHolder, position: Int) {
}
override fun getItemCount(): Int {
return 9
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
}

Update your recycler fragment like this.
class RecyclerFragment : Fragment(R.layout.fragment_recycler) {
var recycler:RecyclerView? =null
private var param1: String? = null
private var param2: String? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler = view.findViewById(R.id.recycler)
recycler?.layoutManager = LinearLayoutManager(this.context,RecyclerView.VERTICAL,false)
recycler?.adapter = Custom_Adapter()
}
}
And you have to move classes Recucler_Item and Custom_Adapter into correct java package.

From your repo link in one of the comments, Custom_Adapter is under your src/test directory. It needs to be under src/main where RecyclerFragment can see it - that's why you're getting unresolved reference errors. Stick it in there with everything else
main and test are different source sets, it's basically a way of keeping stuff separate. All your production code goes in main, and it can't see anything in test by default. When you run tests, those use everything in test (and maybe androidTest) and get all the stuff in main included, since the tests need access to the production code to, y'know, test it!

Related

Is it okay to delete a CompanionObject on a fragment?

So I'm working with Android Studio, and I found a video on youtube on how to set tab layout. I'm trying to create a fragment with new>Fragment>Fragment(Blank) and I'm following youtube instructions to remove everything else except onCreate and onCreateView in Fragment class. But when i try to put everything together, i get this error:
Classifier 'PemasukanFragment' does not have a companion object, and thus must be initialized here
I use AddActivity class to hold my fragment, the code look like this:
class AddActicity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_acticity)
setUpTabs()
}
private fun setUpTabs(){
val adapter= Adapter_AddActivity(supportFragmentManager)
adapter.addFragment(PemasukanFragment,"Pemasukan")
}
}
I have 2 fragment pages. The code look like this:
class PemasukanFragment : Fragment() {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pemasukan, container, false)
}
}
The other fragment page have a similar code to this. I also have adapter that look like this:
class Adapter_AddActivity(supportFragmentManager: FragmentManager) :
FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
private val mFragmentList = ArrayList<Fragment>()
private val mFragmentListTitle = ArrayList<String>()
override fun getCount(): Int {
return mFragmentList.size
}
override fun getItem(position: Int): Fragment {
return mFragmentList[position]
}
override fun getPageTitle(position: Int): CharSequence? {
return mFragmentListTitle[position]
}
fun addFragment(fragment: Fragment, title: String){
mFragmentList.add(fragment)
mFragmentListTitle.add(title)
}
}
I don't know if companion objects can be removed. But if it can, how to solve this error? Any help is appreciated

How to update fragmentStateAdapter after a bottomSheet dismiss

I have this fragmentStateAdapter which holds some of my Cards in order to swipe among them:
public class ScreenSlidePagerAdapter(activity: AppCompatActivity, var items: ArrayList<Helpers.Card>, private val saveToDb: Boolean) : FragmentStateAdapter(activity) {
override fun getItemCount(): Int = items.count()
var fragment:CardItemFragment?=null
override fun createFragment(position: Int): Fragment{
fragment =CardItemFragment(position, saveToDb ,this) //.newInstance( items[position ].getSaveString())
return fragment as CardItemFragment
}}
and the CardItemFragement is:
class CardItemFragment(val position:Int, val saveToDb: Boolean, val isCardMine: Boolean,val adapter: ScreenSlidePagerAdapter) : Fragment() {
lateinit var cardView1: ConstraintLayout
lateinit var crdNameTB1: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.card_item, container, false)
cardView1 = v.findViewById(R.id.cardView1)
crdNameTB1= v.findViewById(R.id.crdNameTB1)
return v
}
Then I can update the Card inside the fragementStateAdapter like this:
fun updateCard(): Bitmap? {
crdNameTB1.text = .....
}
That's works fine and I can swipe among my Cards, but when I change the value of "name" attribute of my Card via a bottom sheet and when I dismiss the BottomSheet I use this code to refresh the fragmentSatateAdapter:
MainActivity.galleryPagerAdapter?.fragment ?.updateCard()
I set MyActivity as companion object to reach it anywher.
When this code executed, I got the fragment not null object but the updateCard gives me null objects
1what is the problem and how can I overcome this and update the shown Card?
I have found the answer by overriding the following methods in order to make the Adapter run
override fun getItemId(position: Int): Long {return items[position].id}
override fun containsItem(itemId: Long): Boolean = items.any { it.id == itemId }
the answer post is here

recyclerview not visible at run time

I implemented a simple recyclerview using databinding using kotlin language.
In xml, recyclerview seems to be the default,
but when I run it, it doesn't show up as default.
Other buttons and views included in the fragment appear normally when executed, but only the recyclerview is not visible. Which part is wrong?
class WorkFragment : Fragment() {
private var _binding: FragmentWorkBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentWorkBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val data = mutableListOf<WorkList>()
val adapter = WorkAdapter()
adapter.data = data
binding.recycler1.adapter = adapter
binding.recycler1.layoutManager = LinearLayoutManager(requireContext())
}
}
class WorkAdapter : RecyclerView.Adapter<WorkAdapter.ViewHolder>() {
var data = mutableListOf<WorkList>()
class ViewHolder(val binding: RecyclerviewWorkItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(workList: WorkList) {
binding.tvStarttime.text = workList.Starttime
binding.tvAdmin.text = workList.Admin
binding.tvPart.text = workList.Part
binding.tvStoptime.text = workList.Stoptime
binding.tvWorkers.text = workList.Workers.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WorkAdapter.ViewHolder {
val binding = RecyclerviewWorkItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: WorkAdapter.ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount(): Int {
return data.size
}
// fun replaceList(newList: MutableList<WorkList>) {
// data = newList.toMutableList()
// notifyDataSetChanged()
// }
}
Is there something wrong with my code?
For reference, I just used a fragment, not an activity.
its typically for the RecyclerView to behave like its hidden but actually its not. the reason is you are passing an empty list so the recycler will not be extended or show because there is no items in the list.

How do I filter cards in a RecyclerView through a SearchView (Kotlin)?

I am currently working on a simple journal app where the user can make new entries, which get stored into a room database and displayed through a RecyclerView using cards. I am currently trying to implement a way to filter card entries based on the text within them using a SearchView. However, everything that I've found online seems to be entirely in Java, just filtering a list, etc, so I'm not sure how I would go about doing this. Any help would be massively appreciated!
Here is my code (without imports):
Fragment that displays entries through RecyclerView:
class HomeFragment : BaseFragment() {
private lateinit var homeViewModel: HomeViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_home, container, false)
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler_view.setHasFixedSize(true)
recycler_view.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
launch {
context?.let {
var journal = JournalDatabase.getDatabase(it).JournalDao().allJournal()
recycler_view.adapter = JournalAdapter(journal)
}
}
newEntryButton.setOnClickListener {
Navigation.findNavController(view).navigate(R.id.action_nav_home_to_nav_new_entry)
}
}
}
My adapter:
class JournalAdapter(val arrList: List<Journal>) :
RecyclerView.Adapter<JournalAdapter.JournalViewHolder>() {
class JournalViewHolder(view: View) : RecyclerView.ViewHolder(view) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): JournalViewHolder {
return JournalViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.recyclerview_entry, parent, false))
}
override fun onBindViewHolder(holder: JournalViewHolder, position: Int) {
holder.itemView.rvTitle.text = arrList[position].title
holder.itemView.rvText.text = arrList[position].journalText
holder.itemView.rvDateTime.text = arrList[position].dateTime
}
override fun getItemCount(): Int {
return arrList.size
}
}

LiveData + ViewModel States , values clash and only last value is observed

Im using ViewModel with states and LiveData with one observer .
I have an activity and a fragment . everything works fine until Im rotating the screen
and then, the states I want to observe , clash.
What can I do in order to prevent it and make it work as expected?
I know I can add more observers but I don't want to solve it in this way , it may lead to problems with the other code.
MainActivity code :
private var appsDetailsHmap = HashMap< String , AppsDetails>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progressBar = CircleProgressBarDialog(this)
viewModel.getState().observe(this, Observer {state->
when(state){
is SettingsViewModelStates.GetAppsDetails->initUI(state.list)
is SettingsViewModelStates.ShowDialog->progressBar.showOrHide(state.visibility)
is SettingsViewModelStates.GetCachedData->setCachedSettings(state.appDetailsHmap,state.selectedApp,state.speechResultAppName)
}
})
if (savedInstanceState==null){
viewModel.initSettingsActivityUI(appsDetailsHmap)
}
else{
viewModel.initCachedSettingsActivityUI()
}
Fragment code
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view= inflater.inflate(R.layout.fragment_added_apps, container, false)
viewModel.getCachedApplist()
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getState().observe(viewLifecycleOwner, Observer {state->
when(state){
is SettingsViewModelStates.PassAppsToFragment->{
initRecyclerView(state.list)
}
}
})
}
ViewModel
private var state=MutableLiveData<SettingsViewModelStates>()
private var appsDetailsHmap=HashMap<String,AppsDetails>()
private var addedApps= HashMap<String,Drawable?>()
fun getState()=state as LiveData<SettingsViewModelStates>
fun getCachedApplist(){
if (addedApps.isEmpty()){
getAppsList()
println("empty")
}
else
state.setValue(SettingsViewModelStates.PassAppsToFragment(addedApps))
}
fun initCachedSettingsActivityUI(){
state.setValue(SettingsViewModelStates.GetCachedData(appsDetailsHmap,selectedApp,speechResultAppName))
}
fun initSettingsActivityUI(list:HashMap<String, AppsDetails>) {
appsDetailsHmap=list
state.setValue( SettingsViewModelStates.GetAppsDetails(list))
}
states:
sealed class SettingsViewModelStates {
data class GetAppsDetails(val list:HashMap<String, AppsDetails>):SettingsViewModelStates()
data class ShowDialog(val visibility: Int) : SettingsViewModelStates()
data class PassAppsToFragment(val list:HashMap<String,Drawable?>) : SettingsViewModelStates()
data class GetCachedData(val appDetailsHmap:HashMap<String,AppsDetails>,
val selectedApp: AppsDetails,
val speechResultAppName:String ) : SettingsViewModelStates()
}

Categories

Resources