I write an app that will be discovering bluetooth devices and display them in ListView that located in fragment.
This is my code in fragment:
class ScanFragment: Fragment() {
val device_list = ArrayList<DataSource>()
val paired_device_list = ArrayList<DataSource>()
val btAdapter = BluetoothAdapter.getDefaultAdapter()
var rvAdapter: RVAdapter? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View? = inflater.inflate(R.layout.scan_fragment, container, false)
val lvDevices = view?.findViewById<ListView>(R.id.lvDevices)
val device1 = DataSource("Test_Xiaomi", "Test_MAC_Address")
val device2 = DataSource("Test_Huawei", "Test_MAC_Adress")
device_list.add(device1)
device_list.add(device2)
lvDevices?.adapter = RVAdapter(activity, R.layout.rv_items, device_list)
rvAdapter?.notifyDataSetChanged()
Log.d("TAG", "Device = $device_list")
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
activity?.registerReceiver(receiver, filter)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val paired_devices: Set<BluetoothDevice> = btAdapter.bondedDevices
for(device: BluetoothDevice in paired_devices) {
val ok_paired_devices = DataSource(device.name.toString(), device.address.toString())
paired_device_list.add(ok_paired_devices)
}
}
val receiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val action: String? = intent?.action
if(BluetoothDevice.ACTION_FOUND == action) {
val device: BluetoothDevice? = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
val newDevice = DataSource(device?.name.toString(), device?.address.toString())
device_list.add(newDevice)
val lvDevice = view?.findViewById<ListView>(R.id.lvDevices)
lvDevice?.adapter = RVAdapter(activity, R.layout.rv_items, device_list)
//Log.d("TAG", "Device = $device_list")
}
}
}
override fun onDestroyView() {
super.onDestroyView()
activity?.unregisterReceiver(receiver)
}
And this is of my adapter:
class RVAdapter(context: Context, var res: Int, var list: ArrayList<DataSource>): ArrayAdapter<DataSource>(context, res, list) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
//super.getView(position, convertView, parent)
val inflater = LayoutInflater.from(context)
val row = inflater.inflate(res, parent, false)
val tvDeviceName = convertView?.findViewById<TextView>(R.id.tvDeviceName)
val tvDeviceMAC = convertView?.findViewById<TextView>(R.id.tvDeviceMAC)
var item = list[position]
tvDeviceName?.text = item.device_name
tvDeviceMAC?.text = item.device_mac
return row
}
I just can't to pass context from fragment to my adapter. I tried to pass either "activity" or "context" or " MainActivity()", but ListView doesn't display nothing at all. If i passing exactly "MainActivity()" to adapter, then i getting error message "System services not available to Activities before onCreate()" in line
lvDevices?.adapter = RVAdapter(activity, R.layout.rv_items, device_list).
and in line
class RVAdapter(context: Context, var res: Int, var list: ArrayList<DataSource>): ArrayAdapter<DataSource>(context, res, list)
If i try to pass "activity" then it just highlighted in red color.
When i use recyclerView instead, then everything is fine. But i do not want to use RecyclerView cause i many times tried implementing onItemClick in different ways and nothing working for me because i can't to pass context in onReceive method.
The problem is that activity property returns nullable type, but adapter requires non-nullable type. If you need context in fragment, call requireContext()
RVAdapter(requireContext(), R.layout.rv_items, device_list)
Related
Get numbers
class Base : Fragment() {
val time = ArrayList<Double>()
val amplitude = ArrayList<Double>()
var flag = 0
private fun readNumbersFromCSV(fileName: String) {
val textView: TextView = requireView().findViewById(R.id.result)
val timeTextView: TextView = requireView().findViewById(R.id.Time)
val amplitudeTextView: TextView = requireView().findViewById(R.id.Amplitude)
timeTextView.movementMethod = ScrollingMovementMethod()
amplitudeTextView.movementMethod = ScrollingMovementMethod()
try {
timeTextView.append("Time, s\n")
amplitudeTextView.append("Amplitude\n")
val file = File(fileName)
if(!file.exists()){
throw FileNotFoundException("File not found")
}
val reader = BufferedReader(FileReader(file))
var line = reader.readLine()
while (line != null) {
val parts = line.split(",")
if (parts.size == 2) {
time.add(parts[1].toDouble())
amplitude.add(parts[0].toDouble())
timeTextView.append(parts[1] + "\n")
amplitudeTextView.append(parts[0] + "\n")
}
line = reader.readLine()
}
flag = 1
reader.close()
} catch (e: FileNotFoundException) {
textView.text = "Error: File Not Found"
} catch (e: Exception) {
textView.text = "Error: ${e.message}"
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_base, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
val file = File(path, "data.csv").toString()
readNumbersFromCSV(file)
/*now im ready to pass data to another class*/
}
}
Do some calculations on those numbers
class Calculations : Fragment() {
private fun meanAmplitude(amplitudes: List<Double>): Double {
if(amplitudes.isEmpty()) return 3.5
return amplitudes.sum() / amplitudes.size
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_calculations, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val copiedList = Base().amplitude.toList() /* data from file passed to new array*/
val textViewAmp: TextView = view.findViewById(R.id.Camplitude)
val valueOfMean = meanAmplitude(copiedList).toString() /*calculate mean value*/
textViewAmp.text = valueOfMean /*display it*/
}
}
MyAdapter
internal class MyAdapter (var context: Context, fm: FragmentManager, var totalTabs: Int): FragmentPagerAdapter(fm) {
override fun getCount(): Int {
return totalTabs
}
override fun getItem(position: Int): Fragment {
return when(position){
0 -> {
Base()
}
1 -> {
Calculations()
}
2 -> {
About()
}
else -> getItem(position)
}
}
}
HomeActivity
class HomeActivity : AppCompatActivity() {
private lateinit var tabLayout: TabLayout
private lateinit var viewPager: ViewPager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
supportActionBar?.hide()
setContentView(R.layout.activity_home)
tabLayout = findViewById(R.id.tabLayout)
viewPager = findViewById(R.id.viewPager)
tabLayout.addTab(tabLayout.newTab().setText("Data"))
tabLayout.addTab(tabLayout.newTab().setText("Calculations"))
tabLayout.addTab(tabLayout.newTab().setText("About"))
tabLayout.tabGravity = TabLayout.GRAVITY_FILL
val adapter = MyAdapter(this, supportFragmentManager, tabLayout.tabCount)
viewPager.adapter = adapter
viewPager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabLayout))
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab?) {
viewPager.currentItem = tab!!.position
}
override fun onTabUnselected(tab: TabLayout.Tab?) {
}
override fun onTabReselected(tab: TabLayout.Tab?) {
}
})
}
}
Im new in Kotlin. I have a problem with initializing an array that is being filled with data from a .csv file in the Base class, and then its contents should be passed to the Calculations class. The problem is that the array instance is being passed before it is being filled with numbers. Two fragments are generated probably in the same time.
Loading from file and initializing an array in the first class works, elements are displayed on the screen without any problems. After passing the array to the second class, it is empty.
I tried to do a flag, but it doesnt work like I though. Im not using activities, just Fragments and ViewPager. I tried Bundles but its hard to apply new things in my messy project.
Here:
val copiedList = Base().amplitude.toList()
You are instantiating a new instance of Base by calling its constructor. This new instance shares nothing with any previous instance. It's a brand new Base that hasn't done anything yet so its lists are still empty.
To pass data between fragments, you should create an arguments Bundle and pass that to the new fragment. The reason you need to do it this way is that Android automatically destroys and recreates Fragment instances under various conditions, and only the arguments data is preserved for the new instance.
The conventional way to do this is to define a Fragment factory function named newInstance() in its companion object. Then the Fragment can unpack the new data in onViewCreated(). You have to convert to and from DoubleArrays because Bundle doesn't support Lists.
class Calculations private constructor(): Fragment(R.layout.fragment_calculations) {
companion object {
private const val TIME_LIST_KEY = "timeList"
private const val AMP_LIST_KEY = "ampList"
fun newInstance(timeList: List<Double>, ampList: List<Double>) =
Calculations().apply {
arguments = bundleOf(
TIME_LIST_KEY to timeList.toDoubleArray(),
AMP_LIST_KEY to ampList.toDoubleArray()
)
}
}
private fun meanAmplitude(amplitudes: List<Double>): Double {
if(amplitudes.isEmpty()) return 3.5
return amplitudes.sum() / amplitudes.size
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val timeList = requireArguments().getDoubleArray(TIME_LIST_KEY).toList()
val ampList = requireArguments().getDoubleArray(AMP_LIST_KEY).toList()
val textViewAmp: TextView = view.findViewById(R.id.Camplitude)
val valueOfMean = meanAmplitude(ampList).toString() /*calculate mean value*/
textViewAmp.text = valueOfMean /*display it*/
}
}
Then in your first fragment, you use Calculations.newInstance() to create your second fragment before passing it to the transaction manager.
By the way, there's a major bug in your Base class. Since Fragment instances can be reused by the OS, the same fragment can go through multiple lifecycles. Since you are adding your data to the same ArrayLists every time onViewCreated() is called, they will get longer and longer as the user rotates the screen or navigates back and forth in the app. You should either remove those properties and use local variables instead, or you should clear those ArrayLists in onDestroyView().
First of all, I am Spanish so my english is not good.
I have an app with Kotlin and room, and it has a Recyclerview.
I have 3 tables: coaster, user and favorite.
The user can add coasters to favorite, and this is done succesfully.
The problem that I have is that when the user clicks on the button to add or delete from favorites, the recyclerview resets, it displays again. So it scrolls to the top of the Screen, and also some odd spaces appears after the element.
I also have a function to search, and it happens the same: spaces appears after each element when I am searching.
I have tried everything: notifyItemChanged,
notifyDataSetChanged... it doesnt work! I also tried removing the observer once from the recyclerview...
My main activity:
class CoasterFragment : Fragment() {
lateinit var coasterListener: CoasterListener
lateinit var usuarioCoaster: List\<UsuarioCoaster\>
private lateinit var searchView: SearchView
private lateinit var cAdapter: CoasterRecyclerViewAdapter
private var \_binding: FragmentCoasterBinding? = null
private val binding get() = \_binding!!
private val viewModel: CoastersViewModel by viewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentCoasterBinding.inflate(inflater, container, false)
val root: View = binding.root
/* val livedata = viewModel.coasters()
livedata.observe(viewLifecycleOwner,object: Observer <List<CoasterFavorito>> {
override fun onChanged(it: List<CoasterFavorito>) {
createRecyclerView(it)
livedata.removeObserver(this)
}
})*/
viewModel.coasters().observe(viewLifecycleOwner){createRecyclerView(it)}
coasterListener = CoasterListenerImpl(requireContext(), viewModel)
searchView = binding.search
searchView.clearFocus()
searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
if(query != null){
searchDatabase(query)
}
return true
}
override fun onQueryTextChange(query: String?): Boolean {
if(query != null){
searchDatabase(query)
}
return true
}
})
return root
}
fun createRecyclerView(coasters: List<CoasterFavorito>) {
cAdapter =
CoasterRecyclerViewAdapter(
coasters as MutableList<CoasterFavorito>,
coasterListener,
requireContext()
)
val recyclerView = binding.recyclerCoaster
recyclerView.apply {
layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
adapter = cAdapter
addItemDecoration(DividerItemDecoration(context, RecyclerView.VERTICAL))
cAdapter.notifyDataSetChanged()
}
}
fun searchDatabase(query: String) {
val searchQuery = "%$query%"
viewModel.searchDatabase(searchQuery).observe(viewLifecycleOwner) { createRecyclerView(it)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
my adapter:
class CoasterRecyclerViewAdapter(val coasters: List<CoasterFavorito>, val listener: CoasterListener,
val context: Context, ) : RecyclerView.Adapter<CoasterRecyclerViewAdapter.ViewHolder>(){
class ViewHolder private constructor(val binding: CoasterItemBinding, private val listener: CoasterListener,
private val context: Context): RecyclerView.ViewHolder(binding.root){
fun relleno(data: CoasterFavorito){
binding.nombre.text = data.coaster.nombre
binding.parque.text = data.coaster.parque
binding.ciudad.text = data.coaster.ciudad
binding.provincia.text = data.coaster.provincia
binding.comunidad.text = data.coaster.comunidadAutonoma
Glide
.with(context)
.load(data.coaster.imagen)
.centerCrop()
.into(binding.imagen)
binding.check.isChecked = data.favorito
binding.check.setOnClickListener{
if (data.favorito) {
listener.delFavorito(data.coaster.id)
binding.check.isChecked = false
} else {
listener.addFavorito(data.coaster.id)
binding.check.isChecked = true
}
}
}
companion object{
fun crearViewHolder(parent: ViewGroup, listener: CoasterListener, adapter: CoasterRecyclerViewAdapter, context: Context):ViewHolder{
val layoutInflater = LayoutInflater.from(parent.context)
val binding = CoasterItemBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding, listener, context )
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder.crearViewHolder(parent, listener, this, context)
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.relleno(coasters[position])
override fun getItemCount() = coasters.size
}
interface CoasterListener {
fun addFavorito(id: Long)
fun delFavorito(id: Long)
}
I have tried everything: notifyItemChanged,
notifyDataSetChanged... it doesnt work! I also tried removing the observer once from the recyclerview...
Your createRecyclerView function should be invoked only once in a whole lifecycle of the Fragment. You should not create any new RecyclerView.Adapter, or set a LayoutManager to the RecyclerView every time your data set changes.
Therefore the Observer used in viewModel.coasters.observe() should only submit a new List to the existing Adapter and call .notifyDataSetChanged(), or other notifying functions.
i have problem when try to display recyvlerview using kotlin , warn no adapter attach skipping layout and nothing happen in my app, ive tried many way but nothing solve it
how could i do ? please review my code, i will very thankfull to anyone can help
i have problem when try to display recyvlerview using kotlin , warn no adapter attach skipping layout and nothing happen in my app, ive tried many way but nothing solve it
how could i do ? please review my code, i will very thankfull to anyone can help
class ArticleFragment : Fragment() {
private lateinit var mPeopleRVAdapter: FirebaseRecyclerAdapter<News, NewsViewHolder>
//function oncreate
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_news, container, false)
}
//viewholder
class NewsViewHolder internal constructor(var mView: View) : RecyclerView.ViewHolder(mView) {
fun setTitle(title: String?) {
val post_title = mView.findViewById<View>(R.id.post_title) as TextView
post_title.text = title
}
fun setDesc(desc: String?) {
val post_desc = mView.findViewById<View>(R.id.post_desc) as TextView
post_desc.text = desc
}
fun setImage(ctx: Context?, image: String?) {
val post_image = mView.findViewById<View>(R.id.post_image) as ImageView
Picasso.with(ctx).load(image).into(post_image)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//"News" here will reflect what you have called your database in Firebase.
//"News" here will reflect what you have called your database in Firebase.
val mDatabase = FirebaseDatabase.getInstance().reference.child("news")
mDatabase.keepSynced(true)
val mPeopleRV = view.findViewById<View>(R.id.myRecycleView) as RecyclerView
val personsRef =
FirebaseDatabase.getInstance().reference.child("news")
val personsQuery = personsRef.orderByKey()
val personsOptions: FirebaseRecyclerOptions<News> = FirebaseRecyclerOptions.Builder<News>().setQuery(
personsQuery, News::class.java).build()
mPeopleRVAdapter = object : FirebaseRecyclerAdapter<News, NewsViewHolder>(personsOptions) {
override fun onBindViewHolder(holder: NewsViewHolder, position: Int, model: News) {
holder.setTitle(model.title)
holder.setDesc(model.desc)
holder.setImage(activity ,model.image)
holder.mView.setOnClickListener {
val url: String? = model.url
val intent = Intent(activity, NewsWebView::class.java)
intent.putExtra("id", url)
startActivity(intent)
}
mPeopleRV.hasFixedSize()
mPeopleRV.layoutManager = LinearLayoutManager(context)
mPeopleRV.apply {
mPeopleRV.adapter = mPeopleRVAdapter
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_row, parent, false)
return NewsViewHolder(view)
}
}
}
override fun onStart() {
super.onStart()
mPeopleRVAdapter.startListening()
}
override fun onStop() {
super.onStop()
this.mPeopleRVAdapter.stopListening()
}
}
Move this code out of adapter:
mPeopleRV.hasFixedSize()
mPeopleRV.layoutManager = LinearLayoutManager(context)
mPeopleRV.apply {
mPeopleRV.adapter = mPeopleRVAdapter
}
This is my first time building an application. I want to display my data in firebase realtimedatabase in recyclerview. but 'E/RecyclerView: No adapter attached; skipping layout' is on the Run chart.
I'll show you my codes in order.
at first, this is my Data class in kotlin
data class BalInputDTO(
var Id : String? = null,
var Itype: String? = null,
var Icategory: String? = null,
var ldate : String? = null,
var balance: String? = null,
var commnet: String? = null)
and then this is my adapter.kt
class BalAdapter(val context: Context, val BalList: ArrayList<BalInputDTO>) :
RecyclerView.Adapter<BalAdapter.Holder>() {
override fun onBindViewHolder(holder: Holder, position: Int) {
holder?.bind(BalList[position], context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(context).inflate(R.layout.household_detail, parent, false)
return Holder(view)
}
override fun getItemCount(): Int {
return BalList.size
}
inner class Holder(view: View?) : RecyclerView.ViewHolder(view!!) {
val recordCategory = view?.findViewById<TextView>(R.id.record_category)
val recordNote = view?.findViewById<TextView>(R.id.record_note)
val recordAmount = view?.findViewById<TextView>(R.id.record_amount)
val recordDate = view?.findViewById<TextView>(R.id.record_date)
val recordDeleteImageView = view?.findViewById<ImageButton>(R.id.record_delete_image_button)
fun bind(bal: BalInputDTO, context: Context) {
recordCategory?.text = bal.Icategory
recordNote?.text = bal.commnet
recordAmount?.text = bal.balance
recordDate?.text = bal.ldate
// recordDeleteImageView.imageb
}
}
}
and the last code. this is my Fragment.kt (only onCreatView part)
var fragmentView : View? = null
var firedatabase : FirebaseDatabase? = null
var BalList : ArrayList<BalInputDTO> ? = null
var ref : DatabaseReference? = null
var mRecyclerView : RecyclerView? =null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
fragmentView= LayoutInflater.from(activity).inflate(R.layout.fragment_household, container, false)
firedatabase = FirebaseDatabase.getInstance()
mRecyclerView = fragmentView?.findViewById(R.id.household_recyclerview)
mRecyclerView?.setHasFixedSize(true)
mRecyclerView?.layoutManager = LinearLayoutManager(context)
BalList = arrayListOf<BalInputDTO>()
ref = FirebaseDatabase.getInstance().getReference("BalInput")
ref?.addValueEventListener(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onDataChange(p0: DataSnapshot) {
if(p0!!.exists()){
for (h in p0.children){
val bal = h.getValue(BalInputDTO::class.java)
BalList?.add(bal!!)
}
val adapter = BalAdapter(context!!,BalList = ArrayList<BalInputDTO>())
mRecyclerView?.setAdapter(adapter)
}
}
})
return fragmentView
}
and this is my database enter image description here
Please let me know if I missed something or did something wrong.
It seems like you passing the wrong list to your adapter. Try this
val adapter = BalAdapter(context!!,BalList)
instead of
val adapter = BalAdapter(context!!,BalList = ArrayList<BalInputDTO>())
I'd say the real issue here is this line
val adapter = BalAdapter(context!!,BalList = ArrayList<BalInputDTO>())
try changing it to:
val adapter = BalAdapter(context!!,BalList)
since this is where you are adding all the elements from FB.
This question already has answers here:
Android Fragment no view found for ID?
(40 answers)
Closed 4 years ago.
Its showing that no view found. But what does that I am not able to understand.
I think problem is in OnCreateView() function as there is only the parameter where view is passed.
Should I use try and catch method?
code for MainScreenFragment
class MainScreenFragment : Fragment() {
var getsongsList: ArrayList<Songs>?=null
var nowPlayingButtonBar: RelativeLayout?=null
var playPauseButton: ImageButton?=null
var songTitle: TextView?=null
var visibleLayout: RelativeLayout?=null
var noSongs: RelativeLayout?=null
var recyclerView: RecyclerView?=null
var myActivate: Activity?=null
var _mainScreenAdapter: MainscreenAdapter?=null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view= inflater.inflate(R.layout.main_screen_fragment,container,
false)
visibleLayout=view?.findViewById<RelativeLayout>(R.id.visibleLayout)
noSongs= view?.findViewById<RelativeLayout>(R.id.noSongs)
nowPlayingButtonBar= view?.findViewById<RelativeLayout>
(R.id.hiddenMainScreen)
songTitle = view?.findViewById<TextView>(R.id.songName)
playPauseButton= view?.findViewById<ImageButton>
(R.id.playPauseButton)
recyclerView=view?.findViewById<RecyclerView>(R.id.contentMain)
return view }
#RequiresApi(Build.VERSION_CODES.O)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
getsongsList = getSongsFromPhone()
_mainScreenAdapter= MainscreenAdapter(getsongsList as
ArrayList<Songs>, myActivate as Context)
val mLayoutManager = LinearLayoutManager(myActivate)
recyclerView?.layoutManager = mLayoutManager
recyclerView?.itemAnimator = DefaultItemAnimator()
recyclerView?.adapter = _mainScreenAdapter
}
override fun onAttach(context: Context?) {
super.onAttach(context)
myActivate = context as Activity
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
myActivate= activity
}
#RequiresApi(Build.VERSION_CODES.O)
fun getSongsFromPhone(): ArrayList<Songs> {
val arrayList =ArrayList<Songs>()
val contentResolver = myActivate?.contentResolver
val songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val songCursor = contentResolver?.query(songUri,null,null,null)
if(songCursor!= null && songCursor.moveToFirst()){
val songId =
songCursor.getColumnIndex(MediaStore.Audio.Media._ID)
val songTitle =
songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE)
val songArtist =
songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
val songData =
songCursor.getColumnIndex(MediaStore.Audio.Media.DATA)
val songAdded =
songCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)
while (songCursor.moveToNext()){
val currentID =songCursor.getLong(songId)
val currentTitle =songCursor.getString(songTitle)
val currentArtist =songCursor.getString(songArtist)
val currentData =songCursor.getString(songData)
val currentAdded =songCursor.getLong(songAdded)
arrayList.add(Songs(currentID,
currentTitle,currentArtist,currentData,currentAdded))
songCursor.close()
}
}
return arrayList
}
}
No view found mostly comes when you are taking the wrong id of the FrameLayout which is on another XML file and replacing the fragment in that FrameLayout. Just check once that you are replacing your fragment in the correct FrameLayout.