notifyDataSetChanged does not work in adapter in kotlin - java

There is a delete button on my recylerview item when I click it I m showing a alert dialog when I click yes button I want to refresh my recylerview but I could'not. I call directly notifyDataSetChanged in adapter at the end of the my code but it does not work.
MyAlertDialog(In my adapter)
mAlertDialog.setPositiveButton("Yes") { dialog, id ->
val databaseHandler: DBHelper = DBHelper(holder.itemView.context)
val removedMed = Medicine(id = medicine.id,name = medicine.name,amount = medicine.amount,description = medicine.description)
databaseHandler.deleteMedicine(removedMed)
dialog.dismiss()
notifyDataSetChanged()
}
Mainactivity
class MainActivity : AppCompatActivity() {
private var adapter: MedicineAdapter? = null
private var medicineList : ArrayList<Medicine> = arrayListOf()
private var recyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getDataFromDb()
}
fun getDataFromDb(){
val context = this
val db = DBHelper(context)
recyclerView = findViewById<View>(R.id.recyclerView) as RecyclerView
adapter = MedicineAdapter(this, db.readData())
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
// set the adapter
recyclerView!!.adapter = adapter
adapter!!.notifyDataSetChanged()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.addBtn -> {
val intent = Intent(this,AddNewMedicine::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
getDataFromDb()
}
}
MedicineAdapter
class MedicineAdapter(
private val mainActivity: MainActivity,
val medicineList: ArrayList<Medicine>)
: RecyclerView.Adapter<MedicineAdapter.ListItemHolder>(){
override fun onCreateViewHolder(
parent: ViewGroup, viewType: Int): ListItemHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.medicine_items, parent, false)
return ListItemHolder(itemView)
}
inner class ListItemHolder(view: View) :
RecyclerView.ViewHolder(view),
View.OnClickListener {
internal var name = view.findViewById<TextView>(R.id.name)
internal var amount = view.findViewById<TextView>(R.id.amount)
internal var description = view.findViewById<TextView>(R.id.description)
internal var deleteButton = view.findViewById<ImageButton>(R.id.deleteBtn)
internal var editButton = view.findViewById<ImageButton>(R.id.editBtn)
init {
view.isClickable = true
view.setOnClickListener(this)
deleteButton.setOnClickListener(this)
editButton.setOnClickListener(this)
}
override fun onClick(view: View) {
//val intentToCarPager = Intent(view!!.context, CarPagerActivity::class.java)
//view.context.startActivity(intentToCarPager)
}
}
override fun onBindViewHolder(holder: ListItemHolder, position: Int) {
val medicine = medicineList!![position]
holder.name.text = medicine.name
holder.amount.text = medicine.amount
holder.description.text = medicine.description
holder.deleteButton.setOnClickListener {
val mAlertDialog = AlertDialog.Builder(holder.itemView.context)
mAlertDialog.setTitle("Are you sure you want to this record!") //set alertdialog title
mAlertDialog.setPositiveButton("Yes") { dialog, id ->
val databaseHandler: DBHelper = DBHelper(holder.itemView.context)
val removedMed = Medicine(id = medicine.id,name = medicine.name,amount = medicine.amount,description = medicine.description)
databaseHandler.deleteMedicine(removedMed)
notifyDataSetChanged()
dialog.dismiss()
medicineList.removeAt(position)
notifyItemRemoved(position)
}
mAlertDialog.setNegativeButton("No") { dialog, id ->
}
mAlertDialog.show()
}
holder.editButton.setOnClickListener {
val dialog = UpdateMedicine(medicine)
val manager = (holder.itemView.context as MainActivity).supportFragmentManager
dialog.show(manager,"")
}
}
override fun getItemCount(): Int {
if (medicineList != null) {
return medicineList.size
}
return -1
}
}

I solved my problem by removing the object from the array
notifyDataSetChanged()
dialog.dismiss()
medicineList.removeAt(position)
notifyItemRemoved(position)

Related

How do I show an admop interstitial ad after number of clicks on the item-views of recyclerview?

In some apps that are similar to my app, they have this thing when the user clicks on the item views of the recycler view randomly for 3 or 4 times and it displays an Admob interstitial ad for them before moving to the next activity or fragment. I would like to do the same, like showing the ad for the user after he clicks randomly for 3 or 4 times on the item views and when the ad is closed it should move to the next fragment. How do I do this kind of idea?
P.C. I am using navigation components to navigate between the fragments and you can use java or kotlin, I understand them both.
**Here is my recycler view code **
class NewsListAdapter(
val context: Context,
val news_list: ArrayList<NewsListViewModel>,
val view: View
) :
RecyclerView.Adapter<NewsListAdapter.vHolder>() {
var inum = 1
var countNum = 0
private lateinit var OverLoad: OverLoad
private lateinit var mRef: DatabaseReference
private var mInterstitialAd: InterstitialAd? = null
private final var TAG = "NewsListAdapter"
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): vHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.news_list_design, parent, false)
return vHolder(view)
}
override fun getItemCount(): Int {
return news_list.size
}
override fun onBindViewHolder(holder: vHolder, position: Int) {
val newsList = news_list[position]
val image = newsList!!.image
val imageView = holder.news_image
Glide.with(this.context)
.load(image)
.into(imageView)
holder.news_title.text = newsList.title
holder.news_desc.text = newsList.desc
holder.news_date.text = newsList.date
holder.news_type.text = newsList.type
val shared = context.getSharedPreferences("LatestNewsSaving", Context.MODE_PRIVATE)
val editor = shared.edit()
editor.putInt("fav_blue", R.drawable.ic_favorite_blue)
editor.putInt("fav_border", R.drawable.ic_favorite_border)
// editor.putInt("count_newsList_num", countNum)
editor.apply()
interstitialAd()
PushDownAnim.setPushDownAnimTo(holder.card_view)
.setOnClickListener {
countNum += 1
editor.putInt("count_newsList_num", countNum)
editor.apply()
if (shared.getInt("count_newsList_num", 0) == 3) {
countNum = 0
if (mInterstitialAd != null) {
mInterstitialAd?.show(context as Activity)
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.")
}
val passData = LatestNewsFragmentDirections
.actionLatestNewsFragmentToNewsDetailFragment(news_list[position])
Navigation.findNavController(view).navigate(passData)
} else {
val passData = LatestNewsFragmentDirections
.actionLatestNewsFragmentToNewsDetailFragment(news_list[position])
Navigation.findNavController(view).navigate(passData)
}
}
}
fun interstitialAd() {
var adRequest = AdRequest.Builder().build()
InterstitialAd.load(context, "ca-app-pub-xxxxxxxxxxxxxxxxx", adRequest, object :
InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.d(TAG, adError?.message)
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.d(TAG, "Ad was loaded.")
mInterstitialAd = interstitialAd
}
})
}
class vHolder(view: View) : RecyclerView.ViewHolder(view) {
val news_image = view.findViewById<ImageView>(R.id.news_image)
val news_title = view.findViewById<TextView>(R.id.news_title)
val news_desc = view.findViewById<TextView>(R.id.news_desc)
val news_date = view.findViewById<TextView>(R.id.news_date)
val news_type = view.findViewById<TextView>(R.id.news_type)
val card_view = view.findViewById<CardView>(R.id.newsListCard)
val favourite_add = view.findViewById<ImageView>(R.id.favourites_add)
}
}

How to save data from RecyclerView (ArrayList) with Kotlin?

I have a RecyclerView created in Kotlin and would like to save the data from the RecyclerView (the ArrayList) for example with GSON Libary. I've already searched a lot but can't find a working solution. Here's my current code: (without saving function)
MainActivity.kt:
class MainActivity : AppCompatActivity(), ExampleAdapter.OnItemClickListener {
private val exampleList = generateDummyList(500)
private val adapter = ExampleAdapter(exampleList, this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recycler_view.adapter = adapter
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.setHasFixedSize(true)
}
fun insertItem(view: View) {
val index = Random.nextInt(8)
val newItem = ExampleItem(
R.drawable.ic_android,
"New item at position $index",
"Line 2"
)
exampleList.add(index, newItem)
adapter.notifyItemInserted(index)
}
fun removeItem(view: View) {
val index = Random.nextInt(8)
exampleList.removeAt(index)
adapter.notifyItemRemoved(index)
}
override fun onItemClick(position: Int) {
Toast.makeText(this, "Item $position clicked", Toast.LENGTH_SHORT).show()
val clickedItem = exampleList[position]
clickedItem.text1 = "Clicked"
adapter.notifyItemChanged(position)
}
private fun generateDummyList(size: Int): ArrayList<ExampleItem> {
val list = ArrayList<ExampleItem>()
for (i in 0 until size) {
val drawable = when (i % 3) {
0 -> R.drawable.ic_android
1 -> R.drawable.ic_audio
else -> R.drawable.ic_sun
}
val item = ExampleItem(drawable, "Item $i", "Line 2")
list += item
}
return list
}
}
ExampleItem.kt:
data class ExampleItem(val imageResource: Int, var text1: String, var text2: String)
ExampleAdapter.kt:
class ExampleAdapter(
private val exampleList: List<ExampleItem>,
private val listener: OnItemClickListener) :
RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.example_item,
parent, false)
return ExampleViewHolder(itemView)
}
override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
val currentItem = exampleList[position]
holder.imageView.setImageResource(currentItem.imageResource)
holder.textView1.text = currentItem.text1
holder.textView2.text = currentItem.text2
}
override fun getItemCount() = exampleList.size
inner class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
val imageView: ImageView = itemView.image_view
val textView1: TextView = itemView.text_view_1
val textView2: TextView = itemView.text_view_2
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
interface OnItemClickListener {
fun onItemClick(position: Int)
}
}
First you need to convert you Data in to json by using json object in onBindViewHolder using
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
And if you want to save then you can use shared preferences.

Pagination Duplicating Values in RecyclerView in MVVM

I am new in Kotlin MVVM also, I tried to achieved Pagination with legacy approach and stucked in a issue with my RecyclerView, whenever I scroll it the data duplicated, I tried DiffUtils but no help.
I Logged the data in VIEWMODEL class the data is not repeating
but, when I logged in Activity where I am observing it is showing duplicate values
SEARCHRESULTACTIVITY.KT
class SearchResultActivity : AppCompatActivity() {
private lateinit var layoutManager: LinearLayoutManager
private lateinit var recyclerView: RecyclerView
private lateinit var pullAdapter: CustomAdapter
private var pageNumber = 1
private var totalItemsCount = 0
private var firstVisibleItemsCount = 0
private var visibleItemsCount = 0
private var previousTotal = 0
private var loading = true
private var fillPullList: ArrayList<RepoPull> = ArrayList()
private var userName: String = ""
private var repoName: String = ""
private var isEnd = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initialize()
getDataPull(userName, repoName)
loadNextData()
}
private fun initialize() {
setContentView(R.layout.activity_search_result)
recyclerView = findViewById(R.id.repoRecView)
layoutManager = LinearLayoutManager(this)
getSearchQuery()
}
private fun getSearchQuery() {
userName = intent.getStringExtra("owner").toString()
repoName = intent.getStringExtra("repo").toString()
populatePullRv()
}
private fun populatePullRv() {
recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
recyclerView.layoutManager = layoutManager
pullAdapter = CustomAdapter(this, fillPullList)
recyclerView.adapter = pullAdapter
progressBar.visibility = View.VISIBLE
}
private fun loadNextData() {
recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val mLayoutManger = recyclerView.layoutManager as LinearLayoutManager
visibleItemsCount = mLayoutManger.childCount
totalItemsCount = mLayoutManger.itemCount
firstVisibleItemsCount = mLayoutManger.findFirstVisibleItemPosition()
if (loading) {
if (totalItemsCount > previousTotal) {
previousTotal = totalItemsCount
pageNumber++
loading = false
progressBar.visibility = View.GONE
}
}
if (!loading && (firstVisibleItemsCount + visibleItemsCount) >= totalItemsCount) {
getDataPull(userName, repoName)
loading = true
Log.d("PAGE", pageNumber.toString())
}
}
})
}
private fun getDataPull(username: String?, reponame: String?) {
val myViewModel = ViewModelProviders.of(this).get(PullVM::class.java)
myViewModel.endofList.observe(this, {
if (it == true) {
isEnd = true
progressBar.visibility = View.GONE
Toast.makeText(this#SearchResultActivity, "All PR Fetched", Toast.LENGTH_SHORT)
.show()
}
})
myViewModel.status.observe(this, {
if (it == false) {
showError(getString(R.string.no_net))
}
})
myViewModel.getPullDataFromVM().observe(this, {
if (it != null) {
listRepos(it) **//DUPLICATE VALUE COMING**
} else {
showError(getString(R.string.nothing_found))
}
})
myViewModel.getPullList(username.toString(), reponame.toString(), pageNumber)
}
private fun showError(s: String) {
progressBar.visibility = View.GONE
val theView =
this#SearchResultActivity.findViewById<View>(android.R.id.content)
Snackbar.make(
theView,
s,
Snackbar.LENGTH_LONG
).show()
}
#SuppressLint("NotifyDataSetChanged")
fun listRepos(repos: List<RepoPull>) {
if (!isEnd) {
progressBar.visibility = View.GONE
fillPullList.addAll(repos)
pullAdapter.notifyDataSetChanged()
}
}}
PULLVM(View Model).kt
class PullVM : ViewModel() {
var pullList: MutableLiveData<List<RepoPull>>
var status = MutableLiveData<Boolean?>()
var endofList = MutableLiveData<Boolean?>()
init {
pullList = MutableLiveData()
}
fun getPullDataFromVM(): MutableLiveData<List<RepoPull>> {
return pullList
}
fun getPullList(ownerName: String, repoName: String, pgNo: Int) {
val retriever = GitHubRetriever
val callback = object : Callback<List<RepoPull>> {
override fun onFailure(call: Call<List<RepoPull>>, t: Throwable) {
status.value = false
}
override fun onResponse(
call: Call<List<RepoPull>>,
response: Response<List<RepoPull>>
) {
if (response.body()?.size == 0) {
endofList.value = true
}
if (response.code() == 404) {
pullList.postValue(null)
} else {
status.value = true
val repos = response.body()
if (repos != null) {
pullList.postValue(repos)
}
}
}
}
retriever.userRepos(
callback,
ownerName,
repoName,
pgNo
)
}
Try moving your viewModel instantiation and observer settings to onCreate so you don't have to create a new viewModel instance and set a new observable to your LiveDatas.
Declare myViewModel as a lateinit property of your Activity and move this part to onCreate
myViewModel = ViewModelProviders.of(this).get(PullVM::class.java)
myViewModel.endofList.observe(this, {
if (it == true) {
isEnd = true
progressBar.visibility = View.GONE
Toast.makeText(this#SearchResultActivity, "All PR Fetched", Toast.LENGTH_SHORT)
.show()
}
})
myViewModel.status.observe(this, {
if (it == false) {
showError(getString(R.string.no_net))
}
})
myViewModel.getPullDataFromVM().observe(this, {
if (it != null) {
listRepos(it) **//DUPLICATE VALUE COMING**
} else {
showError(getString(R.string.nothing_found))
}
})
And
private fun getDataPull(username: String?, reponame: String?)
should only contain
myViewModel.getPullList(username.toString(), reponame.toString(), pageNumber)

Java/Kotlin. No adapter attached; skipping layout. I dont know why i have this error

I Have NetworkRecycler class.I just want to show data to my textviews from server. I use retrofit library. In log i have error message: No adapter attached; skipping layout. Sorry for me English guys. This is my MainActivity class:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://developers.themoviedb.org/")
.build()
val json = retrofit.create(JsonPlaceHolder::class.java)
val call = json.getNetworkId(3)
call.enqueue(object: Callback<List<Network>> {
override fun onResponse(call: Call<List<Network>>, response: Response<List<Network>>) {
val network = response.body()
val networkRecycler = NetworkRecycler(network!!)
recyclerView.apply {
layoutManager = linearLayoutManager
adapter = networkRecycler
}
}
override fun onFailure(call: Call<List<Network>>, t: Throwable) {
Log.e("MainActivity", "${t.message}")
}
})
}
And this is my NetworkRecycler class:
class NetworkRecycler(private val list: List<Network>): RecyclerView.Adapter<NetworkRecycler.ViewHolder(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val network = list[position]
holder.headquarters.text = network.headquarters
holder.homepage.text = network.homepage
holder.id.text = network.id.toString()
holder.name.text = network.name
holder.originCountry.text = network.origin_country
}
override fun getItemCount(): Int = list.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val headquarters : TextView = itemView.findViewById(R.id.headquarters)
val homepage : TextView = itemView.findViewById(R.id.homepage)
val id : TextView = itemView.findViewById(R.id.textId)
val name : TextView = itemView.findViewById(R.id.name)
val originCountry : TextView = itemView.findViewById(R.id.origin_country)
}
}
Finally my Network class:
data class Network(
val headquarters: String,
val homepage: String,
val id: Int,
val name: String,
val origin_country: String
)
You need to set your recyclerView with adapter first, then change the adapter when get the response. This code below may be work.
//define adapter with empty list
var networkRecycler = NetworkRecycler(ArrayList<Network>())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
//set your adapter here
recyclerView.apply {
layoutManager = linearLayoutManager
adapter = networkRecycler
}
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://developers.themoviedb.org/")
.build()
val json = retrofit.create(JsonPlaceHolder::class.java)
val call = json.getNetworkId(3)
call.enqueue(object: Callback<List<Network>> {
override fun onResponse(call: Call<List<Network>>, response: Response<List<Network>>) {
val network = response.body()
networkRecycler = NetworkRecycler(network!!)
//refresh recycler view
adapter.notifyDataSetChanged();
}
override fun onFailure(call: Call<List<Network>>, t: Throwable) {
Log.e("MainActivity", "${t.message}")
}
})
}

Fragment not showing in the Main Screen [duplicate]

This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 5 years ago.
I am creating a music player and I have made some fragments for this. I am using Main Screen Fragment which shows the list of the songs in the device. But when I am trying to open the app it is showing me a blank screen. I also attached this fragment to All songs option in my recycler view, again when I am clicking on the All songs option it is showing me the blank screen. What is the problem, where I am missing something.
here is the code of my MainActivity.kt file and MainScreenFragment.kt File.
MainActivity.kt
class MainActivity : AppCompatActivity(){
var navigationDrawerIconList : ArrayList<String> = arrayListOf()
var images_for_navdrawer = intArrayOf(R.drawable.navigation_allsongs, R.drawable.navigation_favorites,
R.drawable.navigation_settings, R.drawable.navigation_aboutus)
object Statified{
var drawerLayout : DrawerLayout?=null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
MainActivity.Statified.drawerLayout=findViewById(R.id.drawer_layout)
// drawerLayout=findViewById<DrawerLayout>(R.id.drawer_layout) as DrawerLayout
navigationDrawerIconList.add("All Songs")
navigationDrawerIconList.add("Favorites")
navigationDrawerIconList.add("Settings")
navigationDrawerIconList.add("About Us")
val toggle = ActionBarDrawerToggle(this#MainActivity, MainActivity.Statified.drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close)
MainActivity.Statified.drawerLayout?.setDrawerListener(toggle)
toggle.syncState()
val mainScreenFragment = MainScreenFragment()
this.supportFragmentManager
.beginTransaction()
.add(R.id.details_fragment, mainScreenFragment, "MainScreenFragment")
.commit()
//Navigation Drawer
var _navigationAdapter = NavigationDrawerAdapter(navigationDrawerIconList, images_for_navdrawer, this#MainActivity)
_navigationAdapter.notifyDataSetChanged()
var navigation_recycler_view = findViewById<RecyclerView>(R.id.navigation_recycler_view)
navigation_recycler_view.layoutManager = LinearLayoutManager(this#MainActivity)
navigation_recycler_view.itemAnimator = DefaultItemAnimator()
navigation_recycler_view.adapter = _navigationAdapter
navigation_recycler_view.setHasFixedSize(true)
// var navigation_recycler_view = findViewById<RecyclerView>(R.id.navigation_recycler_view)
//navigation_recycler_view.layoutManager = LinearLayoutManager(this)
//navigation_recycler_view.itemAnimator = DefaultItemAnimator()
}
override fun onStart() {
super.onStart()
}
}
MainScreenFragment.kt
class MainScreenFragment : Fragment() {
var getSongList : ArrayList<Songs>? = null
var nowPlayingBottomBar: RelativeLayout?=null
var playPauseButton: ImageView?=null
var songTitle: TextView?=null
var visibleLayout: RelativeLayout?=null
var noSongs: RelativeLayout?=null
var recyclerView: RecyclerView?= null
var myActivity:Activity?=null
var _mainScreenAdapter : MainScreenAdapter?=null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.content_main, container, false)
setHasOptionsMenu(true)
activity.title = "All songs"
visibleLayout = view?.findViewById<RelativeLayout>(R.id.visibleLayout)
noSongs = view?.findViewById<RelativeLayout>(R.id.noSongs)
nowPlayingBottomBar = view?.findViewById<RelativeLayout>(R.id.hiddenBarMainScreen)
songTitle = view?.findViewById<TextView>(R.id.songTitleMainScreen)
playPauseButton = view?.findViewById<ImageButton>(R.id.playpauseButton)
(nowPlayingBottomBar as RelativeLayout).isClickable = false
recyclerView = view?.findViewById<RecyclerView>(R.id.contentMain)
if (getSongList == null) {
getSongList = getSongsFromPhone()
if (getSongList == null) {
visibleLayout?.visibility = View.INVISIBLE
noSongs?.visibility = View.VISIBLE
}
} else {
Log.d(MainScreenFragment::class.java.simpleName, " Data already there")
}
getSongList = getSongsFromPhone()
_mainScreenAdapter = MainScreenAdapter(getSongList as ArrayList<Songs>, activity)
val mLayoutManager = LinearLayoutManager(activity)
(recyclerView as RecyclerView).layoutManager = mLayoutManager
(recyclerView as RecyclerView).itemAnimator = DefaultItemAnimator()
(recyclerView as RecyclerView).adapter = _mainScreenAdapter
return view
// Inflate the layout for this fragment
/* val view = inflater!!.inflate(R.layout.fragment_main_screen, container, false)
visibleLayout = view?.findViewById<RelativeLayout>(R.id.visibleLayout)
noSongs = view?.findViewById<RelativeLayout>(R.id.noSongs)
nowPlayingBottomBar = view?.findViewById<RelativeLayout>(R.id.hiddenBarMainScreen)
songTitle = view?.findViewById<TextView>(R.id.songTitleMainScreen)
playPauseButton = view?.findViewById<ImageButton>(R.id.playPauseButton)
recyclerView = view?.findViewById<RecyclerView>(R.id.contentMain)
return view*/
}
fun getSongsFromPhone(): ArrayList<Songs>{
var arrayList = ArrayList<Songs>()
var contentResolver = myActivity?.contentResolver
var songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
var songCursor = contentResolver?.query(songUri, null, 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 dateIndex = songCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)
while(songCursor.moveToNext()){
var currentId = songCursor.getLong(songId)
var currentTitle = songCursor.getString(SongTitle)
var currentArtist = songCursor.getString(songArtist)
var currentData = songCursor.getString(songData)
var currentDate = songCursor.getString(dateIndex)
}
}
return arrayList
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
getSongList = getSongsFromPhone()
_mainScreenAdapter = MainScreenAdapter(getSongList as ArrayList<Songs>, myActivity as Context)
val mLayoutManager = LinearLayoutManager(myActivity)
recyclerView?.layoutManager = mLayoutManager
recyclerView?.itemAnimator = DefaultItemAnimator()
recyclerView?.adapter = _mainScreenAdapter
}
override fun onAttach(context: Context?) {
super.onAttach(context)
myActivity = context as Activity
}
override fun onAttach(activity: Activity?) {
super.onAttach(activity)
myActivity = activity
}
}
here is an abstract
private void setUpRecycler() {
noteAdapter = new NoteAdapter(noteModelList, v.getContext());
layoutManager = new LinearLayoutManager(v.getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(v.getContext(), DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(noteAdapter);
}
//now when you load data,call again
noteAdapter = new NoteAdapter(noteModelList, v.getContext());
recyclerView.setAdapter(noteAdapter);
noteAdapter.notifyDataSetChanged();

Categories